#templates-archived

1 messages ยท Page 88 of 1

ebon yoke
#

or maybe a custom component, yes

rugged laurel
#

Are you scraping the data or did VG publish it as json?

ebon yoke
#

VG has published everything as json

#

one sec, and i'll dig up the url

#

that's the json structure for the different municipalities

#

they have quite a few others as well.. they also publish the hospital stats, case-by-case stats and a few others as well as json structure

#

@rugged laurel if you'd be interested in working on a custom component for the data from VG, please let me know ๐Ÿ™‚

rugged laurel
#

no need, a rest sensor is enough

ebon yoke
#

let me know if you want to take a look at my, admittedly feeble, attempts ๐Ÿ™‚

#

i had to set up a python web server to present the municipality structure from vg into a structure with a parent key

#

to be able to address it properly.. if you find a different way of doing the same, please let me know

rugged laurel
#

ah, you want multiple..
You need custom_component/appdaemon/netdaemon for that

ebon yoke
#

yeah, i'm monitoring several municipalities

#

if that's what you mean by multiple?

#

i just wrote a python script to put the json structure with a new parent key "municipalities"

#

and then used that key in json_attributes

#

i'm not sure that is the best way of doing it, though

rugged laurel
#

Creating a custom_component for it should be easy enough, probably 15-20 min work, 30 if you want config_flow

ebon yoke
#

i'd be more than happy to create one, but i have no idea how to start out ๐Ÿ™‚

#

what kind of component will it be?

#

which integration?

rugged laurel
#

a new one, that spin up sensors

#

the config_flow should have a dropdown to select a municipality

ebon yoke
#

hm.. the home-assistant repo has changed its name to core?

rugged laurel
#

yes

ebon yoke
#

maybe use the coronavirus component as a starting point

rugged laurel
#

Sounds good

ebon yoke
#

er.. where does that component get its data from?

rugged laurel
#

internet

#

๐Ÿ˜‚

ebon yoke
#

hehe, d'uh.. but WHERE.. i see no references to any urls or similar there

rugged laurel
#

all core integrations require that a pypi package handle the communication to the api

ebon yoke
#

aha

#

ah, here we have it: import coronavirus

rugged laurel
ebon yoke
#
$ pip3 search corona | wc -l
12
#

hehe, there's been a few already, yeah

tender dagger
#

Newbie here, this should be simple but i could not find any examples that helped. I have this action:

service_template: |
  {hdmi_cec.{% if trigger.data['action'] == 'on' %}
             power_on
           {%- else -%}
              {% if trigger.data['action'] == 'off' %}
                power_off
              {%- endif %}
           {%- endif %}}

It's based on a webhook trigger and the if-statement does resolve correctly. But it comes out to: 'hdmi_cec. power_off'. To get rid of that whitespace I need a concat-function, but any operator I put is taken as a literal string, meaning 'hdmi_cec. ~ power_off'. What would be the correct way to make a proper service call out of that?

charred dagger
#

You can simplify it to just if hdmi_cec.power_on else hdmi_cec.power_off endif

#

Unless you expect trigger.data["action"] to ever have a different value than on or off, in which case you're not handling that now anyway.

buoyant pine
#
service_template: "hdmi_cec.power_{{ trigger.data['action'] }}"
#

@tender dagger โ˜๏ธ

tender dagger
#

both of these look right but now result in 'hdmi_cec/power_off' for some reason. is the . now treated as a magic word?

buoyant pine
#

Should be ok, I have several service templates like that

tender dagger
#

will try a reload

buoyant pine
#

Also let's see the whole automation

silent barnBOT
tender dagger
charred dagger
#

That's just the internal name of the service.

#

Do you see hdmi_cec.power_off in the list in devtools ->Services?

#

And do you see hdmi_cec in the integrations list in devtools -> Info?

tender dagger
#

checking it I found that it is .standby not .power_off for turning off, your suggestions now work as intended. Thank you both for your help and time.

pale laurel
#

Has anyone else had any issues with cover templates not being able to get states changes from sensors when updating to 0.107.7?

mighty ledge
#

what's your issue?

#

er let me rephrase, what's your template

#

@pale laurel

pale laurel
#

Basically, everything is working in 0.107.6, but when I updated to .7 it all broke. I have multiple blinds using esphome, and some of the blinds I have grouped together using cover templates (ie two living room blinds that are next to each other. If I have 1 blind open, the template cover is showing the opposite state of the sensor it's supposed to read. I can use the template cover to then close the blinds (everything displays correctly), and then open the blinds (everything displays correctly), but then can't close them again because for some reason the template cover isn't reading the state from the sensor. Here's my code: https://hastebin.com/elinuvuzey.cs

#

Like I said, it all works in .6, but upgrading to .7 breaks it.

#

@mighty ledge

#

The reason I'm using a template instead of a group is because I want my group to only show open if ALL the blinds are open

arctic sorrel
pale laurel
#

I meant cover group, so instead of cover group or cover template, just use a group?

arctic sorrel
#

You can create groups that are only open if all the members are open - see the link

pale laurel
#

I get that part, I should have also mentioned that the reason I'm using cover is because telling Alexa to "open living room blinds" will only work if it's a cover

mighty ledge
#

Your template looks good but you aren't updating the templates based on the sensor.

#

so there could be a race condition there

pale laurel
#

isn't that what value_template does?

mighty ledge
#

Yes, but the value template only has listeners for cover.living_l_blinds, and cover.living_r_blinds

#

it should also have a listener for sensor.living_room_blinds, but sometimes the parser doesn't work

pale laurel
#

Oh ok

#

so I need to add the sensor to the entity_id list

mighty ledge
#

well that will help, i don't know if it will fix your issue.

#

everything looks good the way you have it on the surface

#

without the extra entity_id

#

also, why aren't you just using a cover group?

pale laurel
#

when I used cover group, the group was reading open if even just one blind was open. In the documentation, it didn't show an all condition like the light groups do.

mighty ledge
#

Ah

pale laurel
#

I only want the group to show open if every blind is open

mighty ledge
#

that's a good enough reason

pale laurel
#

yeah, i know that one thing is making this way more complicated lol

mighty ledge
#

ok so try this

#
value_template: >
  {% set covers = [ states.cover.living_l_blinds, states.cover.living_r_blinds ] %}
  {{ covers | selectattr('state','eq','open') | list | length == covers | length }}
#

And you can remove your sensor template

pale laurel
#

dumb question, having "set covers =" is fetching the state of the covers, not trying to set the state of the covers?

mighty ledge
#

yes

#

not a dumb question

#

everything in jinja gets the state

arctic sorrel
#

Jinja variable setting magic

pale laurel
#

sorry, I'm using to = being assigning and == being a comparison

mighty ledge
#

yah, you're assigning a variable equal to the current value of your covers

arctic sorrel
#
value_template: >
  {% set some_thing_here = [ states.cover.living_l_blinds, states.cover.living_r_blinds ] %}
  {{ some_thing_here | selectattr('state','eq','open') | list | length == some_thing_here | length }}
#

Same thing, just less "friendly"

pale laurel
#

OH gotcha

arctic sorrel
#

(I think, if I replaced all the right things)

mighty ledge
#

you did

pale laurel
#

is that covers var local or global? like it's not going to affect other templates?

arctic sorrel
#

Local

pale laurel
#

ok

mighty ledge
#

everything in jinja is what tinker just said

arctic sorrel
#

Jinja variables tend to "hyper-local" too, you can't set things in loops and then use them outside for example

pale laurel
#

what's the difference between using -> and just > when doing multi-line

#
  • rather
buoyant pine
#
  • trims the output
pale laurel
#

so why wouldn't you just use it all the time?

buoyant pine
#

doesn't look as nice

#

idk lol

pale laurel
#

lol gotcha

mighty ledge
#

I never use it because it makes no difference

pale laurel
#

yeah I saw some people using {- -} instead of {} and I wasn't sure why

mighty ledge
#

If this were another package, it would make a difference

#

but home assistant trims all whitespace by default

pale laurel
#

gotcha

mighty ledge
#

now... if you using the editor...

pale laurel
#

no

mighty ledge
#

it makes a difference

pale laurel
#

i use sublime

mighty ledge
#

no when I say editor, i mean the built in template editor

#

take a look

pale laurel
#

the one in the gui?

#

that's why I meant by no, I don't use any addon editors or stuff in the gui, I prefer to just use sublime text

mighty ledge
#

notice the space?

pale laurel
#

gotcha

mighty ledge
#

that little - removes that space

#

so, it's pretty much only useful there.

#

It's also useful for sending notifications because the message field retains spaces.

buoyant pine
#

yeah i was wondering if >- actually did anything. good to know it doesn't lol

#

but yeah, {%- and the like are useful

mighty ledge
#

it's pointless unless in the message: field for notifications

#

there might be other areas where it's useful but I haven't found any

#

outside messages

#

Probably the markdown card

buoyant pine
#

you're gonna hurt the hyphen's feelings

mighty ledge
#

Lol

buoyant pine
#

won't anyone think of the hyphens??

pale laurel
#

what about the icon template, right now I'm using the sensors to define that

mighty ledge
#

that should be fine

pale laurel
#

ok, i thought you meant just get rid of the sensors all together

#

lol

mighty ledge
#

wait

#

lemme look

pale laurel
#

see where I'm using sensor.living_room_blinds to get the state for the icon?

mighty ledge
#

oh, didn't see that.

#

use this

pale laurel
#

just so I get what's happening there, you are setting the blind states into an array called covers, then piping that into the selectattr function to get a list of states, and if the number open states match the length of the array it's uses it?

mighty ledge
#
  {% set covers = [ states.cover.living_l_blinds, states.cover.living_r_blinds ] %}
  {% set open = covers | selectattr('state','eq','open') | list | length == covers | length %}
  {% if open %}
    mdi:window-shutter-open
  {% else %}
>   mdi:window-shutter
  {% endif %}
#

minus that arrow

#

no need for shutter-alert because that will never get hit

pale laurel
#

the only reason I have that in there is so when one goes offline for some reason, I'll notice

mighty ledge
#

Have you ever seen that Icon?

pale laurel
#

kind of a visible error handler

#

haven't tested it yet

mighty ledge
#

Yah, your current logic will never have that hit

#

this will:

pale laurel
#

gotcha

#

let's say a blind goes offline then, how do I have error handling to show me that?

mighty ledge
#
  {% set covers = [ states.cover.living_l_blinds, states.cover.living_r_blinds ] %}
  {% set open = covers | selectattr('state','eq','open') | list | length == covers | length %}
  {% if open %}
    mdi:window-shutter-open
  {% elif covers | selectattr('state', 'eq', 'unknown') | list | length > 0 %}
    mdi:window-shutter-alert
  {% else %}
    mdi:window-shutter
  {% endif %}
pale laurel
#

unknown or unavailable?

#

I just went and pulled the plug on one and it's state is unavailable

mighty ledge
#

Unknown

#

Well

#

See what it says on the states page

pale laurel
#

unavailable

mighty ledge
#

Use that then

pale laurel
#

kk

#

restarting everything and testing

#

then after I snapshot it I'll update to .7 again and see if that fixed it

#

I seriously felt like I was chasing my tail trying to figure out why the heck it wouldn't read that sensor

mighty ledge
#

It looked good but itโ€™s always good to remove unnecessary layers

pale laurel
#

everything seems to be good in .6, going to try it in .7

pale laurel
#

that fixed it!

#

thanks

bitter lagoon
#

How do I use templates?

dreamy sinew
#

{{ 1 + 2 }}

arctic sorrel
#

.topic @bitter lagoon

silent barnBOT
silent barnBOT
#

Carefully

arctic sorrel
#

~share @teal phoenix

silent barnBOT
teal phoenix
analog remnant
#

Hi guys, can somebody tell me what's wrong with this?

  - data_template:
      data:
        message: Warnung - SSL Zertifikat lรคuft in weniger als {{ trigger.to_state.state }} Tage(n) ab. Automatische Erneuerung ist fehlgeschlagen, Logs checken!
      service: notify.mobile_app_fabian_seins
    service: notify.mobile_app_fabian_seins```
Error: ```Error rendering data template: UndefinedError: 'trigger' is undefined```
#

ah, maybe because I trigger it manually?

#

...

charred dagger
#

Could be.

analog remnant
#

I'm so stupid

#

sorry to waste everyones time ๐Ÿ˜„

charred dagger
#

You also have a weird structure.yaml data_template: data: service: service:

#

You probably want yaml data_template: message: service:

analog remnant
#

That's the UI editor which messes up my order

arctic sorrel
#

The UI editor doesn't do templates ๐Ÿ˜‰

analog remnant
#

Yes, but If you add the template afterwards the order doesn't change from alone ๐Ÿ™‚

marble lily
#

Can someone help me with an template from seconds to days , hours, minutes? I tried a lot from home assistant community but no1 worked fine.

analog remnant
#

I think I have one but it has a little bug if I recall correctly

charred dagger
#

What do you have so far?

marble lily
#

'''

analog remnant
silent barnBOT
arctic sorrel
#

~codewall @marble lily

silent barnBOT
#

@marble lily Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.

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

marble lily
#

sorry. I didn't know that.

charred dagger
#

What is happening? What is not happening?

marble lily
#

proxmox_server_uptime
40 seconds ago
Unknown
Successfully saved

#

what need to be here: {% set time = states.sensor.proxmox_server_uptime_s.state %} , after the sensor? I'm getting data from netdata.

#

I get it working. ๐Ÿ˜„ thanks for the post.

charred dagger
#

Try putting one piece at a time into the editor in devtools ->Templates, and add things like {{ time }} here and there to print out the value of variables to see if they are what you expect.

analog remnant
#

What was the problem?

marble lily
#

I changed attributes.uptime with .state

analog remnant
#

Ok, I see, my sensor didn't have the uptime as the state but as an attribute but glad you could get it to work. The template should be fine and always display correctly. Glad I could help ๐Ÿ™‚

marble lily
#

And one more thing.

#

If I want to change the icon for this template sensor, i need to do in the customize.yaml?

analog remnant
#

Oh and one more thing, think about excluding that sensor from your recorder, otherwise it will fill up the database really fast, I had problems with my Pi crahsing when accessing the history panel

young jacinth
#

is is_not_state('sensor.pixel_3_alarm','set') valid? or how do i not with jinja templates?

#

{% if not is_state('sensor.pixel_3_alarm','set') %} this works

queen meteor
#

@young jacinth you can also do ```
{{ states('sensor.pixel_3_alarm') != 'set' }}

young jacinth
#

Thanks!

#

i guess {{ states('sensor.pixel_3_alarm') > 0 }} would work too?

#

{{ states('sensor.pixel_3_alarm') | float > 0 }} does work ๐Ÿ™ƒ

marble lily
#

I have an sensor for idle cpu (proxmox host), i can't get a usage cpu sensor. How can i Convert the idle to used?

#

100% - sensor?

arctic sorrel
#

Pretty much

#

Assuming it returns a value in the scale of 0-100

marble lily
#

yes, i get like 90.88% idle

arctic sorrel
#
sensor:
  - platform: template
    sensors:
      cpu_usage:
        friendly_name: "CPU Usage"
        unit_of_measurement: '%'
        value_template: "{{ 100 - (states('sensor.idle')|float) }}"
#

Test it out in devtools -> Templates

marble lily
#

Mhm it's working but i get like 1.519999999999996 %

#

I need to add an round(2) somewhere.

arctic sorrel
#
        value_template: "{{ (100 - (states('sensor.idle')|float))|round(2) }}"
``` probably
marble lily
#

you're a genius.

#

in a template can I sum multiple sensors?

rugged laurel
#

yes?

marble lily
#

on netdata i can get system%+user%+sftirq%+guest%

#

can i add all of that into one sensor?

rugged laurel
#

yes?

arctic sorrel
#

It's Jinja

marble lily
#

Thanks ๐Ÿ˜„

arctic sorrel
#

The best thing to do is just try stuff out in the Templates menu

rugged laurel
#

and look at the documentation

arctic sorrel
#

๐Ÿค”

#

That sounds like advanced thinking. Doesn't everybody just throw the manual out before trying to build something?

rugged laurel
#

There are manuals? ๐Ÿ˜ฎ

arctic sorrel
#

Which reminds me, must go through the 0.107 breaking changes now I've upgraded ๐Ÿ˜„

rugged laurel
arctic sorrel
#

Yeah, I've got them open, I'm just checking the little details now. I did my usual - upgrade, config check, fix the big things ๐Ÿ˜„

#

Looks like the only thing that snuck in was the addition of idle to the Sonos states

rose reef
#

hey all, what's the syntax to do else if in a template without nesting?

arctic sorrel
#

{% elif ... %}

rose reef
#

literally just found the example ๐Ÿ™‚ thanks

#

I'm using that power sensor I was looking at yesterday and using thresholds to infer a state

arctic sorrel
rose reef
#

oooooh nice documentation, thanks

dry bison
#

Hello
I'm not sure if this is the correct place
But there is a way to make templates more dynamic
I mean
I have for example 7 tplink outlet with energy meter
Also I have created utility meter for adding all of them to get the total amount of energy

#

But if I add a new outlet I need to copy from one and change the entity name and also add it to the utility meter section

#

There is some way to make this process more dynamic
Like using variables or something similar?

queen meteor
#

If you are trying to create sensors for each outlet you setup, you may have to copy and paste the code multiple times. You could however use some sort of variable custom component, and have an automation on state_changed event, and update those variables - defining those set of variables is static, populating dynamic values into those variables can be dynamic/real-time with just one block of code. You decide whether it is worth going through a custom component and set it up, or just duplicate the code.

#

On the other hand, having some sort of variable component can come in handy - it can also be used elsewhere. I personally found that to be very valuable for my setup

dry bison
#

@queen meteor
Any examples how to do it

bitter lagoon
#

I want to add this theme

#

but I dont have a lovelace-ui.config file

arctic sorrel
#

That's nothing to do with templates ๐Ÿ˜‰

bitter lagoon
#

where do I go for that

#

Ok

queen meteor
#

@dry bison I use something called input_label which is basically a sort of label placeholder - like variable. Since everything in Jinja is strings, it stores values as strings. I also have examples where I populate battery values of various sensors into those variables. Check out my repo for examples.

silent barnBOT
dry bison
#

@dry bison I use something called input_label which is basically a sort of label placeholder - like variable. Since everything in Jinja is strings, it stores values as strings. I also have examples where I populate battery values of various sensors into those variables. Check out my repo for examples.
@queen meteor thanks I will try to have a look but Im very newbie reading gitbub lol

acoustic hawk
#

is there any way to uuse a template to display the number of days until a time?

#

I.E "5 days, 3 hours, 2 minutes until X"

dreamy sinew
#

Yep, strftime which is listed on the ha template docs

#

And probably a timedelta claws

acoustic hawk
#

is a javascript template literal the same thing as an HA template?

dreamy sinew
#

No

silent barnBOT
queen meteor
#

If you know the number of seconds, you can display in the format you were lookin

acoustic hawk
#
var countDownDate = new Date("Aug 17, 2020 00:00:01").getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);    
return "Semester Starts in " + days + " days, " + hours "hours, " + minutes + " minutes, and " + seconds + "seconds";
#

ended up using this

queen meteor
#

ok.. thought you were looking to do in jinja - no limits on python!

acoustic hawk
#

i thought i was doing it in jinja too but the add-on i was using uses plain JS templates

unreal cave
#

hi, I have a template {{as_timestamp(states.binary_sensor.back_door_contact.last_changed) }}, it returns 1585527125.312935. I see the jinja helper example, and it's exactly what I want, to turn it into weeks/hours/minutes. How do I merge these segmets so that I can use it in a markdown card? I want to say "the back door was last opened 'weeks/hours/minutes' ago"

queen meteor
#

@unreal cave ```
{% set seconds = as_timestamp(now()) - as_timestamp(states.binary_sensor.back_door_contact.last_changed) |int %}
{%- set map = {'Week': (seconds / 604800) % 604800,
'Day': (seconds / 86400) % 7,
'Hour': (seconds / 3600) % 24,
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}
{%- for item in map if map[item] | int > 0 -%}
{%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
{{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor -%}

unreal cave
#

beautiful

queen meteor
#

this gives the time format you are looking for.... you need to make it into a sensor and display the value in markdown. Markdown is frontend, the and the code above is backend

unreal cave
#

yep works immediately, thanks so much.

#

wow this templating makes HA ridiculously awesome. feels like it goes on forever

queen meteor
#

there are limitations, but it gets you going pretty good once you get hang of it

unreal cave
#

how do you insert a space right after the variable script? it says "secondsago". only way I can get it to insert a space is {{ ' ' }}ago. must be an easier way

queen meteor
#

simple hack would be to add a space to the 'Second': (seconds %60) section...

unreal cave
#

cant, it has to come after the s

queen meteor
#

the reason I said hack is because I don't how what your script looks like. The code has - right after {% and before %}. you can remove that -.

unreal cave
#

the s is appended to week(s) hour(s) etc so you end up with spaces everywhere

queen meteor
#

can you post your code? May be I can show you exactly where to change that

unreal cave
#

oh, exactly, removing those - does it

#

those prevent preceding and following spaces?

queen meteor
#

yup - the hyphen removes white spaces

unreal cave
#

nice. learing.

queen meteor
#

best to play in the template editor

unreal cave
#

the back door was last {% if is_state('binary_sensor.back_door_contact', 'on') %} open {% else %} closed {% endif %}{% set seconds = as_timestamp(now()) - as_timestamp(states.binary_sensor.back_door_contact.last_changed) |int %}
{%- set map = {'Week': (seconds / 604800) % 604800,
'Day': (seconds / 86400) % 7,
'Hour': (seconds / 3600) % 24,
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}
{%- for item in map if map[item] | int > 0 -%}
{%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
{{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor %} ago.

#

so thats the code and it works beautiful now

queen meteor
#

@unreal cave also, you don't have to have to have if and else... you can simplify it into something like this if you want: ```
the back door was last {{ 'open' if states('binary_sensor.back_door_contact') == 'on' else 'closed' }} ...

unreal cave
#

now just need to swap the back door for all the doors automatically

stark perch
#

Hello guys.
I am using a geocoded location via the mobile_app for iOS. It delivers data in form of "Street 7\n6850 Dornbirn\nร–sterreich".
I tried to remove the \n with a template sensor.
value_template: >-
{{ (states.sensor.phone_geocoded_location.attributes["Name"] | string|regex_replace(find='\n', replace=' ', ignorecase=False))}}
Sadly it does not work. Any help would be appreciated.

queen meteor
#

Tried simple split and join?

blissful lantern
#

Hey all, using a icomfort thermostat, cant figure out how to change unit of measure to F.

#

climate:

  • platform: myicomfort
    name: firstfloor
    username: MYUSERNAME
    password: MYPASS
    system: 0
    zone: 0
    cloud_svc: lennox
arctic sorrel
#

You have to change your whole HA system to use imperial measurements

blissful lantern
#

ahh ok.

analog remnant
#

Hi guys, can I define a default value when calling a script with variables? Or do I have to always provide the script with the variables when calling it?

#

Like is there a template I can use to use a default value if the other variable isn't set

analog remnant
#

can somebody help me understand what's wrong with this script?

arctic sorrel
#

What error/problem are you getting?

analog remnant
#

none

#

If I remove the template and (both from payload_template and the templates inside the string) the siren sounds, only when I provide it with templates it doesn't do anything

arctic sorrel
#

That sounds like a problem ๐Ÿ˜‰

analog remnant
#

If I call the script via the dev-panel via service: script.sound_siren with the service_data: variables: duration: 1 strobe: true nothing happens, no error as well

#

Also I added a second sequence to create a persistent notification with the payload as a message and it looks like this:

#

{"warning": {"duration": 2, "mode": "emergency", "strobe": True}}

#

Ok, it has to do with the template, I've listened to what is being sent via mqtt and the template values are not sent

queen meteor
#

@analog remnant I'm no template expert, but shouldn't that be data_template: instead of data:?

analog remnant
#

Not according to the docs

#

But Iโ€™ll try that tomorrow, the persistent notification worked with data_template.

tranquil grove
#

Hi all, can anyone share their climate automation with me? I have been searching for one for awhile with no luck. Ideally i want my AC to turn on to heat when the temperature drops to a certain degrees and visa versa..

queen meteor
nocturne kiln
#

Can someone point me what I miss here, got Error rendering template: UndefinedError: 'None' has no attribute 'state' when try this:

{% if states.input_select.wul_alex_time_hour.state|round(0)|string|length == 1 %} {% set time = 0 %} {% endif %}
{% set time = time|string + states.input_select.wul_alex_time_hour.state|round(0)|string + ':' %}
{% if states.input_select.wul_alex_time_minute.state|round(0)|string|length == 1 %} {% set time = time|string + '0' %} {% endif %}
{% set time = time|string + states.input_select.wul_time_alex_minute.state|round(0)|string %}
{{ time }}
#

states.input_select.wul_alex_time_hour.state = 06
states.input_select.wul_alex_time_minute.state = 40 when I check them.

arctic sorrel
#

Rather than states.input_select.wul_alex_time_hour.state try states('input_select.wul_alex_time_hour') (etc)

nocturne kiln
#

I tried this, and it render, but with output 06:unknown ๐Ÿ˜›

{% if states('input_select.wul_alex_time_hour')|round(0)|string|length == 1 %} {% set time = 0 %} {% endif %}
{% set time = time|string + states('input_select.wul_alex_time_hour')|round(0)|string + ':' %}
{% if states('input_select.wul_alex_time_minute')|round(0)|string|length == 1 %} {% set time = time|string + '0' %} {% endif %}
{% set time = time|string + states('input_select.wul_time_alex_minute')|round(0)|string %}
{{ time }}

So its something with the 4th row, but cant figure out what.

#

This one {% set time = time|string + states('input_select.wul_time_alex_minute')|round(0)|string %}

#

haha, I had misspelled the name on that row. This is too early.

#

But one good thing, I wrote in the right channel ๐Ÿ˜‰

nocturne kiln
#

Templates are supported in - delay right?
like:

- delay:
        minutes: "{{ states('input_select.wul_alex_how_many_minutes') | int }}"
arctic sorrel
nocturne kiln
#

Then it should work. ๐Ÿ™‚

#

And it did ๐Ÿ™‚

little gale
#

how do you correct to 0 decimal place?

arctic sorrel
#

|round I think it is

little gale
#

am I doing this correctly to create a sensor with the temp data?

sensor:
      - platform: template
        sensors:
            temp:
                friendly_name: "Temperature"
                unit_of_measurement: 'Celsius'
                value_template: "{{ states('weather.datasky'),'temperature'|round }}"
silent barnBOT
#

YAML is the mark up language used by Home Assistant. Consistent indenting (two spaces per level) is key

little gale
#

issue with indentation?

arctic sorrel
#
sensor:
  - platform: template
    sensors:
      temp:
        friendly_name: "Temperature"
        unit_of_measurement: 'Celsius'
        value_template: "{{ state_attr('weather.datasky','temperature')|round }}"
#

Indentation and template

#

I'm assuming your entity is valid, and you're not using DarkSky

little gale
#

i am using dark sky. why?

buoyant pine
#

weather.datasky

arctic sorrel
#
sensor:
  - platform: template
    sensors:
      temp:
        friendly_name: "Temperature"
        unit_of_measurement: 'Celsius'
        value_template: "{{ state_attr('weather.dark_sky','temperature')|round }}"
``` would have the actual entity correct
little gale
#

how do you add the colors like that?

buoyant pine
#

add yaml to the end of your backticks

#

the first set

buoyant pine
#

```yaml

little gale
#

damn thanks for the tip

little gale
#

so I saved this and restarted HA but no sensors showed up, nothing in the logs

  - platform: template
    sensors:
        temp:
            friendly_name: "Temperature"
            unit_of_measurement: 'Celsius'
            value_template: "{{ state_attr('weather.dark_sky','temperature')|round }}"
        humidity:
            friendly_name: "Humidity"
            unit_of_measurement: '%i'
            value_template: "{{ state_attr('weather.data_sky','humidity') }}"
buoyant pine
#

you should see sensor.temp and sensor.humidity

#

you still have weather.data_sky in the second one. also confirm that the entity ID is in fact weather.dark_sky

#

finally, you can test templates at developer tools > template. helpful before using in template sensors

little gale
#

you still have weather.data_sky in the second one. also confirm that the entity ID is in fact weather.dark_sky
@buoyant pine intentional as dark sky also provides that info.

silent barnBOT
arctic sorrel
#

~codewall @little gale

silent barnBOT
#

@little gale Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.

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

arctic sorrel
#

Test templates in devtools -> Templates

little gale
#

not sure how

#

do you think that code is correct?

buoyant pine
#

delete the stuff in the text field and paste this in:

{{ state_attr('weather.dark_sky','temperature')|round }}
#

and this:

{{ state_attr('weather.data_sky','humidity') }}
#

and check the output

#

again, check that the entity IDs you're using in the templates are correct. you're using weather.dark_sky in one and weather.data_sky in another

#

also again, you should see sensor.temp and sensor.humidity at developer tools > states

little gale
#

delete the stuff in the text field and paste this in:

{{ state_attr('weather.dark_sky','temperature')|round }}

@buoyant pine this outputs it correctly although the other one says None

buoyant pine
#

because the entity ID is wrong

#

i've said that like three times at this point lol

little gale
#

ok scratch the humidity sensor

#

the temp sensor doesnt show up in States

buoyant pine
#

dude, change the entity ID in the humidity template sensor to weather.dark_sky

#

also run a config check:

silent barnBOT
#

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

little gale
#

It's literally that

  - platform: template
    sensors:
        temp:
            friendly_name: "Temperature"
            entity_id: weather.dark_sky
            device_class: temperature
            unit_of_measurement: 'Celsius'
            value_template: "{{ state_attr('weather.dark_sky','temperature')|round }}"
        humidity:
            friendly_name: "Humidity"
            entity_id: weather.dark_sky
            device_class: humidity
            unit_of_measurement: '%i'
            value_template: "{{ state_attr('weather.data_sky','humidity') }}"
buoyant pine
#
{{ state_attr('weather.data_sky','humidity') }}
#

no, it's not. you don't need the entity_id: weather.dark_sky part anyway

#

and that's the first time we're seeing that part

little gale
#

well I tried to paste it but...

buoyant pine
#

what does a config check show?

little gale
#

Configuration valid!

buoyant pine
#

the config check command, not the UI check

little gale
#

I need to SSH in for this?

arctic sorrel
#

Yup

little gale
#

This is a supervised installation and this is what docker exec home-assistant python -m homeassistant --script check_config --config /config output:

silent barnBOT
#

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

little gale
#
pi@pi4:~ $ docker exec home-assistant python -m homeassistant --script check_config --config /config
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/home-assistant/json: dial unix /var/run/docker.sock: connect: permission denied
arctic sorrel
#

Click the link above

buoyant pine
#

sudo

little gale
#

sudo?

arctic sorrel
#

With Home Assistant

#

See that line?

#

Read that line

#

Follow that line

little gale
#
pi@pi4:~ $ sudo docker exec home-assistant python -m homeassistant --script check_config --config /config
Error: No such container: home-assistant
arctic sorrel
buoyant pine
#

you actually can run the docker config check command on the host with a supervised install, but the container name is likely homeassistant, not home-assistant

#

but that's not explained in the docs, so i guess it's unofficial

little gale
#
pi@pi4:~ $ sudo docker exec homeassistant python -m homeassistant --script check_config --config /config
Testing configuration at /config
pi@pi4:~ $ 
buoyant pine
#

if the config check comes back ok and there are no errors in the log, then the sensors should be at developer tools > states

arctic sorrel
#

Assuming you restarted

buoyant pine
#

yup

little gale
#

yeah did that again and it showed up

marble lily
#

sensor:

  • platform: template
    sensors:
    cpu_usage:
    friendly_name: "CPU Usage"
    value_template: "{{ (15.53 - (states('sensor.proxmox_memory_free')|float))|round(2) }}"
#

I get a string on value_template, I don't understtand what i'm doing wrong.

#

Nevermind, that "" on front and end.

dreamy sinew
#

what comes out of a template is always a string

marble lily
#

value_template: {{ (15.53 - (states('sensor.proxmox_memory_free')|float))|round(2) }} - i get an error on vscode : incorrect type.

spiral imp
#

I have the following script set up to play a particular playlist on a particular speaker. If I set up an input_select for each of my speakers, could I replace "living_room" below with a template that would pull in the speaker name that I selected?

play_70s:
  alias: Play 70s
  sequence:
    - service: media_player.shuffle_set
      data:
        entity_id: media_player.sonos_living_room
        shuffle: "true"
    - service: media_player.select_source
      data:
        entity_id: media_player.sonos_living_room
        source: 70s Road Trip
queen meteor
#

@spiral imp simple answer is yes. It looks like a script, and assuming you are calling that script from an automation, you could pass parameters to it.

little gale
#

Keep getting this error

Invalid config for [sensor.template]: value is not allowed for dictionary value @ data['sensors']['aqi']['device_class']. Got 'pm25'. (See ?, line ?).
silent barnBOT
arctic sorrel
#

Show us the config so we don't have to guess ๐Ÿ˜‰

little gale
#
        aqi:
            friendly_name: "AQI"
            device_class: pm25
            value_template: "{{ state_attr('sensor.waqi_belur_math_howrah_india','pm_2_5') }}"
arctic sorrel
#

There's your problem ๐Ÿ˜‰

#

That's maybe a unit of measurement

#

It's certainly not a class

little gale
#

All sensors that have pm25 as part of their entity_id or pm25 as their device_class

#

as per homekit kb

#

I don't think there's a unit of measurement

arctic sorrel
#

Looks like the HomeKit docs are wrong

#

And yes there is, if there wasn't I wouldn't mention it

#

Looks like for HomeKit purposes you need to add pm25 to the entity

little gale
#

no device_class then?

arctic sorrel
#

Have a read for yourself ๐Ÿ˜‰

little gale
#

Invalid config for [sensor.template]: Entity ID pm25 is an invalid entity id for dictionary value @ data['sensors']['aqi']['entity_id']. Got 'pm25' value is not allowed for dictionary value @ data['sensors']['aqi']['device_class']. Got 'pm25'. (See ?, line ?).

arctic sorrel
#

It's nice not to have to ask somebody for the error for once, but the error without the context is pretty much pointless ๐Ÿ˜‰

#

Also, check the docs, see if the thing your doing is valid

#

You still haven't fixed your device class error either

little gale
#

AQI doesn't have a unit of measurement

arctic sorrel
#

๐Ÿคฆ

little gale
#
        aqi:
            friendly_name: "AQI"
            entity_id: pm25
            unit_of_measurement: ''
            value_template: "{{ state_attr('sensor.waqi_belur_math_howrah_india','pm_2_5') }}"
```:
```css
Invalid config for [sensor.template]: Entity ID pm25 is an invalid entity id for dictionary value @ data['sensors']['aqi']['entity_id']. Got 'pm25'. (See ?, line ?).
arctic sorrel
#

aqi: - that forms the entity_id

#

That is the thing you should be changing

#

Set the unit of measurement to something to get a pretty graph

little gale
#

I thought that was user customizable?

arctic sorrel
#

what?

little gale
#

sensor names are entity_ids?

arctic sorrel
#

When you define a template sensor, the tag you use to define it forms the entity_id

#

You're defining sensor.aqi

#

If you want to add pm25 as specified in the homekit docs, add it there

#

aqi_pm25: for example

little gale
#

that would work?

#

with homekit?

arctic sorrel
#

๐Ÿคท

#

According to the docs you pasted from yes

little gale
#

its working now, thanks

ebon yoke
#

i have a bit of an unstable rest api i'm calling to get data in.. a few template sensors are based on input from this.. what happens is that if the rest api is not working correctly, then these integer sensors are reset to 0

#

can i work around that somehow?

#

because i have an automation that will trigger if the sensor increases

#

i have a template condition like this: "{{ trigger.to_state.state | int > trigger.from_state.state |int }}"

arctic sorrel
#

You could check to see if the state isn't zero?

ebon yoke
#

0 is still a valid value.. most of the sensors are in fact 0

#

but what i want to catch is a value going from positive, non-zero to 0 and then back to the same positive, non-zero number

#

because that's what happening

spiral imp
#

Trying to trigger an automation when any input is selected except "None". Is this correct syntax?

value_template: "{{ not is_state('input_select.sonos_playlist', 'None') }}"
buoyant pine
#

yes, but it will only trigger when the template evaluation goes from False to True

#

assuming you're using that in a template trigger

spiral imp
#

got it, yes, I am

buoyant pine
#

the solution is to make the trigger a simple state trigger with that input_select entity ID and no to or from

#

then use what you have as a condition

#

assuming you want it to trigger any time the input is changed as long as it's not 'None'

spiral imp
#

I was worried that if I had "not None" as a condition, that it would not fire if None was the current input

#

yes, that is exactly what I want to happen

#

Like so?

  alias: 'Play Sonos'
  trigger:
    - platform: state
      entity_id: input_select.sonos_playlist
  condition:
    - platform: template
      value_template: "{{ not is_state('input_select.sonos_playlist', 'None') }}"
buoyant pine
#

yup, looks good

spiral imp
#

Config doesn't like 'None'

buoyant pine
#

probably because it's a reserved python word

#

None

#

thought it might not be an issue since you're making it a string by using quotes

arctic sorrel
#

Should be fine in quotes

buoyant pine
#

that's what i thought... what's the error Cosco?

spiral imp
#

getting errors in quotes too

#

Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/includes/automation.yaml", line 478, column 7
expected <block end>, but found '<scalar>'
in "/config/includes/automation.yaml", line 479, column 72

buoyant pine
#

you're missing the hyphen before alias:

#

if you're not using !include_dir_list for your automations then that's the problem

spiral imp
#

I can just use a word besides "none". I have a hypen, it is in the line above with id:, i just didn;t paste it, sorry

silent barnBOT
buoyant pine
#

oh you have double quotes inside double quotes

#

that's an issue

#

this:

"{{ not is_state('input_select.sonos_playlist', "None" ) }}"
``` should be:

"{{ not is_state('input_select.sonos_playlist', 'None' ) }}"

arctic sorrel
#

~codewall @spiral imp

silent barnBOT
#

@spiral imp Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.

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

buoyant pine
#

dat 2

spiral imp
#

Tried that and also tried changinh 'None" to 'Walrus' (just for fun), I still get this config error: Invalid config for [automation]: Unexpected value for condition: 'None'. Expected numeric_state, state, sun, template, time, zone, and, or, device @ data['condition'][0]. Got None. (See /config/configuration.yaml, line 118).

buoyant pine
#

oh. platform: template under condition should be condition: template

#

forgot to mention that, sorry

spiral imp
#

so this:

  trigger:
    platform: state
    entity_id: input_select.sonos_playlist
  condition:
    - condition: template
      value_template: "{{ not is_state('input_select.sonos_playlist', 'None' ) }}"
buoyant pine
#

no

spiral imp
#

sorry, just fixed it

buoyant pine
#

all good

#

yeah looks good now

spiral imp
#

yep, its working,. Have a few other things to sort out but the template is good

#

thanks

buoyant pine
#

no prob

vernal girder
#

I created a template sensor to pull information from another sensor and do a little processing, I initially screwed this up and forgot to cast the result to a float so the first value in the history of my template sensor is a string so I'm unable to use the Lovelace history-graph card to show a plot of this sensor. Is there a way to delete the history of a given entity?

queen meteor
#

@vernal girder you can use SQLite to edit the database if you use default database to log events and states

vernal girder
#

@queen meteor Thanks, I deleted the entities completely and that got my plots working correctly.

latent spear
#

I wonder if anyone could help me, I'm trying to create a button that would toggle between two scene, I have a scene called cinema_on and another called cinema_off . basically they just change philips hue tints. I couldn't figure how to make that work with a button card. I've been able to do something similar using the custom:button-card with a group but scene aren't working the same way it seem.

queen meteor
latent spear
#

thx!

edgy dirge
#

what is this error all about Unable to load the panel source: /api/hassio/app/entrypoint.js.

#

my HA stopped working

#

hw to resolve

inner mesa
indigo basin
#

I'm using the bwalarm component and this used to work (on a much older version);

#

'ALARM TRIGGERED!!! {{ states[states.alarm_control_panel.house.attributes.changed_by.split(".")[0]][ states.alarm_control_panel.house.attributes.changed_by.split(".")[1]].name }}'

#

It now gives me;

#

Error rendering template: str: Invalid domain name ''

#

Any ideas?

charred haven
#

Trying to write a template binary sensor based on users from tautullii that are actively playing something on plex instead of just paused....not sure how to properly loop over attributes for each user to determine teh proper Activity value. Anyone have any pointers on this?

#

each user shows up as an attribute but the value is in JSON {'Activity': None} so its a bit difficult to iterate

#

like if i just want to display which users are not None this code isnt working and just displays every single attribute even ones that don't have ['Activity'] attribute https://hastebin.com/dajofejabu.php

willow cosmos
#

Hi - anyone know what I'd put in a template to get the number of hour since 06:00 each morning?

weary jasper
#

@heady crow

  - platform: template
    sensors:
      kitchen_table_dimmer_state:
        friendly_name: 'Kitchen Table Dimmer Last Button Push'
        value_template: >-
                      {% if states('sensor.kitchen_table_dimmer_state_2')[0] == "1" %}
                        On
                      {% elif states('sensor.kitchen_table_dimmer_state_2')[0] == "4" %}
                        Off
                      {% else %}
                        None
                      {% endif %}
#

replace relavant info

heady crow
#

@weary jasper sorry, not sure what tis is response to

weary jasper
#

didnt you want yes or no instead of off and on?

heady crow
#

yeah sorry, confused me as you responded in a different channel

#

i thought it was something id have to do in the customize UI editor

#

ill try and learn how to make the above work for me

weary jasper
#

templates are powerfull but tricky to learn ....test in dev>template

heady crow
#

Ill give it a go

#

where is dev-template?

weary jasper
heady crow
#

oh cool

#

so thats like a sandbox section

#

for testing templates

weary jasper
#

yes sir

heady crow
#

awesome

#

thank you for your help

#

more learning for me ๐Ÿ™‚

#

between has and nodered, crazy amounts of hours are lost

lunar osprey
#

Hello, I need to add/delete a string from an input_text depending on an input_boolean

#

{% if is_state('input_boolean.deebot_cucina', 'on') %}
'{{states(''input_text.valuestanze'')}}Cucina, '
{% else %}
'{{states(''input_text.valuestanze'') | replace("Cucina,", "")}}'
{% endif %}

#

What is wrong here?

weary jasper
#

remove quotes ie:

- service: light.turn_off
        data_template:
          entity_id: light.kitchen
          transition: >-
              {% if is_state("input_boolean.boolean_evening_time", "on") %}
              {{ states('input_number.evening_mode_transition_value') | int }}
              {% elif is_state("input_boolean.boolean_movie_time", "on") %}
              {{ states('input_number.movie_mode_transition_value') | int }}
              {% elif is_state("input_boolean.boolean_sleep", "on") %}
#

damn i suk at pasting ๐Ÿคฃ

rugged laurel
#
"{{ states('input_text.valuestanze') + 'Cucina, ' if is_state('input_boolean.deebot_cucina', 'on')  else states('input_text.valuestanze') | replace('Cucina,', '') }}"
lunar osprey
#

Thanks I will check

#

@rugged laurel this is not working

rugged laurel
#

it is

#

if it's not working for you:
a) you are using it wrong.
b) the data you pasted is worg
c) ๐Ÿคทโ€โ™‚๏ธ

lunar osprey
#

I fixed it, thanks!

weary jasper
#

@rugged laurel show off

lunar osprey
#

{% if is_state('input_boolean.deebot_aurora', 'on') %}
{{states('input_text.valuestanze') + "Aurora, "}}
{% else %}
{{states('input_text.valuestanze') | replace("Aurora, ", "") }}
{% endif %}

#

Why it doesn't add the space at the end?

#

๐Ÿ˜ฆ

rugged laurel
#

How about you tell the whole story, what are you trying to do?

lunar osprey
#

I need to concatenate strings depending on 8 booleans flag

#

add if flag is on

#

remove if flag is off

#

if works, but when Adding, it doesn't add the space at the end....

#

"Aurora, "

#

--> This space

#

I read that jinja trims automatically

rugged laurel
#
{% set bools = [
 {"entity": "input_boolean.deebot_aurora", "name": "Aurora"},
 {"entity": "input_boolean.deebot_cucina", "name": "Cucina"}
] %}
{% set stuff = namespace(names=[]) %}
  {% for bool in bools %}
    {% if is_state(bool["entity"], "on") %}
      {% set stuff.names = stuff.names + [bool["name"]] %}
    {% endif %}
  {% endfor %}
{{ stuff.names | join(", ") }}

Expand the top part to fit your need

lunar osprey
#

My problem was different

#

I need the space at the end

#

and Jinja trim it automatically

#

btw I fixed it, thanks!

queen meteor
#

If you are new to templates, there is something called Template Editor. You can write template code in that editor and test the results. Go to developer tools -> Templates, clear the text you see there and paste your code. Refresh page to restore defaults.

queen meteor
#

It is surprising that many folks donโ€™t see the template editor until they come here. Hoping this pinned message will help (only if they care to read pinned messages).

weary jasper
#

@queen meteor do a server ping to all to notify

queen meteor
#

lol. It is not that urgent ๐Ÿ˜‚

#

Although, it could be part of welcome message. Not that people read that too.

weary jasper
#

@queen meteor a required checklist ....know where dev templates is and etc and it only checks the box if you navigated to it

queen meteor
#

Oh man, love that idea. Not sure if discord lets you implement that way. @weary jasper

#

Discord should not let folks post any messages until they acknowledge some required things.

dreamy sinew
#

Could probably bot some things

weary jasper
#

@queen meteor make it happen sir ... you got my vote

wet drum
#

Hi! How can I get the Device an entity belongs to within a template? I want to get a list of the device names of all the devices that have an entity with the attribute 'update_available' set to True.

#

The entity_id of the matching states are something like binary_sensor.0x1234567890ab_update_available, part of a device with the name 0x1234567890ab

#

(These are the zigbee2mqtt devices for which an OTA update is avaliable)

#

It would be more natural to loop over all devices and filter out the ones that have such an entity, but I see no documentation that devices are even accessible in templating.

lunar osprey
#

@queen meteor very helpful!!! Thanks.

silent barnBOT
#

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

#

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

high lagoon
#

how can i get the sensor to show only the degrees?

#

Can it be done in the sensor with some kind of value_template or do I need to get it done in the automation publishing it?

robust nexus
#

Does anyone know if it's possible to list everything in a group as entities in an entities card?

arctic sorrel
#

It's not, not with a stock card anyway

willow cosmos
#

@robust nexus timkerer is right, in case you don't know which custom cards enable it, take a look at auto-entities. Or see fold-entity-row for a different take on it.

spiral imp
#

is there a way to template a group so that it only includes switches that are on or a way to template a script to only turn off switches that are on?

arctic sorrel
#

If they're already off, turning them off shouldn't do anything

spiral imp
#

I use template switches to join my Sonos speakers. I have them all in group. I have script to turn off the group (unjoin all speakers), but doing this also stops music playing from the master speaker

robust nexus
#

Thanks @willow cosmos I'll take a look at them both.

light garnet
#

I'm trying to set up some template sensors for a Tuya heater so I can track the on/off status over time, changes to the target temperature and current temperature better. I have some questions:

  1. For unit_of_measurement what is the syntax for degrees centigrade?
  2. For on/off do I need to do anything special or can I just specify no unit_of_measurement?
  3. Any other advice for getting values from Tuya devices?
#

Aware that may be a different kind of template to what is being discussed here!

tulip plover
#

I have this template that works on the dev tab but does not seem to work when I turn it into a sensor value template. Any advice?

 
    sensors:
      octoprint_time_elapsed_format:
        friendly_name: 'Printing Time Elapsed'
        value_template: "{{ states('sensor.octoprint_time_elapsed') | int | timestamp_custom('%H:%M:%S', 0) }}"
queen meteor
#

do you see any errors in the logs?

tulip plover
#

I do not

#

when I add that sensor it just shows 00:00:00

queen meteor
#

you could try giving entity_id.

stray cape
#

Anyone that can help with - platform: history_stats?
I have it that my device is publising state now but the stats is still not counting
sensor:

  • platform: version

history of flow meter

#daily

  • platform: history_stats
    name: flow_rate_daily
    entity_id: binary_sensor.flow_state
    state: ON
    type: time
    start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
    end: '{{ now() }}'
#

Sorry... I'm not sure if this is the right area to post about this.

buoyant pine
#

@stray cape state: ON likely should be state: 'on' (the quotes around on and the case are important)

#

Confirm the state at developer tools > states

stray cape
#

Damn you are good.. THANKS @buoyant pine !!! it worked right away... I've been strugling with this for the last 2 days...

#

sadly... now that is working I'm realizing that it is not going to give me what I want.... DAMN... wasted so much time on this....

#

have to rethink this thing and find the right area to ask about it... THANKS a lot for your help!!!

buoyant pine
#

No prob! Yeah, states are case sensitive and using quotes around them is a good idea (except for numbers in some cases)

stray cape
#

will remember the next time LOL!!!

lofty sphinx
#

Hey guys I'm having a hard time with something that should be simple. I have a input_select that cycle between color names ("blue", "red", "green"...) but I can't make it work on a color_name. I use it like this:
color_name: "{{ states('input_select.light_color_cycle') }}"

And what I get on log is:

  • Got unknown color {{ states('input_select.light_color_cycle') }}, falling back to white

Weird thing is that the same works on a notification with message: "{{ states('input_select.light_color_cycle') }}" - I get a notification with "blue" on.
Any ideas? Thanks!

buoyant pine
#

@lofty sphinx looks like you're not using data_template:

#

But...you should share all the relevant code so we can see.

silent barnBOT
lofty sphinx
#

@lofty sphinx looks like you're not using data_template:
@buoyant pine That was it wail thanks!

buoyant pine
#

Lol no prob

lime olive
#

I've been loving using state_filter card with the header_toggle...

I understand that we can't use header_toggle as an entity but is there a way to implement something similar?

I use it to turn of devices of choice off at night

rugged laurel
#

yes

#
{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}
lime olive
#

That looks awesome. What goes in between (", ")?
Also where should I put this template? Binary sensor? ๐Ÿ˜

rugged laurel
#

Nothing.
As the value of entity_id in a script/automation

lime olive
#

Nice, Ok I'll give it a go.
Thanks mate

sinful plume
#
{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}

@rugged laurel Really awesome, thanks!

lime olive
#

The template works in the template section in developer tools but sorry I can't seem to implement it as a script

  sequence:
  - data:
      entity_id: '{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}'
    service: light.turn_off
arctic sorrel
#

Rule #1 of templating

silent barnBOT
lime olive
#

I have tried data_template instead of data and it didn't work

arctic sorrel
#

Well, with data: it can't work

lime olive
#

lol I did try service_template also but still no dice

#

Stop torturing me and give me the answer lol

#

This is the error

can not read an implicit mapping pair; a colon is missed at line 676, column 123:
     ... ity_id') | list | join(', ') }}'
                                         ^
buoyant pine
#

You need double quotes on the outside

#

"{{ ... }}"

upbeat saffron
#

How do you assign a switch template to an automation?

buoyant pine
#

The quotes on the outside and inside of the template can't be the same

#

@upbeat saffron use the switch. entity?

upbeat saffron
#

@buoyant pine Thanks, I'd doing that, but the GUI doesn't show it as a device and if I remove the device_id I get a domain error

arctic sorrel
#

devtools -> States for the list of all entities

silent barnBOT
#

The Devices and Entities views under Configuration don't show every entity in your system. If you want to see everything, look under Developer Tools then States.

lime olive
#

Thanks @buoyant pine

  sequence:
  - service_template:
      entity_id: "{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}"
    service: light.turn_off

Still not working

buoyant pine
#

What's the error

lime olive
#

All good, had to change service_template to data_template
Goes against the template rules #1
You must use service_template in place of service when using templates in the service section of a service call.
I guess not in this case....

#

Thanks anyway @buoyant pine

arctic sorrel
#

That's rule #2 ๐Ÿ˜‰

lime olive
#

yeah that lol

#

Now tell me, how can I specify which lights I was in that group instead of all? ๐Ÿ˜„

buoyant pine
#

@lime olive you use service template instead of service when you're templating a service

#

You're templating service data in your template

#

Thus data template... so the docs are correct

#

I didn't even notice that you used service template there lol

#

For example:

service_template: "script.lights_{{ trigger.to_state.state }}"
lime olive
#

Right! Gotcha now. I'll prob fall victim to this again next time

dreamy sinew
#

you could make a group of lights and iterate through that instead

#

or make a light.group and just use that

silent barnBOT
lime olive
#

So I can't incorporate specific entities within this template?

buoyant pine
#

Wait...why not just use entity_id: all here?

lime olive
#

no filter named 'all'

dreamy sinew
#

not with that template

#

there are ways

#

depends on what you're actually doing

lime olive
#

Well I basically wanted to mimic the header_toggle on a state_filter card that I have.
I use it to switch off all the lights that are on before bed

#

and so Ludeeus came up with that great template

dreamy sinew
#

the code as provided will turn off all lights that are on

#

which was the original AC

lime olive
#

yeah that's the problem now. I'd like to specify which because some are night lights

dreamy sinew
#

Acceptability Criteria

#

which do you have more of, night lights or daytime lights?

lime olive
#

daytime

#

Also if I can somehow include other entities like scripts for my gate and garage switches etc that would be great!
To make sure they're closed

dreamy sinew
#

do other service calls in the sequence

#
{% set night_lights = ['light.honeywell_39351_zw3005_inwall_smart_dimmer_level'] %}
{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', night_lights)| join(', ') }}```
#

for example, that works on my system

lime olive
#

Yeah that look like it'll do the job nicely! Thanks mate

dreamy sinew
#

could put all the night lights into a group and make another list out of them if you wanted but that's the jist

queen meteor
#

phnx vs phoenix ๐Ÿ™‚

dreamy sinew
#

Lol didn't notice that ๐Ÿคฃ

queen meteor
#

lmao

dreamy sinew
#

That reject filter is kinda obnoxious. It's not super clear how it works from the jinja2 docs

queen meteor
#

Yeah. Most things (like filters) that are available in Jinja is not available in HA too. We have to explicitly code for them.

hardy swallow
#

I was using this wait_template with my google home device:

wait_template: "{{ is_state('media_player.home', 'idle') }}"

And all was working as expected. Now i want to use that template with one of my echo devices and used this template:

wait_template: "{{ is_state('media_player.echo_show_5', 'idle') }}"

But i noticed the echo devices doesnโ€™t go to idle state as it remains always in standby state so the template doesnโ€™t work.

How to change that template to have the automation working again ?

lime olive
#

Now the question is how can I incorporate this with the multiple domains into one script?
This obviously is a no go

  sequence:
  - data_template:
      entity_id: "{% set ignore = ['switch.bedroom_power', 'light.night_light', 'media_player.bedroom_gh', '', '', '', '', ''] %}
{{ 
dict((states.switch|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', '), 
dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', '), 
dict((states.media_player|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', ') 
}}"
    service: light.turn_off
rich yacht
#

You cant light.turn_off a switch or media_player but you can homeassistant.turn_off a switch and light

#

seems it works for media_player too

lime olive
#

Nice, can it also control other domains like mediaplayer?
For now my only solution was

  sequence:
  - data_template:
      entity_id: "{% set ignore = ['light.office_1', 'light.office_2', 'light.office_3', 'light.cinema_1', 'light.cinema_2', 'light.cinema_3', '', '', '', '', '', ''] %}
{{ dict((states.light|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', ') }}"
    service: light.turn_off
  - data_template:
      entity_id: "{% set ignore = ['switch.receiver_vol_up', 'switch.all_blinds', 'switch.bedroom_main_2', 'switch.christmas_tree_2', 'switch.porch_blinds', '', '', '', ''] %}
{{ dict((states.switch|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', ') }}"
    service: switch.turn_off
  - data_template:
      entity_id: "{% set ignore = ['', '', '', '', '', '', '', ''] %}
{{ dict((states.media_player|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | reject('in', ignore)| join(', ') }}"
    service: media_player.turn_off
#

Oh ok cool! I'll do that instead then, thanks!

rich yacht
#

If you are turning the same things off every time then why not just create a scene? I have a bedtime scene that turns anything that should be off off

lime olive
#

Good idea too but I'm constantly adding new devices that don't need to stay on when going to bed or when we leave the house (arming the alarm)

#

This way I'm not gonna have to add new devices, just add the ones I'd like to ignore

jagged obsidian
#

nifty

lunar osprey
#

Hello

#

I have this code snippet

#

params:
cleanings: >
{%- if is_state('input_boolean.deebot_times', 'on') -%}2{%- else
-%}1{%- endif -%}
rooms: >
{{states('input_text.idstanze')[:-1]}}

#

I got this result...

#

('async_send_command %s (%s), %s', 'spot_area', {'cleanings': '2', 'rooms': '6'}, {})

#

instead I should have this one

#

('async_send_command %s (%s), %s', 'spot_area', {'cleanings': 2, 'rooms': 6}, {})

#

without the apex next to 2 and 6

#

how shall I do it?

waxen rune
#

I'd like to have a sensor to show if the coffee machine is brewing or just warming. the wall plug reports power so I can template from that - but the pattern is like "if power > 0, then if power > 750w for more than 45 s = brewing else keeping hot"

basically: is there a "duration parameter" in templates?

or do I need to create a helper sensor and an automation that set the helper sensor's state after a duration?

wise arrow
#

750w? Jewsus Christ do you have an industrial coffee machine? lmao

buoyant pine
#

Many are like that actually

wise arrow
#

@buoyant pine really? I have a medium sized brewer, I'm would be surprised if it pulled more than 200w when heating

buoyant pine
#

Yeah, my small single-serve one is 650W, the large 12-cup one is 1200W

dreamy sinew
#

hmm, i haven't checked to see what mine is

buoyant pine
#

Gotta heat that bitch up real fast

wise arrow
#

Wtf I redact that

#

I just checked mine

#

1450w

buoyant pine
#

Yup

dreamy sinew
#

lol

buoyant pine
#

But it's only for a short period of time

#

Just like a microwave

dreamy sinew
#

instant water heaters are intense

buoyant pine
#

Also why kitchens in the US at least have been required to have 20A circuits for a long time

wise arrow
#

But you have puny 110v

buoyant pine
#

Indeed

#

Well, AC is 240V at least

dreamy sinew
#

mine is 1500w apparently

wise arrow
#

Which is a lot at 110v, not that bad at 220v

buoyant pine
#

12.5 A at 120V

dreamy sinew
#

13.636A

wise arrow
#

Which in Norway would mean a second level fuse in older houses

buoyant pine
#

It's 120 at the outlet...with resistance it might go down to around 110

dreamy sinew
#

ah ok

wise arrow
#

We used to have mostly 10a, then we got 13a on the same wires, but 16a would be one step up in wire diameter, and 25 would be even one more step up

dreamy sinew
#

still sub 20 ๐Ÿ˜›

buoyant pine
#

Yup

nocturne kiln
#

{{ states.light | count }} <-- this will count all entities under the light domain. But is there a way to just count them that isn't Unavailable ?

dreamy sinew
#

{{ states.light|rejectattr("state", "eq","off")|list |count }}

#

change off

#

and probably change all the quotes, i was lazy

nocturne kiln
#

Oh thanks!

steep kiln
#

when adding two values I need |int for the sensor value right?

dreamy sinew
#

int or float

#

otherwise you get string math which is the bad kind of math

#

"4" + "5" = "45"

steep kiln
wise arrow
#

Bad math lmao

steep kiln
#

ah |float

#

ok

#

thanks

#

and to get this senor updated I add entity_id: of one sensor

#

preferably the one that changes most of the time

#

right?

arctic sorrel
#
        value_template: "{{ (states('sensor.sonoff01_momentane_leistung'))|int + (states('sensor.sonoff02_momentane_leistung'))|int +  (states('sensor.fibaro_system_fgwpef_wall_plug_gen5_power'))|int   }}"
``` will result in the template sensor updating if any of those update
steep kiln
#

cool thank you

waxen rune
#

as a part two of my question earlier, the pattern on the coffee machine is like this:
https://imgur.com/a/x91qPRc
..so full power for like 3,5 minutes while brewing, then full power for ~20 secs every five minutes.
the goal it to show "brewing", "keeping warm", "off" to for use on dashboard and in automations.
hmm.. suggestions on how to make some kind of smart template sensor showing the status from that?

..or maybe it's time to change to #automations-archived

dreamy sinew
#

you could probably get complex with a template, but the simpler solution would just be "heating" vs "not heating"

ivory delta
#

First attempt at templates and not really getting it. I want to loop through my sensors to extract information about my GitHub repos but I'm struggling to even identify which sensors are repos in the first place.

I've got this so far, ({{ sensor }}) will be replaced with more meaningful data once I can select the sensors I want.

All repos:
{% for sensor in states.sensor %}
  {% if state_attr(sensor, 'latest_commit_sha') %}
    {{ sensor }}
  {% endif %}
{% endfor %}

Any ideas how I fix the loop to identify repos?

vagrant monolith
#

What math is used to make an sensor based on battery charging and battery level to make an sensor say average battery chargign time

humble beacon
#

Can anyone please help?

#
"{{ dict((states.media_player|list)|groupby('state'))['on'] | map(attribute='entity_id') | list | join(', ') }}"
#

how must it look like, if i need state 'on' and state 'playing'?

rugged laurel
#

must?, have no clue... can, like this:

"{%set c=namespace(e='entity_id',o='on',p='playing',d=dict((states.media_player|list)|groupby('state')))%}{{((c.d[c.o]|map(attribute=c.e)|list)+(c.d[c.p]|map(attribute=c.e)|list))|join(', ')}}"
humble beacon
#

This is cool. Thank you very much!

still harbor
#

Hi guys, is there a template I can use to manually colorloop some lights using hs_color? Thanks

viscid parcel
#

There's no media_player template is there?

#

I know there's the Universal Media Player but it's a bit unclear whether it can do what I want it to...

buoyant pine
#

Well, what do you want to do?

viscid parcel
#

I have my TV setup like so:

  • TV has Xbox on HDMI1, 5x1 HDMI Switch on HDMI2
  • HDMI Switch has Nintedo Switch, PS4, etc on each input
  • I have a Logitech Harmony Hub
#

I'd like to expose Xbox, Switch, PS4, etc as Sources for a Media Player on Homekit

#

So the Harmony would set the TV input and the Switch input by Activity

#

And I'd get the TV as a Media Player with On/Off, Volume and Sources for those in Homekit

#

It's a little unclear as to how the sources part of the UMP works though...

#

Oh, can it take an input_select?

buoyant pine
#

Unless there's a way to change sources with that HDMI splitter in home assistant I don't think that'd work

viscid parcel
#

That's what the Harmony Hub is for

buoyant pine
#

Ah

viscid parcel
#

Granted it does also have RS232

buoyant pine
viscid parcel
#

Assuming that's correct

#

Gonna need quite a few helpers I suspect lol

alpine surge
#

Hi

#

I want time offset in given template

#

{{ states.sensor.time.state == states("sensor.dhuhr") }}

arctic sorrel
#

What offset?

alpine surge
#

Like, i want to trigger this template about after 1 hour, or before 1 hour

#

Like below example

{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.islamic_prayer_time_dhuhr"), "%Y-%m-%dT%H:%M:%S")) + 3000}}

#

This example runs after 50 minutes or 3000 seconds

arctic sorrel
#

What is the state of sensor.dhuhr?

alpine surge
#

This is islamic prayer api sensor

arctic sorrel
#

And ... what is the state so we don't have to play guesswork ๐Ÿ˜‰

alpine surge
#

I used this in automation. Which works and trigger on time, when this templates ==

{{ states.sensor.time.state == states("sensor.dhuhr") }}

#

"Sensor.dhuhr" is time afternoon time. It changes daily and gets latest time from aladhan website, using api

arctic sorrel
#

But... without knowing the actual state value you're seeing, it's incredibly hard to help you

#

Is it HH:MM or HH:MM:SS or ... what?

silent barnBOT
alpine surge
#

Please find

#

I have pasted my config

arctic sorrel
#

~codewall @alpine surge

silent barnBOT
#

@alpine surge Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.

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

alpine surge
#

Ok

arctic sorrel
#

You posted all that

#

You still haven't provided the actual state

alpine surge
#

Actually, i pasted to show you all.

'{{ states.sensor.prayer_times.attributes.data.timings["Dhuhr"] | timestamp_custom("%H:%M") }}'

#

This is H:M

arctic sorrel
#

And you want an offset of 50 minutes?

alpine surge
#

I want given time offset, like 50 minutes after, or sometimes 1 hour before

#

Whatever we enter in - or + offset

arctic sorrel
#

Enter where?

alpine surge
#

Like in this given example

Like below example

{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.islamic_prayer_time_dhuhr"), "%Y-%m-%dT%H:%M:%S")) + 3000}}

#
  • 3000 second mean 50 minutes after this template will execute
#

Same like, i want in my template

{{ states.sensor.time.state == states("sensor.dhuhr") }}

arctic sorrel
#

But it sounded like you want a variable offset, not a fixed offset

alpine surge
#

Yes

arctic sorrel
#

So... input_number?

alpine surge
#

{{ states.sensor.time.state == states("sensor.dhuhr") +3000 }}

#

Like this

#

But is not working

arctic sorrel
#

Well, no

#

Because those are strings

buoyant pine
#

You'd need to compare timestamps at that point

arctic sorrel
#

Which is quite do-able, but not trivial

buoyant pine
#

Yeah time offsets in templates are kinda tricky

arctic sorrel
#

Well, easier with dates, since you can convert to timestamps

#

Here you'd have to add the current date, convert to a timestamp, do the maths

buoyant pine
#

Yup...fun stuff

alpine surge
#

Like below example

{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.islamic_prayer_time_dhuhr"), "%Y-%m-%dT%H:%M:%S")) + 3000}}

#

In this template

#

Whatever i enter + or -

arctic sorrel
#

Yup, that's easier since it has a date

alpine surge
#

Hhmmm

rugged laurel
#

@arctic sorrel like this

#

{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.islamic_prayer_time_dhuhr"), "%Y-%m-%dT%H:%M:%S")) + 3000}}

arctic sorrel
#

Except, not ๐Ÿ˜›

rugged laurel
#

yes

arctic sorrel
#
{{ as_timestamp(strptime(states("sensor.time"), "%H:%M")) }}
``` does give a value, I wonder if 

{{ as_timestamp(strptime(states("sensor.dhuhr"), "%H:%M")) }}

#

Try it, see if you get some values that are vaguely similar

alpine surge
#

Ok thanks.

arctic sorrel
#

The timestamp is going to be negative, because of the lack of a date

#
{{ as_timestamp(strptime(states("sensor.dhuhr"), "%H:%M")) - as_timestamp(strptime(states("sensor.time"), "%H:%M")) }}
``` should, if `dhuhr` is in the future, give a positive value that's relatively small, or negative value that's relatively small if it's in the past
alpine surge
#

Ok. I will try all

#

Thanks

arctic sorrel
sonic nimbus
#

Hi, how can I ask for or condition like this: {{is_state(('binary_sensor.motion_sensor_bedroom_right', 'off') or ('binary_sensor.motion_sensor_bedroom_left'))}}

#

it says Unknown error rendering template

arctic sorrel
#
is_state((
``` ๐Ÿค”
#
{{is_state('binary_sensor.motion_sensor_bedroom_right', 'off') or is_state('binary_sensor.motion_sensor_bedroom_left','off')}}
sonic nimbus
#

oh, I see..tnx!

#

just a question, how then would I add and operator?

buoyant pine
#

and

arctic sorrel
#

Replace or with and mindblown

sonic nimbus
#

for example: (A and B) or (C and D)

arctic sorrel
#

Just like that

#

It's worth reading the templating docs ๐Ÿ˜‰

#

It links to the Jinja2 docs, which explain a lot too

sonic nimbus
#

yeah I know for all operators, Im on the templating docs, but some more complicated examples are arising ๐Ÿ™‚

arctic sorrel
#

It's basic logic

sonic nimbus
#

I already moved some automations to templates

#

much less code ๐Ÿ™‚

arctic sorrel
#

Don't try to make up operators, and remember that templates may be slower than "standard" triggers or conditions

#

Templates can be overly complex ๐Ÿ˜‰

buoyant pine
#

Lol

dreamy sinew
#

eh, i've seen (and tried) worse

#

no macros or namespaces

sonic nimbus
#

this is similar to my picker for radio stations with these elif's ๐Ÿ˜„

arctic sorrel
#

I view templates like regex - possibly the only solution, but should rarely be the default solution ๐Ÿ˜›

buoyant pine
#

Yeah this is for a very specific automation involving several variables

#

Used to be 10 or so separate automations which is a PITA to manage

sonic nimbus
#

I would be always for more complex code and much less lines of code..

#

it's kind a easier..

#
or 
is_state('binary_sensor.motion_sensor_bedroom_right', 'unavailable'))
and
(is_state('binary_sensor.motion_sensor_bedroom_left', 'off') 
or
is_state('binary_sensor.motion_sensor_bedroom_left', 'unavailable')) 
}}```
#

here is my and/or query ๐Ÿ™‚

dreamy sinew
#
{% set off_states = ['off', 'unavailable'] %}
{{ states('binary_sensor.motion_sensor_bedroom_right') in off_states and states('binary_sensor.motion_sensor_bedroom_left') in off_states }}
sonic nimbus
#

thanks @dreamy sinew much more elegant ๐Ÿ™‚

thorny snow
#

Can I take a mqqt value that is "1" and make it into OK/NOT_OK with the data/value_template?

#

under the mqtt platfom

arctic sorrel
#
{{ "OK" if whatever == 1 else "NOT_OK" }}
#

There are, of course, many MQTT integrations

thorny snow
#

what do you mean? mqqt lights, etc?

arctic sorrel
#

Yup

#

Switches, lights, sensors, etc etc etc

thorny snow
#

Yes, I am trying to use mqtt for everything now

#

rtl_433 in this case

#

I am trying to find the differnce between a dat atemplate and a value template...

arctic sorrel
#

Which

#

Integration

#

are

#

you

#

talking about

#

There's a load of them, and being vague isn't helping us help you

#

Context in each may be different

thorny snow
#

Oh, I thouhgt I said platform: mqtt

arctic sorrel
#

๐Ÿค”

#

๐Ÿคฆ

thorny snow
#

" - platform: mqtt"

arctic sorrel
#

Switch?

#

Light?

#

Sensor?

thorny snow
#

OHhh sensor, sorry

arctic sorrel
#

The fsck are you talking about

#

Finally

#

That only has value_template - no data_template

#

So now I'm even more confused

thorny snow
#

howso?

arctic sorrel
#

I am trying to find the differnce between a dat atemplate and a value template...

thorny snow
#

rtl_433 spits out ambient waether data to mqtt

arctic sorrel
#

There is no data_template in that integration

#

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

thorny snow
#

Ok, that answers my question

#

when would you use data template?

arctic sorrel
#

Well, I'd start with when supported by the integration in question

#

That's like asking when would you use a hammer

thorny snow
#

when you want to bang things

arctic sorrel
#

Please stand up a little straighter then ๐Ÿ˜›

thorny snow
#

I don't know the difference between a value template and a data template

arctic sorrel
#

One is for values

#

One is for data

thorny snow
#

is it either/or per integration?

#

it's all data

arctic sorrel
#

Find an integration with both, and then we can continue the conversation

#

I'm all for existential discussions, but this one ....

thorny snow
#

Thanks

#

Is this correct? value_template: "{{ 'OK' if value == 1 else 'NOT_OK' }}"

buoyant pine
#

make the inside quotes single quotes

thorny snow
#

and "value" is like a self.value reference, correct?

buoyant pine
#

assuming value is defined

thorny snow
#

Here's what I am not understanding...

#

I want to transform the data as it comes in to OK from a 1 or 0... if I put value_template: "{{ 'OK' if sensor.master_battery == 1 else 'NOT_OK' }} .. isn't that self-referential??

#

The data coming in is a "1".. I can't change that data to 'OK', or it's not 1 anymore...

#

how do I say "whatever value I get from mqqt"

buoyant pine
#

oh this is regarding mqtt. i have no clue then. i was just validating syntax lol

#

you might need to use a template sensor then to display whatever value you want. not ideal as you said but it might be the only choice

#

wait, 1 or 0? is it a binary sensor?

#

might as well give it a shot with the value template using value like you did

thorny snow
#

no, not a binary sensor, but maybe i can treat it that way?

#

oh look.. safe mode ๐Ÿ˜„ (remove those double tikcs LOL)

#

Well, they successfully say "NOT_OK" now on the dash... but it's wrong of course

buoyant pine
#

what do you mean?

thorny snow
#

I mean the data coming in is indeed a "1", but HA is saying NOT_OK

#

but value =/= 1 if value isn't a variable for this input

dreamy sinew
#

1 != "1"

thorny snow
#

correct... it's just coming in as 1 I presume?

#

value_template: "{{ 'OK' if value == '1' else 'NOT_OK' }}"

buoyant pine
#

ditch the quotes around the 1

thorny snow
#

maybe that? let's see

#

I haven't tried it yet

buoyant pine
#

'1' is a string, 1 is a number

thorny snow
#

oh.. dang

dreamy sinew
#

he tried the number first

buoyant pine
#

ah. then yeah try whatever you didn't do

thorny snow
#

i haven't tried what works... let's try that ๐Ÿ˜„

buoyant pine
#

just a heads-up all states in home assistant are stored as strings

#

not sure how things work with mqtt specifically though

dreamy sinew
#

which is stupid obnoxious ๐Ÿ˜„

thorny snow
#

ohhh.. important to know

dreamy sinew
#

but then, everything that comes out of a template is a string so... ยฏ_(ใƒ„)_/ยฏ

buoyant pine
#

yup

thorny snow
#

that makes sense... python underneath, right?

dreamy sinew
#

python doesn't care

thorny snow
#

isn't py like perl, where it's string unless you do math?

#

maybe not

buoyant pine
#

what's fun is that state attributes aren't always necessarily strings

thorny snow
#

oh jeez go away

dreamy sinew
#

nope, python has standard types

thorny snow
#

hahah...

#

Maybe that's why I liked perl so much back in the day... befoe I knew data types

dreamy sinew
#

python interprets down to C iirc

thorny snow
#

AHHA!!! Now it's working correctly!

buoyant pine
thorny snow
#

Thanks fellahs! @arctic sorrel gave up on me, but he helped a lot

buoyant pine
#

example of state attribute that is not a string

arctic sorrel
#

I gave up on your being vague and confused ๐Ÿ˜›

thorny snow
#

VERY confused

dreamy sinew
#

heh state attrs can be objects to make it even worse

thorny snow
#

woooof. let's build that bridge when we get there

buoyant pine
#

/r/boneappletea

thorny snow
#

that's an proper idiom

#

burn that bridge when we get tehre is a brooks and dunn song ๐Ÿ˜›

buoyant pine
#

i've only ever heard "let's cross that bridge when we get there" lol

thorny snow
#

now you got me thinking

dreamy sinew
#

Burn that bridge
I'm a fan of that one

thorny snow
#

oh no, I am wrong it seems