#templates-archived

1 messages ยท Page 114 of 1

cinder ore
#

under file editor i edited /config/configuration.yaml adding sensor: !include sensors.yaml

#

than in the /config/sensors.yaml file I added the following line

#

- platform: template sensors: tl_mr6400_b_received_mb: friendly_name: MB Received value_template: "{{state_attr( 'sensor.tl_mr6400_b_received', 'state') }}" unit_of_measurement: MB

#

the new entity named tl_mr6400_b_received_mb is created but it would not display any value

#

I tried different value_template but everything gives me error except this one

ivory delta
#

{{ states( 'sensor.tl_mr6400_b_received') | int / 1000 }}

#

You're trying to get an attribute called 'state'. It doesn't exist.

#

State and attributes are different. They just live on the same 'object'.

cinder ore
#

ok so I simply can use states and the entity id is that right?

#

I try it.

ivory delta
#

You can also test things as you go. Look at devtools > Templates

#

There are examples in there and you can use it as a playground.

cinder ore
#

one last question, after saving the file I need to reload script and than restart hass?

ivory delta
#

Yes. But always check your config before you reload HA.

silent barnBOT
#

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

cinder ore
#

thank you i'll read that documentation

#

Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states( 'sensor.tl_mr6400_b_received') | int / 1000", None)])" in "/config/sensors.yaml", line 5, column 0

#

invalid key: "OrderedDict([("states( 'sensor.tl_mr6400_b_received') | int / 1000", None)])" in "/config/sensors.yaml", line 5, column 0

ivory delta
#

You still need to wrap it with quotes ๐Ÿ˜‰

cinder ore
#

thank you mono..

#

ok I did it

#

value_template: "{{ (states( 'sensor.tl_mr6400_b_received') | float / 1000000) | round(2) }}"

#

thank you!!!

deft timber
#

FYI you don't need to reboot ha. You can go in the Control Server screen and refresh the template entities

#

and to be accurate you should do /1024/1024instead of /1000000 ๐Ÿ™‚

ivory delta
#

Depends if you want Mibi or Mega... ๐Ÿ˜‰

#

Source was Kibi

deft timber
#

Indeed, the source is in Kb/s but the template sensor is in Mb, you may change have to change to make it more consistent @cinder ore

cinder ore
deft timber
#

No. In the Control Server screen you have the possibility to update the configuration of some configuration elements. Template sensors is one of the elements you can refresh w/o a restart

cinder ore
#

I only have "Server Management -> Restart / Stop "

ivory delta
#

Go to your user profile in the bottom left and enable advanced mode.

cinder ore
#

ah ok thanks

night mural
#

Any templating wizards that know why the name_template does not parse in Lovelace but it does in the Templating Editor (I have the card-templater installed and working). I based this code on the examples on the card-templater Github ๐Ÿ˜•
`---
card:
entities:
- input_boolean.pvgrafiek
name_template: {{ "On" if states('input_boolean.pvgrafiek') == "on" else "Not One" }}
tap_action:
action: toggle
type: button
entities:

  • input_boolean.pvgrafiek
    type: "custom:card-templater"
    `
#

(I want other text than On or Off, I just use this as a test-

ivory delta
#

Well that's invalid YAML, for a start.

#

You need to escape single line templates with quotes.

night mural
#

yes, but i'm not yaml savvy enough, yet

#

single or double quotes?

ivory delta
#

Doesn't matter, which is why I didn't specify.

#

But you'll also need to sort out the mixed quotes you're currently using ๐Ÿ˜‰

night mural
#

so this is better? '{{ 'On' if states('input_boolean.pvgrafiek') == 'on' else 'Not One' }}'

ivory delta
#

Nope. Think about it... it'll read from left to right. When it sees the second quote, it means that string is finished.

#

The 'outside' quotes need to be different from the 'inside' quotes.

night mural
#

ow, ok

#

so line this? "{{ 'On' if states('input_boolean.pvgrafiek') == 'on' else 'Not One' }}"

#

like*

#

Ok, now it works, thank you for your help

#

I'm used to C and Java escaping/quotes and YAML requires different thinking ๐Ÿ˜†

nocturne chasm
#

@wispy bane and @deft timber , there should be a link to update the docs on github on the docs page. Please do if you notice a discrepancy

hexed galleon
#

Is it possible to reference blueprint !input variables within templates? Or do you have to go a bit more long-winded and define them as variables first?

deft timber
#

@hexed galleon you have to define a variable first

cedar wigeon
#

I want a REST sensor to provide the following in to sensors, how do I do this?
The first mnt_point -> free
The first mnt_point -> used

curl --x http://10.0.24.11:61208/api/3/fs [{"mnt_point": "/", "fs_type": "ext4", "free": 11258875904, "key": "mnt_point", "size": 15247720448, "percent": 22.8, "used": 3318775808, "device_name": "/dev/root"}, {"mnt_point": "/boot", "fs_type": "vfat", "free": 223278592, "key": "mnt_point", "size": 264289792, "percent": 15.5, "used": 41011200, "device_name": "/dev/mmcblk0p1"}] C:\Users\Administrator\Downloads\curl-7.74.0_2-win64-mingw\curl-7.74.0_2-win64-mingw\bin>

deft timber
#

Define a restful sensor and in value_template:, set something like "{{ value_json[0].free }}" and another one with "{{ value_json[0].used }}" (assuming the order will always be the same in your json)

cedar wigeon
#

Thanks @deft timber ๐Ÿ™‚ It works.
Yeah, I can make two sensors like that.
But is there a way to do this with just one API-call? To reduce the API-traffic

deft timber
#

Yes you can, and you can set the result of the call in the attributes of your sensor

cedar wigeon
#

Do you have a recipe for that?

deft timber
cedar wigeon
#

thanks (Y)

brisk nebula
#

Hello everyone, I need some help with manipulating dates in templates.

#

I have an initial date, say "2021-1-5 00:00:00". Now I would like to add datedelta(days=7) to it.

#

timedelta, sorry

cedar wigeon
#

And one (two) more questions @deft timber :P

  1. Can I in any way get attributes from both [0] and [1] in json_attributes, I guess not for what google tell, but is there a way or do I just need to make more calls then?
  2. Can give my attributes a custom attribut name?

Anyway, my working sensor:
- platform: rest resource: http://10.0.24.11:61208/api/3/fs name: Glances - DeCONZ - Disk - all value_template: '{{ value_json[0] }}' json_attributes: - free - used

deft timber
#

I'm actually surprised your config works ๐Ÿ™‚ I would expect the json_attributes to use path from the result of the REST call, not from the value_template result, and thus I'm surprise that the path used for the json_attributes works...

#

so I can't answer you first question...

#

I don't think you can custom the attributes names

ivory delta
#

You'd have to use multiple sensors to have the freedom to name them all the way you want.

deft timber
#

apparently, if you just set free as an attribute, HA will get the free of the first element of the collection. If you want the free of the second, you need to set json_attributes_path: '$[1]'

#

So the conclusion is indeed that you can't get the free from the first and the second element of the collection in the same sensor

cedar wigeon
#

@deft timber, can you give me the whole rest-sensor I need? I have tried all kinds of combinations, but whatever I do, If i use json_attributes_path in any way the entity vanish

deft timber
#

This is what I used to test :

  - platform: rest
    resource: http://192.168.0.175/test.json
    name: test json
    value_template:  '{{ "ok" }}'
    json_attributes_path: '$[1]'
    json_attributes:
      - free
cedar wigeon
#

worked when I copyed that .. :P
I missed '{{ "ok" }}'
Can "ok" be a value, or just whatever I want? Else ok i ok

deft timber
#

it is the value of your sensor, you can choose whatever you want. Hard code or get it from the json as you did.

haughty pond
#

Hi
Can someone point me to why this isn't this working:
service: rest_command.creeper_msg data: icon: ALARM msg: '{{ state_attr(''sensor.hd1913_last_notification'', ''android.text'') }}' val: '0'
It's just sending through the code of msg instead of fetching the text from last_notification?

arctic sorrel
#

Because android.text isn't an attribute ๐Ÿ˜‰

#

Test it in devtools -> Templates

haughty pond
#

Hm.. I saw another guy using it that way directly in his automation, so I tried to do the same.

#

But I guess, that's not possible?

#

But android.text is an attribute of last_notification?

arctic sorrel
#

Try it

#

devtools -> Templates

haughty pond
#

Well, got it working in Templates using this code:
'{{ state_attr('sensor.hd1913_last_notification', 'android.text') }}'

#

Now it fetches what I want to, but how do I now get it into the actual automation?

arctic sorrel
#

Then the template is good, and you need to check your log file for any errors, also check the recipient of that REST command to see what it received

haughty pond
#

Well, I get a visual of what's recieved everytime I run it

ivory delta
#

I think it's sending the unevaluated template.

haughty pond
#

Exactly

ivory delta
#

Which suggests that service doesn't support templates. At least not via the Dev Tools.

#

Where are you trying it?

haughty pond
#

I use the REST command to send it to an arduino which outputs the text on an OLED so I can see it all time displaying what I just sent

#

In an automation in my service for a rest command

#

REST:
creeper_msg: url: "http://192.168.1.124:80/DisplayMessage?message={{ msg }}&icon={{ icon }}&value={{ val }}" method: POST payload: 'Testing it' verify_ssl: false

ivory delta
#

And it's when you use it as part of the automation that it doesn't work?

haughty pond
#

Action in automation:
service: rest_command.creeper_msg data: icon: ALARM msg: '{{ state_attr('sensor.hd1913_last_notification', 'android.text') }}' val: '0'

ivory delta
#

Triple backticks for better formatting ๐Ÿ˜‰

haughty pond
#

No, icon and val works fine as intended. But the msg part just sends the unevaluated text as you said.

#

Ok ๐Ÿ™‚

#
data:
  icon: ALARM
  msg: '{{ state_attr('sensor.hd1913_last_notification', 'android.text') }}'
  val: '0'```
ivory delta
#

Hmm. The docs don't describe POST requests.

#

Is it possible to use payload: instead of query params?

haughty pond
#

Well.. I guess that would need me to redo my Arduino code as well I'm guessing

#

Since that won't be sent the same way right?

ivory delta
#

It'll be different... but some middlewares interpret it the same. If you're coding everything from scratch, you'll have to handle that change.

haughty pond
#

Coding from scratch so... ๐Ÿ™‚

#

There's no way to make it work like I tried to you're guessing?

ivory delta
#

Just as a quick test, move those params into a payload and log out the request in your code.

#

If the template evaluates correctly, do it that way instead.

#

It's more common to have a request body with a POST than to have a string of query params anyway.

haughty pond
#

Will have to try it later on in that case since I need to reboot HA etc. to do change the payload.

#

Running off in like 3 min

#

But will take it into advice!

silent barnBOT
haughty pond
#

You see how he uses it in his action?

ivory delta
#

Different integration, different rules.

haughty pond
#

I see...

ivory delta
#

It might appear on the surface that there's a common way to do things. Underneath, it's not that simple.

haughty pond
#

As it always is then. ๐Ÿ™‚

ivory delta
#

If you're comfortable with code, you can take a look at the Python code for the rest_command integration to see how it works.

haughty pond
#

Gotta run off, but I'll get back to trying later, thanks for your input.

haughty pond
#

@ivory delta , you there?

#

Got it working. Had to do this.

#
data:
  icon: ALARM
  val: '0'
data_template:
  msg: '{{ state_attr(''sensor.hd1913_last_notification'', ''android.text'') }}'```
ivory delta
#

Oh, weird. Most integrations switched to not needing _template a while back.

#

Glad you solved it.

molten scroll
#

value_template: "{{ states('luxtronik.VV_aanvoer')|int - states('luxtronik.VV_retour')|int }}" 

#

Can I make this float ? By simply replacing int with float?

#

The input values are xx,y

#

I don't what to lose the precision

ivory delta
#

Yes

deft timber
#

if it doesn't work you maybe have to replace the ',' with a '.'

#

states('luxtronik.VV_aanvoer') |ย regex_replace(",", ".") | float

ivory delta
#

If it's already working with | int does that not mean it's already handling the comma? I've never tried these fancy European numbers.

#

Ah, it won't work with | int either ๐Ÿคฃ

molten scroll
#

Well it showed one crazy number, let's hope it doesn't do that again

#

It shows it american style by the way, with a .

#

I would need the regex to make it a , but idc

hexed galleon
#

Hi all, if I were to create a template sensor using relative_time function, how would I get it to update? It seems to only update on HA start/restart. Here's my sensor format: "{{ relative_time(strptime(states.input_datetime.worm_timer.state, '%Y-%m-%d')) }}"

ivory delta
#

Templates update when any of the entities they reference update.

serene mortar
#

Well I guess if you use {% set dummy = now() %} you can force it to update every minute

wet lodge
#

Hey folks... Need some help. I copied some code from a forum post and adapted it for my own use. Here's what I have:
{% set ns = namespace(res=0) %} {% for light in state_attr('group.all_lights', 'entity_id') if is_state(light, 'on') %} {% set ns.res = ns.res + 1 %} {%endfor%} {{ ns.res +1 }} lights on | {% set ns = namespace(res=0) %} {% for light in state_attr('group.all_rooms', 'entity_id') if is_state(light, 'on') %} {% set ns.res = ns.res + 1 %} {%endfor%} {{ ns.res }} rooms
It works correctly except one weird quirk. I'm getting a bunch of extra spaces between the pipe and the number of rooms. This only seems to happen when I have more than one of these loops in a single template. Any help is appreciated.

outer shell
#

hello, I cant find information about the related entities tab. am I somehow able to link two entities together so they appear in eatch others tab ?

hexed galleon
ivory delta
#

The answer was already given.

#

And don't tag people for help.

silent barnBOT
#

Generally, don't tag people to ask for help - it comes across as bad manners, youโ€™re demanding somebody answers you. Itโ€™s different if youโ€™re thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.

Similarly, please donโ€™t DM (direct message) people asking for help. It also comes across as demanding, and means that others canโ€™t learn from what you do.

Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).

hexed galleon
#

Sorry, was a reply - not a tag. I just believe the reply function auto-tags people ๐Ÿ˜ฆ

ivory delta
hexed galleon
#

Yeah, just saw that. TIL! Thanks ๐Ÿ™‚

ivory delta
#

If not, add the date time integration and decide for yourself how granular you need it by referencing one of the entities it creates in your template.

#

Same idea... something has to update for the template to be re-evaluated.

hexed galleon
#

Thanks. Will take a look at both options.

glass jasper
#

what's wrong with this code? it's copied from the forum and should work, yet it doesn't and I don't see the minutes senor in my entities (the firbit sensor works) https://hastebin.com/hevujatoyi.yaml

hollow sierra
#

hey how do i make a slider entity so i can set a slider on the front end that i can read back using node red

#
  • platform: template
    sensors:
    zone_1_duration:
    name: Zone 1 Manual Time
    icon: mdi:timer-sand
    initial: 30.00
    min: 0
    max: 55
    step: 5
#

thats what i had but it wasnt working

hollow sierra
#

but then how would node red see that @hexed galleon

#

because AFAIK it needs to be an entity

mighty ledge
#

@hollow sierra take the convo to #integrations-archived. And @hexed galleon is correct. Input number is what you need. There's also a #node-red-archived channel that can probably help you with everything you need.

#

Also, what y ou posted is not a template sensor. It's a mix of a template sensor and input_number, which is why it's not working. Most of those configuration fields you configured are not valid template sensor fields.

#

In fact, every field under zone_1_duration is incorrect

hollow sierra
#

i took it from someone elses project

cedar wigeon
#

Why is this sensor showing
"322,80078125 MB" when i use round?

glances_deconz_ram_used_mb: friendly_name: "Glances - DeCONZ - RAM Used" unit_of_measurement: "MB" value_template: '{{ state_attr("sensor.glances_deconz_RAM", "used") | float / 1048576 | round(0) }}'

#
  • platform: template btw
ivory delta
#

Order of operations:
1048576 | round(0)

#

You're rounding that, then dividing by the result.

#

You probably want this:
{{ (state_attr("sensor.glances_deconz_RAM", "used") | float / 1048576) | round(0) }}

cedar wigeon
#

Aha, so that is how i works, tanks.

fossil hearth
#

hi ! ๐Ÿ™‚ hi this is a template sensor, i want to tell it if the temperature is above 27 for more then 2 hours that means its off.
{(states.sensor.H1.state) ) > 27 for more then 2 hours}} how to do this ? :)
unless automatons can change states then ill use numeric state automation

fossil hearth
#

@nocturne chasm but its actually a sensor not an automation

#

template sensor..

nocturne chasm
#

But you setup a sensor to monitor something and then use an automation to tell you when it goes above 27 for 2 hours

fossil hearth
#

@nocturne chasm i want it to be an actual sensor..

#

@nocturne chasm how can i display it in lovlace with an icon if its an automation and i want to give it a couple of attributes

#

if the automation can change state.. then it changes everything

ivory delta
#

I don't know if you can do it with a single sensor. You could make a template binary sensor that tests if it's over 27, then wrap that in another sensor that checks that the last updated time of the first one is at least 2 hours.

#

If you're also going to use this information in any automations, I'd recommend having automations that toggle an input boolean after 2 hours, then just show the state of the input boolean (wrap this in a template sensor if you want to do something else with it).

fossil hearth
#

aha or maybe i can use automation and mark it as mqtt and send payloads to change ?

ivory delta
#

You don't need MQTT for this. Everything you described is inside HA.

fossil hearth
#

nice

#

โค๏ธ

ivory delta
#

threshold sensor also lets you use hysteresis so you can handle fluctuations.

fossil hearth
#

true okey ill see what i can do thanks ๐Ÿ˜„

#

but threshold doesn't have time right ?

#

like more then 2 hours thingy ..

ivory delta
#

Sensor 1 = threshold. Sensor 2 = has sensor 1 been true for X hours?

fossil hearth
#

got it

#

๐Ÿ™‚

#

thanks

#

100%

#

btw i noticed there is time_window: 00:05:00

#

in the sample what is that ?

#

its not explained there

ivory delta
fossil hearth
#

yeah sorry

jolly grove
#

hey guys, i need help creating a template... anyone there?

ivory delta
#

Just ask your question...

#

There are over 6000 people online. I'm sure someone can answer once they know what you're asking.

jolly grove
#

I'm trying to get the battery level and turn into a sensor, how can i do that? I haven't done this in like 1 year now.
mac: 778BF410
device_class: door
timestamp: 2020-12-30T11:27:00.692000
rssi: -70
battery_level: 101
friendly_name: Nursery

ivory delta
jolly grove
#

I was able to create the sensor, i just dont know to add the % sign

#

'''

sensor:

  • platform: template
    sensors:
    nursery_door_battery:
    value_template: "{{ state_attr('binary_sensor.wyzesense_778bf410', 'battery_level') }}"

'''

#

How do i add the % sign to the sensor?

ivory delta
#

"{{ state_attr('binary_sensor.wyzesense_778bf410', 'battery_level') }}%"?

#

Or just do it properly and learn how to customise entities with a unit of measurement.

jolly grove
#

thanks

simple tusk
#

With the help of the documentation i got my first template sensor to work
The Sensor returns Cal.Entries for garbage collections
Now i want to achieve, to change the day in the corresponding attribute to a different language.

I achieved with the help of the documentation the followinig solution. But i don't know, if there would be a better way? If Yes, please tell me :)

{% set day = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"] %}
{{day[as_timestamp(state_attr('sensor.ics_1', 'start'))-1 | timestamp_custom('%w', true) | int ]}}

#

okay, something went wrong.. i thought it works, but it does not.. i will look further into it

simple tusk
#

okay, at that point the -1 is the problem.. hm
perhaps anybody hast a small hint, where to look to further:
I can get this String Thursday, 07.01.2021
Or that String: 2021-01-07 00:07:00+01:00

I thought the second would be better, so i tried to work with Timestamp. But then its says its Friday. Which is wrong ๐Ÿ™‚

median mason
#

i want to use templates for severel button cards. like this here (https://github.com/matt8707/hass-config/issues/8). to do this I have to switch to yaml mode for lovelace? is it necessary? if i need to switch to yaml mode, then what about the resources that i added so far via gui? do i have to add them again?

serene mortar
simple tusk
simple tusk
#

now it works, but i dont know.. it feels a bit clunky in my eyes...
perhaps anybody has a further hints what i can optimize, before i use this for 20 Sensors :)

Startpoint is sensor.ics_1 which delivers a Timestamp in the following way: 2021-01-07 00:07:00+01:00
I want the weekday in German, so i build the following statement:

{% set day_array = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"] %}
{% set day = day_array[as_timestamp(state_attr('sensor.ics_1', 'start')) | timestamp_custom('%w', true) | int ] %}
{% set date = states('sensor.ics_1').split(',')[1] %}
{{ day + ',' + date}}

Output is now: Donnerstag, 07.01.2021

But i would like to get better and find the best way to get the desired result

wet lodge
#

Hi folks. Please forgive me as my Jinja2 skills are pretty amateur. Iโ€™m wondering... Is there a way to concatenate the output of some function with additional text, and perform some logic on the final result?

Hereโ€™s my use case:
I have a function that returns a number of occupied rooms. After that, I have added the word โ€œ roomsโ€. What Iโ€™d like to be able to do (without additional conditional statements) is replace instances of โ€œ1 roomsโ€ with โ€œ1 roomโ€.

Hereโ€™s what my template looks sorta looks like:
{{ function that returns a number }} rooms | replace(โ€˜1 roomsโ€™, โ€˜1 roomโ€™)

ivory delta
#

If you already have something that returns a number, use the number to decide whether you use the plural version of the word.

#

Adding the word and then trying to manipulate it is overkill.

wet lodge
#

Right. Whatโ€™s not obvious from my simplified example is that it sits within a larger structure of conditionals. I was hoping to keep that structure simple by not introducing more branches.

kind hornet
#

hi, I try to get google_say working with a template, but does not evaluate the template - based on the doc https://www.home-assistant.io/integrations/tts/ the data_template shall not be needed any more?!
without {{...}} it speaks the text fine.
entity_id: "media_player.mpd"
message: 'Temperatur betraegt {{ states.sensor.bb_aussen_temperatur.state }} Grad.'
cache: false
Any hints for me?

ivory delta
kind hornet
#

ohh - it seems that templates can not be used in the developer service page, - because i tried now to call the service via an automation, and now it works ๐Ÿ˜…

wet lodge
#

Sounds good. Can you give some advice how? Again, Iโ€™m an amateur here.

ivory delta
#

Well if you share a valid template, I'm sure someone can help adjust it.

#

What you posted above isn't valid.

wet lodge
#

Fair enough. Here is the template I have:
{% set ns = namespace(res=0) %}{% for light in state_attr('group.all_rooms', 'entity_id') if is_state(light, 'on') %}{% set ns.res = ns.res + 1 %}{%endfor%}{{ ns.res }} rooms

dreamy sinew
#

{{ 'rooms' if my_num > 1 else 'room' }}

wet lodge
#

In this example, I have a group that represents the lights in each room. If one is on, I consider that room occupied. The code to count items from a group that are on is something I copied from a forum post.

ivory delta
#

phnx, king of templating ๐Ÿ˜„

wet lodge
dreamy sinew
#

Could probably use something with expand and then maybe rejectattr to do it without a loop

serene verge
#

Looking for some templating assistance with JSON. I have an MQTT topic that will contain messages formatted like the two examples below. I have an automation for the first that works fine in interpreting the JSON and acting upon it. But the second message causes a JSONDecodeError in the from_json filter which breaks the automation. I actually don't need the automation to do anything for the second type message, I just want it to fail silently. Any way to do this? I've tried eery combination of filter and formatting I can think of.

'{"message":{"id":"A3","unit":12,"state":"on"},"protocol":"clarus_switch","length":"A3","value":"A3","repeats":2,"status":2}'

'{"message":"{\"id\":\"A3\",\"unit\":12,\"off\":1}","protocol":"clarus_switch"}'
dreamy sinew
#

Gross double json

serene verge
#

Agreed. Coming from a commercial product so can't be changed.

lone crypt
#

Ok... I think I am totally missing a few brain cells on templates.
I have a binary sensor (just a reed switch open/closed)
I want to give it a name, so I can add it to a card, and say open or closed instead of on/off

#

Am I just dreaming?

dreamy sinew
#

Need to set a device class via customize

#

Then it'll happen automagically

lone crypt
#

OMG.

#

lol

#

Now I get Was Closed, and if I disconnect, it changes to On

#

not open

dreamy sinew
#

Hmm

lone crypt
#

There

#

Had to add an icon, and reload customizations.

#

And now to add a unique ID somehow to make it available to move to an area

lone crypt
#

Anyone wanna tell me how to do that? haha

#

Now I have the sensor all like I want, but i would rather have each of the sensors in the different rooms that they are actually in

#

Probably as simple as using the groups thing right?

ivory delta
#

If you're using a Lovelace-managed dash, take control and build it just the way you want ๐Ÿ˜‰

lone crypt
#

That's just crazy talk! hahahahaha

#

Thank you @dreamy sinew Some of this stuff is super easy, then some is stupid complex. I get on thinking it's stupid complex when it's really easy sometimes.

dreamy sinew
#

Haha the only difference between the newbies and the greybeards is knowing which is which

lone crypt
#

fair enough. lol

fossil hearth
#

how to use groups in automations ? do i need to specify that its the sates that am after ?

    trigger:
      - platform: numeric_state
        entity_id: group.milkpots 
        above: 79.5
        below: 100

sample of on entity in the group

{{states.sensor.rpot1.state}} is 29.687

what wrong have i done

ps actions and services work .. i just wanted to change it to groups instead of individuals

thorny snow
#

Hi guys, happy hollydays to begin with
I just added the 17track integration to my HA
for tracking orders
it creates a sensor.seventeentrack_package_12345678 for every order added in the website. (12345678 being the actual tracking number)
one of its attributes is 'info_text' which goes 'Out For Delivery' whenever an order is going to be delivered..
I'd like to create a binary_sensor or some sensor that changes to on whenever any of my orders are out for delivery, no matter the tracking number..
any help will be much appreciated

split wharf
#

Hi guys, Trying to get my first template to work correctly. How can I correctly round this value to one decimal?
value_template: "{{ states('sensor.kitchen_sensor_temperature') | float +2 | round(1) }}"

ivory delta
#

Is it giving you more than 1 decimal place at the moment?

split wharf
#

yes

ivory delta
#

Order of operations

#

This happens first: 2 | round(1)

split wharf
#

as far as I'm reading online it rounds the +2

ivory delta
#

You need to force a different order by wrapping things in parentheses:
{{ (states('sensor.kitchen_sensor_temperature') | float + 2) | round(1) }}

#

That will round the result of the brackets instead of rounding the 2.

split wharf
#

ok, will try it again, but before that gave me an error

ivory delta
#

If it gave you an error, you made a mistake. That will work.

split wharf
#

Apparently.. I spent an hour finding a solution for an error that was caused by having platform: templates

#

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

ivory delta
#

Don't worry, it happens to all of us ๐Ÿ˜„

split wharf
#

And yeah, it now works. Thank you!

ivory delta
#

If you ignore the sensor, you're basically just doing this:

{{ 1.9999 + 2 | round(1) }} # 3.9999000000000002
{{ (1.9999 + 2) | round(1) }} # 4.0
#

Floating point math is random.

split wharf
#

Yeah, that part I understood.. I actually tried putting it in parentheses but must have misplaced them as I got the error

silent barnBOT
#

@random wing Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

Please take the time now to review all of the rules and references in #rules.

random wing
#

Seems a bit harsh, I was providing context...

#

Let me try again.

ivory delta
#

No need to post it again, it's all in the paste the bot made.

#

And rules are rules ๐Ÿคทโ€โ™‚๏ธ

#

The issue will be that, despite you casting to an int, HA will then interpret the response from the template. It's likely casting it to another data type - integrations should do their own validation and cast if necessary.

#

This may have worked in the past (there was a change that allows templates to return native types) but there are edge cases where things break as a result.

random wing
#

Yes, this makes sense. The integration service call schema looks like this:

START_WATERING_SCHEMA = SERVICE_BASE_SCHEMA.extend(
{vol.Required(ATTR_MINUTES): cv.positive_int,}
)

Is it possible to have polymorphic schema?

#

Otherwise, how else can I validate the input?

ivory delta
#

End-user support up here. Dev support down in the dev channels ๐Ÿ™‚

random wing
#

ack

molten scroll
#

How can I create a delta t graph or bar view of existing data?

nocturne chasm
somber hamlet
#

Hi, I'm trying to build a template trigger: "{{ now().strftime("%H:%M") == states.input_datetime.notificatie }}" but it doesn't trigger. Any idea what goes wrong in my thinking?

deft timber
#

first of all, states.input_datetime.notificatie is an object, not a string

#

if you want the state of that entity, you should use states.input_datetime.notificatie.state, or better, states("input_datetime.notificatie")

#

furthermore, it is a datetime with hour only, you will have seconds also

#

so it will never match "%H:%M"

#

you need to format the input_datetime as well

oak tiger
#

Not sure if correct chat. I am trying to get the same graph in my Grafana as I can see it on generic thermostat. With one line as set temperature, second line as temperature and third line as value if heater was on. I am using influxdb. Any idea what data I should send to Influxdb and how to use it?

#

Thank you.

somber hamlet
#

Thanks for your input. I will try that.

unkempt loom
#

Hey there, I have a timer for 1200 seconds. Sadly, these seconds are translated to a %-H:%M:%S (maybe %-M , didn't tested) value and provided as an attribute within the timer entity (duration).
I'd like to create a template which converts that value back to seconds.
0:20:00 should be converted to 1200 but I did not come up with a solution using jinja. Any suggestions?

karmic oar
#

This might sound silly, but how can I create a switch that I can turn on and off and it doesnt do anything but just... report itself on or off

silent barnBOT
karmic oar
#

So an input boolean and then just use a switch to turn it on or off as necessary

karmic oar
#

Seems cumbersome

ivory delta
#

So you're deliberately doing something unusual and then complaining it's hard work? ๐Ÿค”

lethal dawn
#

2 lines for backtics, and 1 line for a thanks ๐Ÿคฃ - poor guy only wrote 11 lines!

ivory delta
#

I was tagged for that? ๐Ÿค”

silent barnBOT
ivory delta
#

Ah, goodie. Another one...

silent barnBOT
#

@stone coral Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

Please take the time now to review all of the rules and references in #rules.

ivory delta
#

I seem to remember that the logs don't render the template. The actual call it's making will be rendered.

#

If you want to test this, post to somewhere you can see the request and see what you get at the other end.

waxen knot
#

Hi guys - happy new year!
I've got a question regarding variables and calculating:
I have an ESP sensor and want to create a variable with an offset value. Then I want to calculate the sum of both. At the moment I tried to "create" that offset variable in the config with

#

sensor:

  • platform: template
    sensors:
    gasverbrauch_offset_eingabe:
    value_template: "{{ states('gasverbrauch_offset_eingabe') | float }}"
#

but it seems it is not possible to calculate this variable + my sensor variable from ESP

silent barnBOT
#

@waxen knot 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/.

nocturne chasm
#

But gasverbrauch_offset_eingabe is not a valid entity.

waxen knot
#

why?

nocturne chasm
#

Check dev tool / states for it and you will see why.

waxen knot
#

hmm, looks ok for me:

Entitรคt    Zustand    Attribute 
 
Entitรคten filtern
offset_ein
 
Zustรคnde filtern
 
Attribute filtern
 sensor.gasverbrauch_offset_eingabe    10.00    unit_of_measurement: mยณ
friendly_name: gasverbrauch_offset_eingabe
nocturne chasm
#

Except that is not what you put in your template

waxen knot
#

? sorry I do not understand what you try to tell me

nocturne chasm
#

Your forgot the domain of sensor. in your template

ivory delta
#

value_template: "{{ states('sensor.gasverbrauch_offset_eingabe') | float }}"

#

gasverbrauch_offset_eingabe is your entity name. sensor.gasverbrauch_offset_eingabe is the entity ID.

#

Entity ID's always have a domain prefix.

waxen knot
#

ah, okay I understand - thanks a lot. But it is okay to create variables like that, isn't it? or is there a better way of doing this?

ivory delta
#

Variables? You're passing a string.

waxen knot
#

hmm ok.
I wanted to create a variable or something like this to be able to calculate in the next step. E.g. I get a value from on of my gas sensors and want to sum this value up with an offset value. And this offset value somehow needs to be created.

mighty ledge
#

how many sensors?

waxen knot
#

1 sonsor

mighty ledge
#
value_template: >
  {% set sensors = expand('sensor.x', 'sensor.y', 'sensor.z') %}
  {{ sensors | map(attribute='state') | map('float') | list | sum }}
mighty ledge
#

you want to add 1 sensor to what?

waxen knot
#

okay I'll try to explain better:
I have one gas sensor which sends the actual consumption

#

And I want to have the real value of the gas counter displayed in ha.

#

so I thought it would be a good idea to have one variable where I could enter some kind of offset

#

and have another variable where this offset + the value of the gas sensor is summed up

#

that's the problem.

mighty ledge
#

then your template sensor would be:

sensor:
- platform: template
  sensors:
    adjusted_consumption:
      value_template: "{{ states('input_number.xyz') | float + states('sensor.gasverbrauch_offset_eingabe') | float }}"
      unit_of_measurement: mยณ
karmic oar
ivory delta
#

I'd hardly call it a lot ๐Ÿคทโ€โ™‚๏ธ

mighty ledge
waxen knot
#

ok, thank you. so is there a more elegant way?

mighty ledge
waxen knot
#

sorry forget it...

#

@mighty ledge as far as I can see my sensor.gasverbrauch_offset_eingabe looses his value after restarting HA. Is there a way to make this sensor remember his last value?

mighty ledge
#

that depends on where that device comes from

waxen knot
#

it's not really a device it's just my calculation helper...

mighty ledge
#

Post the code for it

waxen knot
#

you mean the code of the part of the configuration.yaml?

#

sensor.gasverbrauch is what I get from my ESP. All other "sensors" are just there for calculation and comfortable setting the offset after a power fail or something like that

mighty ledge
#

@waxen knot Your template sensor is wrong for gasverbrauch_offset_eingabe

#

Itโ€™s referencing itself. It will always be zero

waxen knot
#

ah I understand what you want to tell me :-), but how could I get this working otherwise? The sensor gasverbrauch_offset_eingabe was meant to be a quick way to manipulate it via developer tools after a power fail...

mighty ledge
#

You need an input number. Your offset sensor should be adding some OTHER sensor inside the equation. Not itself.

#

Ask yourself this: What sensor am i offsetting? Then take that answer and use that in the offset sensor.

#

for example, if I wanted to create an offset sensor for 'sensor.abc'. Then I would use...

- platform: template
  sensors:
    offset_abc:
      value_template: "{{ states('sensor.abc') | float + states('input_number.offset_abc') | float }}"
#

You will not be able to offset anything without adding an input number. Embrace it, don't fight it.

waxen knot
#

Ok I think I got it. I will have a deeper look at that. Thanks so much

kindred arrow
#

Hey guys, I'd like to get a template values that gives "true" when any script is active, can we do that?

#

My objective is to show a conditional markdown with all the active scripts

dreamy sinew
#

{{ states.script | selectattr('state', 'eq', 'on') | list | length > 0 }}

kindred arrow
#

Damn you're fast, will try that

#

thank you so much

dreamy sinew
#

Haven't tested but that's an idea

kindred arrow
#

Can we put conditions like that into a conditional card?

dreamy sinew
#

Not sure

#

I don't mess with the front end much

kindred arrow
#

I guess i'll create a sensor then, snif

#

It works! That was ez

#

Can we now do the same but when an automation is running? (not the state I mean, but when it has been triggered?)

mighty ledge
#

nope

#

separate your action section from the automation into a script and you can, only if the script has a duration.

#

the calc will be on the script though, not the automation

kindred arrow
#

Yeah sounds logic, but good idea anyway, i'll live without that option then xD

#

Another question, is there a way to stop all the scripts at once btw?

#

Unless creating a group with all the selected scripts in it?

mighty ledge
#

yeah, script.turn_off and list all the entities in entity_id under data

#

all might even work

#
service: script.turn_off
entity_id: all
kindred arrow
#

Will try :p

#

Works perfectly omg, 2021 starting great for me

karmic oar
mighty ledge
#

That doesnโ€™t make sense, they are essentially the same in that regard

mighty ledge
karmic oar
mighty ledge
#

So youโ€™re either skipping some explanation or you havenโ€™t tried it?

karmic oar
#

Never tried it. Didn't see any documentation that led me to believe it worked that way.

mighty ledge
#

An input_boolean looks and acts like a switch in the UI

#

Thereโ€™s no difference. It exists to do exactly what you want: a toggle that does nothing that you can build automations off of

#

Or a toggle to use in an automation, where you set the state

#

Configuring it is super simple and doesnโ€™t require any yaml

#

Configurations -> helpers -> toggle. Name it and go.

karmic oar
#

Yeah, I just reconfigured it. Nice. That's exactly what I wanted.

mighty ledge
#

Thereโ€™s other helpers too

#

So keep that in mind when you need something else

karmic oar
#

I probably need to stop doing so much manual YAML work when HA does a lot of this stuff in the UI now

unreal dawn
#

Hi. I've got two entities that give a currency so for example ยฃ60.52. I'm trying to combine them into a value template but struggling to get it right. The following code works fine and combines them but I want to add a ยฃ at the start and can't seem to get it working.

#

Working code {{ float(states.sensor.electricity_30_days_cost.state.strip("ยฃ"))+float((states.sensor.gas_30_days_cost.state.strip("ยฃ"))) }}

#

Non working code {{ "ยฃ%.2f"|format float(states.sensor.electricity_30_days_cost.state.strip("ยฃ"))+float((states.sensor.gas_30_days_cost.state.strip("ยฃ"))) }}

unreal dawn
#

Figured it out {{ "ยฃ{:,.2f}".format(float(states.sensor.electricity_30_days_cost.state.strip("ยฃ"))+float((states.sensor.gas_30_days_cost.state.strip("ยฃ")))) }}

blazing wagon
#

How do I do else if statements? I have this code and the parser just throws errors.

          {% if is_state("binary_sensor.bg_sensor", "unavailable") %}
            false
          {% else if is_state("switch.gate_button", "unavailable") %}
            false
          {% else %}
            true
          {% endif %}
ivory delta
#

Replace your first else with elif

#

It's always elif if you want to check another condition and else for the default.

dreamy sinew
#

.jinja2 for more

silent barnBOT
blazing wagon
#

like this? {% elif is_state("switch.gate_button", "unavailable") %}

#

thanks mono

kindred arrow
#

Is there a way to convert seconds into %d %H:%M ? Like 360 = 6minutes ?

serene verge
#

Looking for a way for an automation to call a script (with a parameter) on every entity in a group. Ie, if group has three entities, the script is called three times - with parameter set to each entity. I've figured out how to use expand to get the elements out of the group, but there doesn't seem to be a way to loop over service calls to repeatedly call the script.

silent barnBOT
thorny snow
#

Hey guys,
i'm struggeling with an automatotion triggerded by a template (if-statement) depending on a sensor state. The sensor checks the difference between a local measured temperature and the one measured by my TRV. This sensor works so far. So I wrote a template which is checking if the temp-difference is in a given area. So if the difference sensor shows a "value between 0.4 and 50 OR over 50 and under 127.6" it shall trigger the automation (negative numbers are 128-x thats why I'm checking for < 127.4). It seems like the template triggers whenever it wants. Sometimes it works, atm the difference is 127.7 and the template says its true.

code can be seen above

near meadow
#

How can I get the min state from today of an entity? I have been looking into min/max and statistics integrations, but none can provide me with the min from today specifically.

loud otter
#

Hi all, does anyone has experience with template light integration? It seems that it has never been used because there are no post in the community

ivory delta
#

Never been used? ๐Ÿค”

#

And... it's an #integrations-archived. Start there unless your question is about the actual templates you're writing to make it work.

loud otter
#

Well it seems so looking at the forum. I'm trying to make it works but my templates are somehow wrong.

#

For example set color:

    set_color:
      - service: light.turn_on
        data_template:
          entity_id: light.striscia_led_cucina_rgb
          rgb_color: "{{ rgb_color }}"
      - service: light.turn_off
        data_template:
          entity_id: light.striscia_led_cucina_bianco
#

none for dictionary value @plucky token ['rgb']

#

I will move to integration to see if I understand well it and the come back here

loud otter
#

so

ivory delta
#

This is the bit you're stuck at:

color_template template (optional, default: optimistic)
Defines a template to get the color of the light. Must render a tuple (hue, saturation)

#

You need a template that does that. Not RGB. Hue and saturation.

loud otter
#

uhm, so how to convert RGB in hue???

#

hue saturation could be HS value in dev tools states?

ivory delta
#

If you have it there already, sure. Maybe there's no need to convert.

#

So you just want a template like the one in the docs that returns a tuple.

#

color_template: "({{states('input_number.h_input') | int}}, {{states('input_number.s_input') | int}})"
Adjust that to read from attributes instead if it's not coming from a state.

loud otter
#

ok now status is reported correctly. Thank you but I still have issue to set_color service. Here's my code I already changed based on your feedback:

    set_color:
      - service: light.turn_on
        data_template:
          entity_id: light.striscia_led_cucina_rgb
          hs_color: "{{ hs_color }}"
#

why it doesn't work either?

ivory delta
#

What doesn't work? Is there an error?

loud otter
#

yes. When I try to change color from ui I see an error message: None for dictionary value @ data['hs_color']

loud otter
#

it should be correct right?

#

it works in dev tools

muted knoll
#

I want to list all entities that has numeric state less specified in the input.

I'm using this code. But it looks like it compares not by numbers but by strings:

{{
expand('group.batteries')
| selectattr(
  'state' ,
  '<=',  
  states('input_number.battery_low_level') 
)
| map(attribute='name')
| join('\n')
}}

Is there a way to create such "oneliner" that makes the comparison bu numbers?

ancient garnet
muted knoll
#
{% for i in expand('group.batteries') %}
{% if (i.state|int) <= (states('input_number.battery_low_level')|int) %}
{{ i.name }}
{% endif %}
{% endfor %}
#

this does what I need. But I want to learn how to do the same thing without loop but with chained filters

ebon jewel
#

(it used to work with the data template but when i added the service template, it stopped working as intended)

ancient kelp
#

How do I save a template to an automation? When I save it it changes to [object, object] and doesn't work

silent barnBOT
#

@ebon jewel Please DO NOT cross post. Read the channel description, post it and wait for folks to respond.

nocturne chasm
#

@ancient kelp , if you are using the UI automation editor more than likely, 1) your template is not correct or 2) you are trying to add a template that the UI automations editor canโ€™t handle.

ebon jewel
#

how long is it acceptable to wait before crossposting? activity on some of these groups can be slow and take hours. and what would be more appropriate for a template automation question? template or automation?

grim geyser
#

Is there a way to keep a sensor value from the previous day and then subtract todayโ€™s value from it to get the difference?

ebon jewel
#

perhaps you can setup an automation that saves that value to some helper object to persist the value

fossil hearth
#

how to use groups in automations ? do i need to specify that its the sates that am after ?

    trigger:
      - platform: numeric_state
        entity_id: group.milkpots 
        above: 79.5
        below: 100

sample of on entity in the group

 is 29.687

what wrong have i done

ps actions and services work .. i just wanted to change it to groups instead of individuals

earnest cosmos
#

Hi, folks!
I get this error from my script:

Error executing script. Unexpected error for call_service at pos 1: Template rendered invalid service: 
#

This is the script:

 - service: >
     {% if is_state('input_boolean.in_bed', 'on') %}
         script.goodmorning
     {% else %}
         script.goodnight
     {% endif %}
#

... which would fire script.goodmorning if still in bed.

#
- service: >
    {% if is_state('binary_sensor.dark_inside', 'on') %}
        script.lys_grunnbelysning_on
    {% endif %}

Why does this last script (I assume) fail?

#

.. so I need to include an {% else %} here to avoid the error it seems, right?

silver pewter
#

Hi! My dishwasher has a entity called "sensor.diskmaskin_remaining_program_time" and state is "2021-01-03T10:19:05.176532+00:00" when a program is running. I want to make a template that shows remaining time in Hours & minutes(1h 34min) or %H:%M:%S ๐Ÿ™‚ i only know this template:
"{{ as_timestamp(states('sensor.diskmaskin_remaining_program_time'))|timestamp_custom('%H:%M') }}" what is only showing what time program is done, not countdown ๐Ÿ™‚
and google did not help me much

loud otter
#

Hi, Iโ€™m trying to setup a light template and this set_color doesnโ€™t works. Can someone please support me?

set_color:

  • service: light.turn_on
    data_template:
    entity_id: light.striscia_led_cucina_rgb
    hs_color: "{{ hs_color }}"
kindred arrow
#

Is there a way to get a return "true" when a variable is undefined? like {{ trigger.entity_id is not defined }}

deft timber
#

@kindred arrow, do you have a scenario where trigger.entity_id is undefined? From my point of view, it should not be possible

#

if you want to determine if a state is undefined for instance, just test if it is equal to the string undefined

kindred arrow
#

Actually my full condition is {{ trigger.entity_id == 'switch.chauffage' or trigger.entity_id == 'script.timer_chauffage' or trigger.entity_id is undefined }}

#

It works just perfectly fine when defined

#

But i'd like the condition to be true also when not defined

#

(To be triggered manually)

deft timber
#

ok, I get it

#

maybe testing with None ?

kindred arrow
#

I'll try and let you know, was on it already aha

deft timber
#

I made a little test and is undefined is supposed to work...

#
{% set a = {} %} 
{{ a.b is undefined }}

returns True

kindred arrow
deft timber
#

ok it is trigger that is undefined, not trigger.entity_id

#

try {{ trigger is undefined or trigger.entity_id == 'switch.chauffage' or trigger.entity_id == 'script.timer_chauffage' }}

kindred arrow
#

Oh

#

It's works yeeeeey, i'm stupid I didn't even thought about that way

deft timber
#

@silver pewter did you looked at relative_time?

#

@earnest cosmos Yes if you don't have an else, the template may return nothing, and HA won't like that. If you want you can include the service call in a choose statement, that way nothing will be called if your condition is not met

#

@fossil hearth I don't think you can do that, i.e. having a group of numeric entities and have a group state that reflect somehow the numeric value of your group

silent barnBOT
gleaming goblet
#

Found the issue ๐Ÿ™‚ a . in the {% endif %} ...

teal cove
#

I've been fiddling around for a good while now and I think I'm missing something big time. There has to be an easier way to get minutes until HH:MM when 'HH:MM' is provided by a sensor. The day should be the current date, don't care about overlapping at midnight. Can someone help me out?

cedar wigeon
#

I have made a sensor like this below, it is formated just like my others, but the sensor don't exist, not even after reboot. Anyone know why?

#

No entity is generated

thorny snow
#

Hi guys

#

how does this template: {{states.sensor.inbox.attributes.data[0].received}}

#

translate to the format {{state_attr('sensor.inbox', 'data', ... )}} ?

#

thanks in advanced

#

I have been able to get this: {{state_attr('sensor.inbox', 'data')[0].received }}

#

but is there a better way?

cedar wigeon
#

Hi. I have this one to select the second process, and it works:

- platform: rest resource: http://10.0.24.11:61208/api/3/processlist name: Glances - DeCONZ - CPU - Processes value_template: '{{ "ok" }}' json_attributes_path: '$[1]' json_attributes: - name - status - username
But I want to select the process by Name and not by order (because that can change)
But no mater what I test I cant find a way.

ivory delta
#

There are examples there on how to test for specific values of nested properties.

#

@cedar wigeon โ˜๏ธ

ivory delta
#

Something like this should work: $..[?(@.name=="DeCONZ")]

wary helm
timid osprey
#

Does that currently output a string or something?

#

{{ 1 if is_state('binary_sensor.vibration', 'on') else 0 | int }}

#

maybe that, Idk

#

I figured it'd bbe an int already though

wary helm
#

outputs a boolean

timid osprey
#

I meant the template you had above

wary helm
timid osprey
#

dev tools

wary helm
#

Yes, sorry, result type is a string

#

What should the output be? I'm still getting a string and the same graph

mighty ledge
#

@wary helm you need a unit_of_measurement

#

without it, sensors are always treated as strings, regardless of what the template returns

#

if you add a unit_of_measurement, it knows the sensor is numerical. Also, you'll have to wait for the database to purge out the 'non-unit_of_measurement' state changes in order for the change to take effect.

teal umbra
#

After reading some things on internet i created a sensor for lights that are currently on but i also read that is a resource hog. How can i make this code less resource consuming is there a written guide?

  • platform: template
    sensors:
    current_kitchen_lights_on:
    friendly_name: Number of kitchen lights on
    unit_of_measurement: 'on'
    value_template: >
    {% set lights = [
    states.light.hue_light_kitchen_ceiling_1,
    .Etc..,
    ] %}
    {{ lights | selectattr('state','eq','on') | list | count }}
mighty ledge
#

it's not resource consuming, people exaggerate. If you define the list in the template, it's minimal. If you iterate all the state objects on every state change, it's a hog. What you have there is fine.

timid osprey
#

good to know about why it was string petro, thanks

split wharf
#

Hi!
quick noob question if I may - would this trigger work if states have slightly different formatting? https://paste.ubuntu.com/p/chmJQhN59s/

it should read as HH:MM == HH:MM:SS

or should I reformat one to unify them?

#

I mean just the part before adding the offset (forgot to delete that in example)

deft timber
thorny snow
#

oh thanks

wary helm
split wharf
#

Any ideas why this trigger doesnt work? https://pastebin.com/wSDh7gW7
If I test that in template editor it returns true. but the automation doesnt trigger at that time. (it seems to be triggered by just changing the time (from before now to after now)๐Ÿคฆโ€โ™‚๏ธ )

mighty ledge
split wharf
#

Thanks! But without as_timestamp theose did not turn out to be true as time returns in HH:MM format but the input has :SS also

silent barnBOT
brave raven
#

Hi, i'm trying to create an icon change on a sensor template. it keeps registering new sensor as unknown. I searched on the templates pages and tried a few things without success. Can someone assist and have a look over my code to see what i'm missing

silent barnBOT
brave raven
brave raven
#

Solved it ๐Ÿ™‚

dense ore
#

Can anyone tell me if there's a way to truncate object id please? So for example I have an input_number.l_temp_evening that I want to use to change the target temperature of a climate.l_temp, using
entity_id: 'climate.{{trigger.to_state.object_id}}'
so I want to remove the _evening from the object id of the trigger entity (I have an input_number.l_temp that I use to set the temperature at a different time of the day, which is why I don't want to change the name of anything). I'm not sure if this is the correct section, or if this makes sense!

mighty ledge
mighty ledge
mighty ledge
brave raven
#

Thanks @mighty ledge I solved it with the below code

silent barnBOT
brave raven
#

can you add a spinning mdi icon to a sensor template?

mighty ledge
#

no

#

that has to be done at the UI level

#

in lovelace, and you'll need a custom card

#

if you're referencing a fan, there's already plenty of solutions, look on the forum.

#

typically they use the custom button card

brave raven
#

aha, thank you very much ๐Ÿ™‚

mighty ledge
#

fyi, it's not easy

dense ore
tidal heart
#

How can I convert {{state_attr('sensor.text_weather_swe', 'icon')}} to Javascript template? I can't figure it out

#

Here is my shot [[[ states.sensor.text_weather_swe.attributes["icon"] ]]]

deft timber
wicked parrot
#

Can I stick multiple actions in a switch template?

timid osprey
#

yes

wicked parrot
#

Rad. Thank you.

#

Finally got a projector that has an integration. Getting rid of my Logitech Harmony hub.

mighty ledge
#

You don't like the ass backward API that harmony offers?

wicked parrot
#

It did its job years ago, now not so much.

mighty ledge
#

I wish they would update it

#

I still can't believe they only tell you the activity name, not what devices & commands are mapped to each activity

#

makes it a fucking useless api

silent barnBOT
limpid fractal
#

Can someone help me with a condition in a script, details are posted above

timid osprey
#

you probably should use a yaml condition rather than a template condition.

#

If your template is not true then it is leaving nothing in the call

livid island
timid osprey
#

You have a lot of stuff for me to look through there. Have you tried throwing your templates in the dev editor and making sure all of the outputs look proper?

#

dev tools*

#

Also, does it trigger and fail to call action or does it never trigger?

livid island
#

it does trigger, it seems as i can see it in the logbook, okay then it's properly the script

timid osprey
#

Did you check output of templates?

livid island
#

hmm yeah that gives me a trigger undefiende...

timid osprey
#

I meant the temperature and set_now templates you have

#

maybe that is what you meant too

livid island
#

yes that also gives me a trigger undefined.

#

ah okay i just need to give it the trigger entity, and yes then it works.

#

and now i tested the whole automation in the out and it seems to work.

#

hmmm i think i maybe found it give me 2 min.

#

hmm okay no that was not it.... i thought i was because the template actaully outputted severals lines, so i made the template into one line, but that didn't help.....

#

ah nevermind the other one also does that.

#

okay if i only have the first with the entity_id and hardcode the rest then it works as soon as i add another it fails..

#

it was the " that was the error...

hollow hare
#

I hope I'm in the right place. I've just flashed openmqttGateway to an 8266 and I'm trying to get the templating for an RF plug formatted in HA. So far all I can do is get HA to send "ON" or "OFF" no matter what I set as command_on_template. It also doesn't register the json payload coming from the module.

hollow hare
#

ok, I got it to turn on after some tinkering and reading the project's forum some more. Now I need it to actually stay on in HA when I turn it on via the UI or the plugs' remote.

abstract river
#

Is there documentation on how you need to format a template with device class timestamp to be formatted properly in different browsers? I have one that displays fine in Safari and Chrome but in the silk browser on my Fire Tablet it just shows the date instead of "18 minutes ago" or whatever it should be

#

Oh wait - it might just be the entity card that isn't displaying it correctly

dapper oyster
#

Hey
I think this might be a very newbish question, I want to format a sensor, I found that I should write some template thing.
When I try it out in the developer tools, template section I got the formatting to work, but where should I put this code more permanently ?

deft timber
#

you have to create a template sensor

dapper oyster
#

and is that just in the configuration.yml?

deft timber
#

yes

dapper oyster
#

ok thanks ๐Ÿ™‚

prime hinge
#

Any way I can convert an array of byte values (e.g. [12,34,56,78]) to a numeric value? I have an mqtt sensor which sends data that way.

#

hm... wonder if something like value[3] + value[2] * 255, ... will work

marble needle
#

what's the best value to return for a numerical template sensor before its dependent entities are ready?

#

or can i just return nothing?

timid osprey
glossy viper
cedar wigeon
#

my drive is 100% so i can't save edits in my configuration.yaml, so I can't implement the purge-db that way.
How can I run a manual purge?

hexed wing
#

call the recorder.purge service

#

however, it is probably easier to delete e.g., the homeassistant.log file to create a littlebit of quick space (so you get room to figure out what is going on)

cedar wigeon
#

help, but I don't have access with samba, and my vscode plugin is saying read-only.

#

I am running the VMDK in esxi

hexed wing
cedar wigeon
#

you can select remove, but don't look like I have rights

hexed wing
#

Sounds odd, sorry not sure how to help at this point.

#

running the service might help, or else get into the system by terminal to clean up some space

cedar wigeon
#

hmm. I did a reboot, and I can no access trough samba, and have deleted the db and log, but the web gui say "Unable to connect to Home Assistant"

hexed wing
#

Ensure it is started, when running out of disk space

#

systems will act weird and will fail at starting parts

bronze tide
#

another try. hope this time it is the right place. ๐Ÿ˜…
this is my solution to find devices which are offline (state=='off'). it is rather rudimentary that is why i tried to add a check on the device_class attribute which should be 'connectivity', but this is not working. any hint?

{% set e =  states.binary_sensor | selectattr("state", "in", ["unavailable", "unknown", "off"]) %}
{%- for state in e -%}
{%- if state.entity_id.startswith("binary_sensor.l") %}
{%- if state.entity_id.endswith("status") %}
{#- {%- if state.name | selectattr("device_class", "is", "connectivity") %} #}
- {{ state.entity_id }} 
{#- {%- endif -%} #}
{%- endif -%}
{%- endif -%}
{%- endfor %}
deft timber
#

you do a state.name before the selectattr, state.name is a string, it has no attribute

#

why don't you simply do is_state_attr(state, "device_class", "connectivity") ?

glossy viper
deft timber
#

usgs_earthquakes_feed is not a valid entity id

glossy viper
#

is a feed type...but i don't know how to make templates

fossil totem
#

@glossy viper an entity_id will have a period in it somewhere, in your case it probably should be something like {{ state_attr('geo_location.usgs_earthquakes_feed', 'time') }}

glossy viper
#

still unknown status

fossil totem
#

what does it tell you in the template editor?

glossy viper
#
  • platform: template
    sensors:
    shake_time:
    friendly_name: "Earthquake time"
    value_template: "{{ state_attr('geo_location.usgs_earthquakes_feed', 'time') }}"
#

all good (already restarted)

fossil totem
#

so it's all good or it isn't working

glossy viper
#

oh...in developer tools

#
  • platform: template
    sensors:
    shake_time:
    friendly_name: "Earthquake time"
    value_template: "None"
#

This template listens for the following state changed events:

Entity: geo_location.usgs_earthquakes_feed
#

all good - syntax i meant

#

but value_template returned is none ๐Ÿ˜ฆ

fossil totem
#

does the entity under developer tools > states show anything? more to the point, has there been any earthquakes for it to report?

glossy viper
#

sure

#

3 eartquakes / one is from today updated

fossil totem
#

yeah ok so i just went and setup this component and holy lol, think i need to dial back the settings a bit

#

i have 9000+ entities added as a result

glossy viper
#

i put the card and the sensor which is radius 1000 km from my home

#

if u want to catch the same earthquake your radius should include croatia ๐Ÿ™‚

fossil totem
#

ok so this component turns out to be pretty awful

#

instead of creating an entity that has a list of events under it, it creates a new entity for every event. this isn't going to be fun to deal with.

glossy viper
#

i see

#

that's why i put card auto-entities

fossil totem
#

{{ states.geo_location | list }} will show you a bit of what's going on

glossy viper
#

ok. i will put instead of time in template sensor to see what i can get straight in the card

hexed wing
#

So you can fake that, by creating an helper

#

and next an automation that triggers on such an event and populates the helper

#

that way, you'll end up with an helper entity that has the last received event

fossil totem
#

was trying to figure out how to sort by time, but that's another easy solution

glossy viper
#

too advanced for me i guess. only 2 months of ha

fossil totem
#

might not work on startup, depending on the order that things are populated

glossy viper
#

barely have one input boolean to stop notification to my phone

mighty ledge
#

@glossy viper are you trying to find the latest earthquake? If so...

value_template: >
  {% set quakes = states.geo_location | selectattr('attributes.source', 'eq', 'usgs_earthquakes_feed') %}
  {% set latest = quakes | map(attribute='attributes.time') | list | max %}
  {% set latest = quakes | selectattr('attributes.time','eq', latest) | first %}
#

then from there you just gotta decide what piece of info you want

#

or if you want the entity_id ... {{ latest.entity_id }}

glossy viper
#

I imagined that once with the earthquake i can see as a secondary info time. I know that i can see the time if i click on card and see more attributes, but i wanted to see directly from viewing, not by one. click. i thought it was simplier, but i guess sometimes things can be simple only in my mind
just went home....will try now. thank you for your time, no matter if works or not.

ivory delta
#

You can get attributes via templates too...

#

I suggested a template sensor already.

#

Use petro's template and then build on it. You want to get time, do something like {{ latest.attributes.time }}

glossy viper
#

i need an example to understand like petro did....i'm too old to think myself for first step. then i can manage by myself...but the first step is the biggest for me ๐Ÿ™‚

#

i'll try to do with time

timid osprey
#

template editor, break it, fix it

glossy viper
#

Result type: string

{value_template: >

This template listens for the following state changed events:

Domain: geo_location
#

i'm on a good way?

#

and no time around earthquakes ๐Ÿ˜ฆ

ivory delta
fast mason
#

is there a better way to count all input* helpers together than counting them individually and adding them up?

#

cos for individual counts I have e.g. {{states.input_boolean | count }}, but I'd rather have all types together

#

and all I can think is to do that for each and add them up after

ivory delta
#

Match their names against a regex and then count.

#

Something like this:
{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list }}

fast mason
#

is regex the * thing? ๐Ÿ˜‚

ivory delta
#

No, that's an asterix.

fast mason
#

I'm really bad with templates haha

timid osprey
#

lol

ivory delta
#

RegEx = regular expressions. It's a powerful syntax that allows you to query text for patterns.

fast mason
#

This is my first time seeing regex ๐Ÿ™ˆ

timid osprey
#

well hold on for a ride

#

looks way more complicated than it really is ๐Ÿ˜›

fast mason
#

Let me try with your examples. Let's see

ivory delta
fast mason
#

You REALLY don't want to see my template sensors lol

glossy viper
#

i do ..maybe i will guess what to do for me ๐Ÿ™‚

ivory delta
#

Not much chance of that

#

You've been given the answer.

glossy viper
#

i put the answer as u can see in pastebin, but i didn't get it

ivory delta
mighty ledge
ivory delta
#

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

#

I told him what to do next. He clearly didn't read my message at all.

#

He pasted yours without edits and expected it to work.

glossy viper
#

i said that i don't have experience with template and need help building that

ivory delta
#

Between petro's example and the extra line I gave you, that's literally the full answer.

#

I don't know how much more help you need other than someone writing it for you.

#

Here we go... just to end this conversation:

value_template: >
  {% set quakes = states.geo_location | selectattr('attributes.source', 'eq', 'usgs_earthquakes_feed') %}
  {% set latest = quakes | map(attribute='attributes.time') | list | max %}
  {% set latest = quakes | selectattr('attributes.time','eq', latest) | first %}
  {{ latest.attributes.time }}```
(assuming `time` is the name of the attribute you want)
timid osprey
#

what does that mean from hassbot, lol

ivory delta
#

It means my first paste had incorrect indentation and therefore wasn't valid YAML.

timid osprey
#

ahh

ivory delta
#

It doesn't check edits, so it'll still have an x.

timid osprey
#

thanks

glossy viper
#

i know that i have put your patience to the max mono, but without understanding what represents first line is an trial & error in a loop for me

#

but someday i hope i can deliver a beer for the guys helping me

ivory delta
#

Get the feed (from the attribute usgs_earthquakes_feed)
{% set quakes = states.geo_location | selectattr('attributes.source', 'eq', 'usgs_earthquakes_feed') %}
Sort by time, newest first
{% set latest = quakes | map(attribute='attributes.time') | list | max %}
Get the most recent item in the feed
{% set latest = quakes | selectattr('attributes.time','eq', latest) | first %}
From the most recent item, show the time
{{ latest.attributes.time }}

strange sable
#

Do template definitions still need to be manually put into the config.yaml or has something been added to do it from the HA frontend? Running version 2021.1.0

ivory delta
#

What?

#

It depends entirely on what you're doing...

strange sable
#

So creating a custom sensor from an entity attribute..

#

I have it working this way, but just making sure I am not missing something..

ivory delta
#

Well creating sensors is a YAML thing, so the answer is to still do it in YAML.

strange sable
#

Thanks.. Just making sure I wasn't missing something where the config could be put in via a web based window. Something like when you create a custom resource for lovelace there is the "gui" interface for adding it.. Hope that just made sense..

fast mason
#

Playing around with what you gave me I also ended up getting it to count every single entity id. Probably not the way to do it but I'll use that too since I got it now

#

Only issue with counting the helpers I realised I have a few automations with the word "input" in and it's now counting these as well

#

I'm just using it twice to subtract automations with input in the name

#
(states | map(attribute="entity_id") | map('regex_search','automation.*input') | select('true') | list | count) }}
ivory delta
#

You only need it once, just fix the regex.

#

Really quick guess: map('regex_search','input_.*\..*'). Gives me a sensible count.

#

I haven't verified the entity names it returns to check.

#

input_.*\..* means input_ followed by any number of characters, followed by a . followed by any number of characters.

#

And since there should only be one . in an entity ID, that should match all inputs.

fast mason
#

I knew it was that but I had to chance, but I was just staring at it to work out what to do with it

ivory delta
#

RegEx looks like some arcane wizardry at first glance but it's quite logical. It's just a PITA to come up with expressions if you're new to it.

#

For the longest time, I could read a ton of them but not write any ๐Ÿคฃ

fast mason
#

I'm in the process of reading your explanation ๐Ÿ˜‚

#

Bear with

ivory delta
#

regex101.com will help you understand it. You can plug in examples in the 'test' pane and see which things match and which don't.

timid osprey
#

regex101 is a blessing

fast mason
#

I went there but it confused me on how i should use it

ivory delta
fast mason
#

on the top I put the regex and underneath the potential matches?

ivory delta
#

Like that

#

Any test string that's highlighted is a match (and will also appear on the right). Top right is a breakdown of your regex.

timid osprey
#

it has globbal on by default on the site so you can put a list and compare the list being hihglighted

fast mason
#

Ah I see. I was putting more in there and likely was failing because of it

ivory delta
#

Bottom right is the quick reference. It explains most of the common syntax.

fast mason
#

Ah I see now

ivory delta
#

You can get fancy and give alternates too. Here's an example where I only care about input_number or input_boolean: http://prntscr.com/wijdcg

fast mason
#

So | means or ?

ivory delta
#

Yup

#

It's all in the reference in the bottom right.

#

Here's a fun one. This is the official regex to validate if an email address is valid:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

timid osprey
#

did you see the explanation at the top right too? It breaks down the regex inputed

fast mason
#

I was just adding . to see the explanation of that haha

timid osprey
timid osprey
#

lol

#

lol to the site, not you

#

โค๏ธ

fast mason
#

๐Ÿค—

ivory delta
#

That regex is bugged though. It allows some illegal email addresses ๐Ÿคฃ

#

Shows how tricky regex gets when you do more complex stuff.

timid osprey
#

99.99%

#

lol ๐Ÿ˜›

ivory delta
#

Anyway... does the one I gave you work for your inputs, Thanasis?

fast mason
#

A so in your input_.* it's not . then * it's the whole thing .* that means something if I'm getting that right

#

Yeah yeah works exactly like it should ๐Ÿ’ฏ

ivory delta
#

Read it in steps...
input_ the literal string 'input_'
.* any number of any character
\. the character '.' (needs a backslash as an escape character because . has special meaning)
.* any number of any character

fast mason
#

I only new of * meaning anything which is why I got so confused when I saw .*

ivory delta
#

Another way to solve your problem of it matching 'input' in the entity name of an ID would be to anchor the regex to the start of the string: ^input_.*
That would do:
^ match from start of line
input_ match the literal string 'input_'
.* any number of any character

#

Should also work for you, just another way of doing the same thing. Might even be quicker but we're talking fractions of milliseconds for simple stuff like this.

fast mason
#

Even just ^input gives me the same

#

Compared to what i had with subtracting them ๐Ÿ˜‚

#

What is the meaning of select being true/false ?

timid osprey
#

the select('true') ?

#

nvm, that can't be, lol

ivory delta
#

| map('regex_search', 'pattern') is running a test against each item and will return true/false for each item... but you still get back a result for every item (that's what maps do).

timid osprey
#

oh, my b

ivory delta
#

You then run a | select('true') to filter out the ones that don't match that test.

timid osprey
#

if you remove the end bits of the template pipe by pipe, you can see what is going on

ivory delta
#

It's like when you see people do massive multi-line templates where each line is a step in a bigger process... pipes are the same thing on one line.

fast mason
#

Ah I also see the point the moment you completely remove it. Give you eveything

timid osprey
#

yee, you get a fat list of true/false and then we filter out only true before count

ivory delta
#

And like I said earlier, it took me ages to learn this kinda stuff. I'm a software engineer and I still don't grasp this stuff immediately ๐Ÿคฃ

timid osprey
#

And when you mix 6 different libraries, all sorts of fun

fast mason
#

Yeah I've hardly played with templates so haven't had time to really understand them yet

#

@ivory delta so if you're a Biologist likely decades then hahahah

ivory delta
#

They're one of the harder bits of HA but they're so powerful once you learn them.

timid osprey
#

If you are ever messing with templates that require events, you can throw in a json object and parse it as an obj so you can sort the other templating based off of the event

dreamy sinew
#

they can be super powerful

timid osprey
#

if that makes sense

#

'might be a better way, lol

dreamy sinew
#

but can also be really obnoxious ๐Ÿ˜„

fast mason
#

do they go nuclear @dreamy sinew ?

dreamy sinew
#

datetimes in templates make me want to commit sudoku

fast mason
ivory delta
#

I think he means like this:

{## Imitate available variables: ##}
{% set value_json = {"sensors":{"28-00000b988fef":"42.312","28-00000b98f5e6":"51.937","28-00000b9905e1":"39.062","28-00000b9920f3":"39.062","28-00000b994f64":"37.625","28-00000b9951c4":"37.812","28-00000b996c8c":"38.0","28-00000b99a737":"33.687","28-00000b99a884":"33.25","28-00000b99b4f0":"38.937","28-00000b99f29e":"37.75","28-00000b99fa3c":"34.187","28-00000b9a170e":"36.562","28-00000b9a1ca5":"37.75","28-00000b9a2529":"32.375","28-00000b9a3025":"40.187","28-00000b9a444d":"42.125","28-00000b9a4668":"41.312"}} %}

The temperature is {{ value_json["sensors"]["28-00000b988fef"] }}```
#

Pretend you have a JSON coming in but just mock the data so you can play around.

fast mason
#

One of these days I'll finish with my gitignore file and upload my config to github. I'll send a link to my templates mindblownmindblownmindblown

ivory delta
#

In something like a REST sensor, you'll have value_json coming in... but you don't want to have to reload your sensor every time you want to test a change.

fast mason
#

Aaaah so I set up a fake sensor state so it parses in the template and I get an output ?

timid osprey
#

also like to state and from states

#

triggers, I mean

ivory delta
#

I'm so glad the Template dev tool now retains your previous templates. I'm using mine as a kind of respository of examples I want to refer back to or share with people ๐Ÿคฃ

#

Yeah, same idea with those too, BuSheeZy.

fast mason
#

I do that too

ivory delta
#

Mock the data, then experiment with the mock.

fast mason
#

but does it not clear once you restart?

ivory delta
#

Nah

#

Some HA magic happens and it's saved into .storage or something.

fast mason
#

So I just went to it to do all these templates now and I knew I had left there templates from last time but I had the default one

ivory delta
#

You want some real helpful templates? How about knowing which room/house/floor/whatever something is assigned to?

{{ states | selectattr('attributes.room', 'equalto', 'study') | list }}```
fast mason
#

So like I had left things from e.g. a week ago

ivory delta
#

I customised some entities to have the attribute 'room' with a value assigned to it ๐Ÿ”ฅ

fast mason
#

So you give them like both floor and room for example to filter even more?

ivory delta
#

You can give them whatever you want.

timid osprey
ivory delta
#

Let's say you have tons of media players and you want to easily identify which ones are TV's/sticks and which are audio-only.

fast mason
#

It's likely my 1h of sleep and amount of work currently stored in my head

timid osprey
#

I am not doing any parsing here, but this type of trigger is just what I meant

#

where you wouldn't be able to get that info in your tempalte editor so you make a pseudo one for toying with

#

snag it out of your mqtt stuff and then make it into a template obj

fast mason
#

Ah so you publish to that topic yourself?

timid osprey
#

yes

#

as soon as an mqtt event comes in, it immediately goes back out and I could do stuff with the data all within that piece right there

#

with templates

fast mason
#

But your trigger mqtt is an actuall sensor you have and you have that published to a fake one? or confusing myseld now?

timid osprey
#

these are two diy devices. co2 sensor that I output to a separate 7 segment display that isn't a sensor.

#

co2 sensor is logged but rather than doing an automation based off of state, I just do 'er with the mqtt trigger

#

7 seg is not a sensor or anything, just sending data to it for no reason

#

I should have just had a good example because this is not ๐Ÿ˜›

fast mason
#

Throwing me right in the deep ๐Ÿ˜›

timid osprey
#

Imagine I have a json packet coming in and I only want to log one of the attributes as an entity. I can make a template out of that for sure and it will always have its state in HA. Maybe I have another attribute in a json packet and I don't want to log its state at all or store it as an entity at all, I can just use the template to get the trigger.packet and immediately forward it off somewhere else without having to make automations based off an entities state.

#

I am too afraid to read back that sentence, I typed for a long time without a period, I think

#

there has to be a good example on there too but I am a lazy person atm

#

oh, lots of stuffs

fast mason
#

That is making some sense to me actually ๐Ÿ™‚

silent barnBOT
timid osprey
#

you are trying to pass data through the topic?

ivory pawn
#

Hello all, can someone help me with yaml automation and mqtt ?

How do I change the code so that the last variable X (varX) in the trigger topic is also passed to the data template ?

  initial_state: True
  trigger:
    - platform: mqtt
      topic: 'A/states/B/C/varX'
  action:
    - service: mqtt.publish
      data_template:
        topic: 'A/B/C/varX'
        payload_template: '{{ trigger.payload }}' ```

At the moment I am having to treat each varX as fixed by writing a seperate trigger and action automation for know values of varX.
timid osprey
#

{{ trigger.topic | regex_findall_index('.*/(.*)') }}

#

try that

ivory pawn
#

@timid osprey thanks but it doesn't pass yaml . error : expected <block end>, but found '<scalar>'

timid osprey
ivory pawn
#

@timid osprey thanks ... ill try to understand the link and try it out.
Just to be sure, i'm trying to take any mqtt topic starting with A/states/B/C/ and forward it to A/B/C/ but preserving whatever comes after C in the state topic. Or in another way I want to take out only the '/states' part of an mqtt topic before forwarding.

#
        topic: 'A/B/C/{{ trigger.topic | regex_findall_index('.*/(.*)') }}'
``` isnt accepted by HA config check and brings up an error. Can you please help me correct this? Thanks
timid osprey
#

not sure if you can put a template there

#

try with double quotes

#

around the topic

ivory pawn
#

@timid osprey thanks .. this worked topic: "A/B/C/'{{ trigger.topic | regex_findall_index('.*/(.*)') }}'"
however, it still needs the trigger topic to have pre defined (static) values for varX, otherwise the template topic doesn't have this value to copy. any ideas?

timid osprey
#

a wildcard trigger doesn't work/come through?

#

I'm not super experienced with this

ivory pawn
#

solved with split . thanks

bright quarry
deft timber
#

@bright quarry What I would do is create an MQTT sensor by door/window sensor, and in the value_template: attribute put something like:

name: my_entity_id
value_template: >
  {% if value_json.device = "device_id" %}
    value_json.state
  {% else %}
    {{ states("sensor.my_entity_id") }}
  {% endif %}
json_attributes_template: "{{ {'time': value_json.time, 'extradata': value_json.extradata} | tojson }}"
#

and put the time & extradata in the attributes

#

what it does is that it updated the state of the sensor if the device matches the device id of that door/window (1P7T3), and if gets the existing state of the sensor if the device id does not match the device id of that door/window

#

you will have to add the same logic in json_attributes_template

#
name: my_entity_id
value_template: >
  {% if value_json.device = "device_id" %}
    value_json.state
  {% else %}
    {{ states("sensor.my_entity_id") }}
  {% endif %}
json_attributes_template: >
  {% if value_json.device = "device_id" %}
    {{ {'time': value_json.time, 'extradata': value_json.extradata} | tojson }}"
  {% else %}
    {{ {'time': state_attr("sensor.my_entity_id", "time"), 'extradata': state_attr("sensor.my_entity_id", "extradata")} | tojson }}"
  {% endif %}
cedar wigeon
#

I have a broken HassOS installation, I can't login to the web-gui, but I can log into the CLI with root, and access the root system

I want to copy out my configuration and start ower. How can I enable SSH or SFTP so I can copy my config? I have samba enabled but I don't remember my credentials

cedar wigeon
#

wrong place to post I se

acoustic ridge
#

I got this template to change temperature on ac when outside temperature is under 5. How can i get it to change to 14 when temperature outside is still under 5 but electricity price is "VERY_EXPENCIVE"? https://pastebin.ubuntu.com/p/gXQFRhS7Vr/

bright quarry
#

@deft timber where do those go? configuration.yaml and somewhere else? i tried the first code block in configuration.yaml and got a syntax error, maybe my indentation was wrong.

sonic nimbus
#

Hello I have weird situation that my wait template is not quite working as expected

#
    timeout: '00:00:10'                                                                                                                                     
    continue_on_timeout: 'true' ```
#

its skipping this condition

#

and automatically returns the scene before for the media player\

#
    data: 
      entity_id: scene.before```
#

so, basically I can hear my tts, but in the middle of a sentence, it set my scene like before (changes the channel)

#

so, do you have maybe better solution how to stop script (to wait) for my tts its finished and then proceed further?

deft timber
deft timber
#

change value_json.state whith {{ value_json.state }} and the = with ==

bright quarry
#

how do i use it after that? i added a sensor but nothing happens.

bright quarry
deft timber
#

Then create a sensor by door/window

#

changing the device_id

#

and don't forget to change sensor.my_entity_id with the actual id of your sensor

#

the one you are defining

#

sensor.simplisafe_sensor in your case

bright quarry
#

oh. you mean create a sensor for each door/window and specify it's device_id? in configuration.yaml?

deft timber
#

yes

spring zenith
#

The input of the Solar pannels from brand 'SMA' are connected with modbus.
If the sun is gone i get the lowest possible number because the readings are 'unknown' .
Trying to fix this with a template but its not working.๐Ÿ˜ซ
https://hastebin.com/ipoloketuy.yaml sensor.yaml file
https://imgur.com/a/AQELToP
Working on this for 1 week now. Anny suggestions ?

ivory delta
#

So you want to use the value of sensor.sma_pac unless it's unavailable, in which case you want to have 0?

#

I don't know if there's a better way but this should work:
{{ 0 if states('sensor.sma_pac') == 'unknown' else states('sensor.sma_pac') }}
@spring zenith

spring zenith
#

Thats exactly what i would like. yes

ivory delta
#

If it returns a numerical value, you could probably just cast to an int too, since 'unknown' will cast to 0.

#

{{ states('sensor.sma_pac') | int }}

dreamy sinew
#

yeah, if its always a number you can just cast to int. Anything that is NaN gets dumped to 0

ivory delta
#

Looks neater too, even if it leaves you wondering how it cast a string ๐Ÿ˜„

dreamy sinew
#

that's a jinja thing

#

neat trick but not obvious

ivory delta
#

It's handy. I only just thought to try it.

dreamy sinew
#

was gonna suggest it but you were faster

ivory delta
#

๐Ÿ˜‰

#

Makes a change for me to beat one of the pros.

dreamy sinew
#

lol

spring zenith
#

Also strange that i cant find 'sma_ppv_incl_0' and not 'sma_pac_incl_0' back in HA

stoic comet
#

it's not clear to me why condition: works and conditions: does not

#

ยฏ_(ใƒ„)_/ยฏ

#

oh, it this the intersection of boolean testing?

#

bother

#

ok, this works but it's a lot visually..... condition: condition: or conditions: - "{{ state_attr('light.desk', 'brightness') < 51 }}" - "{{ is_state('light.desk', 'off') }}"

#

this is better? condition: "{{ state_attr('light.desk', 'brightness') < 51 or is_state('light.desk', 'off' }}"

hexed wing
#

The latter is a slight more efficient from the code part of things

#

as it just checks 1 condition

#

instead of rendering 2 templates

#

however, that is micro optimization, readability is generally more important I would say

#

You can alternatively format it like so:

condition: > 
  {{
     state_attr('light.desk', 'brightness') < 51
     or is_state('light.desk', 'off'
  }}
stoic comet
#

oh that's nice

alpine pelican
#

I'm using scrape that is ending up with value == "Docker Registry Browser ยท Version 1.3.5 (59abbda)". In Dev Tools/Template, if I do something like this:

{% set val = 'Docker Registry Browser ยท Version 1.3.5 (59abbda)' %}
{{ val | regex_replace('^Docker Registry Browser . Version ([0-9.]+) .*$', '\\1') }}

it works great.
But in sensors.yaml, this returns the whole string:

  value_template: >-
    {{ value | regex_replace(find='^Docker Registry Browser . Version ([0-9.]+) .*$', replace='\\1') }}
#

Any ideas?

stoic comet
#

using the word condition three times felt like i was doing it all wrong

hexed wing
#

Nah, it was fine, depends on the use case

#

for example

#

you could have used

#
  condition:
    condition: or
    conditions:
      - condition: numeric-state
        entity_id: light.desk
        attribute: brightness
        below: 51
      - condition: state
        entity_id: light.desk
        state: "off"
#

or a combination of any ๐Ÿ™‚

charred dagger
#

Conditional conditions conditional conditions condition condition conditional conditions.

hexed wing
#

depends...

#

๐Ÿ˜›

stoic comet
#

๐Ÿ˜›

#

yes

hexed wing
#

Templates are generally less efficient for the system

#

using native available stuff is generally a tad faster

stoic comet
#

and now the zha attached ge link bulbs i'm using behind my monitor follow the brightness of my hue bulbs down to a point and then just turn off. https://hastebin.com/usikutofub.yaml

alpine pelican
#

@hexed wing If you're replying to my issue, I'm not sure what you're suggesting. Is there a better way to get that information (just the version number) into a sensor?

hexed wing
#

I was not

alpine pelican
#

oh... ok. good. Because I wasn't sure what to do with it. ๐Ÿ™‚

#

FWIW: changing my code to this:

  value_template: >-
    {{ value | regex_findall_index(find=' Version ([0-9.]+) ', index=0) }}

fixed it

vocal linden
#

Is there a way in templating to get the devices/entities of an area? I need it in a blueprint where it has a target selector and I want to check in a loop for every item of an area/devices/entities (the things a target selector can give) in an automation if it has a kind of attribute. For devices and entities the loop is straight forward, but not for area. Didnt find much about areas in the docs (especially for templates). Only found that theres an "expand" for groups, but I need it for an area or a way to convert an area to a group and filter these.

ivory delta
#

I don't know about for areas but you could set custom attributes on entities to designate which 'area' they're in and do something like this:
{{ states | selectattr('attributes.room', 'equalto', 'study') | list }}

vocal linden
#

Thanks for the effort but I think it doesnt suit in my usecase. Because its for a blueprint I want it to work right away. If the user has to set costum things to each entity of an area, he could also just create a group and use the group. Avoiding to have making group and making it easy to use with a target selector is my motivation for such a messy solution for this blueprint. Targets are great for services, but messy in templating I think

near meadow
#

Can I get the state of an entity from a specific time?

bright quarry
#

@deft timber i can't figure out how to make a sensor with device_id. can you help? ;/

molten scroll
#

I have a sensor that shows used time time in seconds, how can I edit it so it displays hours/minutes/seconds , with no limits on the hours (so values like 10.000 hours should be possible)

#

The examples i found online seem to limit the hours to 24 or 99

ivory delta
#

What kind of sensor?

molten scroll
#

My heat pump has a thermal unit it reports time used in seconds, so i added that as a sensor configuration but seconds aren't as easy to read as hours minutes seconds

#

Id copy a test configuration but the file editing add on doesn't support text selection or copy/paste sub menus on android

#

I tried this but it gives an error

#

can not read a block mapping entry; a multiline key may not be an implicit key at line 128, column 30:
{%- set map = {'Week': (seconds / 604800) % 604800,
^

deft timber
ivory delta
molten scroll
ivory delta
#

D'oh. I missed that ๐Ÿ˜„ What happens when you put that into Dev Tools > Templates?

molten scroll
#

Is there any way to remove that sample template besides holding backspace for each line individually

#

The value template stuff is calculated in the Dev tools template

#

And shows the sensor entries as plain text

ivory delta
#

And if you just want hours, minutes, seconds, this is what you're after:

{%- set map = {
       'Hour': (seconds / 3600),
       'Minute': (seconds / 60) % 60,
       'Second': (seconds % 60) } -%}```
#

178 Hours, 6 Minutes, and 40 Seconds

bright quarry
#

@deft timber https://pastebin.com/F1a82gDZ
dunno how to parse # bathroom window sensor. dunno what to give it for a platform name or what else to put there to make it work.

ivory delta
#

Highlight the text with your cursor, then press backspace? ๐Ÿค”

molten scroll
#

Yeah it stops every line

#

I have to manually click the line above to delete that, and the one above

ivory delta
#

Then you / your device / your browser is the problem.

molten scroll
#

And so forth 24 times

#

Ahh so it's a compatibility issue with chrome on android

#

Can I use this code outside if a template?

ivory delta
#

That code is a template. I don't know what you mean by 'outside of a template'

#

And editing code on a mobile phone is ๐Ÿคข

#

Use a real editor...

#

On a real computer ๐Ÿ˜‰

molten hound
#

Not sure if this is the right place, but.... anyone know how to convert a binary_sensor to a value, like 0 or 1?

deft timber
molten scroll
#

I was hoping to use it directly in the sensor definition instead of creating a new sensor under template

teal cove
#

Hey guys, what am I doing wrong here?
Solution: use media_player.play_media !

  - service: media_player.media_play
    data:
      entity_id: media_player.spotify
      media_content_type: playlist
      media_content_id: >
        { 'spotify:playlist:23kjh45hk23jh345jh123k' }

(template shortened)
It logs testscript: Error executing script. Invalid data for call_service at pos 1: extra keys not allowed @ data['media_content_type'] ๐Ÿคทโ€โ™‚๏ธ

#

I also don't understand why it rants about content_type instead of content_id

ivory delta
#

Try it without media_content_type

bright quarry
teal cove
ivory delta
#

Ah, yes... media_play and media_pause are for the currently playing media. play_media is 'go play this thing'.

#

The names aren't ideal ๐Ÿ˜„

teal cove
#

indeed haha ๐Ÿ˜…

#

it makes sense. but still impractical ๐Ÿ˜…

fossil totem
#

Is there any way within a template to figure out if the current system's location calls for units in ยฐC or ยฐF? Like, I want to literally send a string ยฐC if the current locale calls for ยฐC.

vocal linden
#

your temperature sensor for your wather integration has a attribute "unit_of_measurement". So you can determine from your weather.home which comes right out of the box in HA what the unit is

fossil totem
#

annoyingly, the two that i'm using currently (met.no and nws) don't seem to have that

vocal linden
#

you dont have to search for the sensor which is created by the weather-home

fossil totem
#

That's the stock met.no provider that is selected by default when deploying a new hass installation

vocal linden
#

oh I see the sensor i have is from my open weather map integration, sorry ๐Ÿ˜…

fossil totem
#

the nws sensor (really good if you're in the US) similarly doesn't offer unit_of_measurement

vocal linden
#

Yeah okay if you have the open weather map integration my way will work. I think there is no easy solution for that except comparing the location with ''closest'

#

and some example coordinates for regions with fahrenheit and celius

ivory delta
#

One would imagine that since the NWS is based in the US, it would always surface data in imperial. No need to figure out which region you're asking for data from.

fossil totem
#

so my problem is... this is being developed as part of my HASP project, which means the template is going to land on other people's system, and i don't know ahead of time which weather providers they will have installed or which region they are in

#

i could create some if-else monstrosity to check each provider and make a guess, which would be great right up until one of them changes and then all my users have a broke config