#templates-archived

1 messages · Page 130 of 1

mighty ledge
#

yah but the datetime timestamp is local

#

I warned the devs about this

#

I thought it was stupid that it wasn't utc

ivory delta
#

Everything should be UTC in data and presented differently in the UI.

mighty ledge
#

yep

#

if it's a time datetime it the timestamp should be today at that time in utc

#

if it's a date datetime it should be the timestamp at midnight your tz in utc

#

if it's both, well, that's easy

#

just the damn datetime in utc

marble surge
#

suppose that I need to call a service inside my automation

#
  - service: mqtt.publish
      data_template:
        topic: "tele/solarstation/REMAINING_SECONDS"
        qos: 0
        retain: false
        payload: '{"remaining_seconds":"{{ states.input_number.waterpump_activation_seconds.state | int }}"}'       
#

something like this

#

how can I insert template in the payload attribute?

#

I mean something with an if then else

#

like this

{% if (timestamp_now < state_attr('input_datetime.solarstation_activation_hour', 'timestamp')  ) %}
    2
{% else %}
    3
{% endif %}
#

I would like that the result of the if then else is the value of one of the json attribute of the payload

ivory delta
#

Have you tried it?

fossil venture
marble surge
#

last question

#

I have this

#
{% set timestamp_now = as_timestamp(utcnow().replace(year = 1970, month = 1, day = 1)) %}
#

if I do this

#
   {{ state_attr('input_datetime.solarstation_activation_hour', 'timestamp') - timestamp_now  }}
#

it returns 8269.825654

#

what the heck is 8269?

#

now is 18:12

#

and input datetime is set at 18:30

ivory delta
#

It's the difference between the two

marble surge
#

oh my god

ivory delta
#

You're doing maths. Subtraction, specifically.

fossil venture
#

In seconds.

marble surge
#

I think that Cobol is better than this

ivory delta
#

🤯

#

The language you use has nothing to do with it. It's simple maths.

#

You're welcome to reproduce HA in Cobol if you like.

marble surge
#

in this moment I can't find how to translate that numbers in the difference between the two "time"

#

expressed in seconds or minutes

ivory delta
#

You do... more maths.

#

And believe it or not, modulus is your friend here too.

marble surge
#

how 58560 can be the 18:16? 😄

ivory delta
#

Does Cobol not have the mod function?

marble surge
#

58560 / 60 = 976

ivory delta
#

58560 seconds since midnight. Where there are 86400 seconds in a day.

marble surge
#

but isn't 58560 / 60 should return minutes?

ivory delta
#

No... dividing an integer by another integer won't give minutes. Why would it?

marble surge
#

still don't get how to get the difference between this two time expressed in minutes or seconds mmm

#

if you have 120 seconds and you divide it by 60

#

you get 2 minutes

ivory delta
#

How does it know you're working with seconds and minutes? There are no units.

#

120 is just a number. 60 is just a number. It's not a mind reader.

#

What do you want?

marble surge
#

I want to get the difference in seconds or minutes between this

#

as_timestamp(utcnow().replace(year = 1970, month = 1, day = 1))

#

and this

ivory delta
#

So do the math...

marble surge
#

state_attr('input_datetime.solarstation_activation_hour', 'timestamp')

ivory delta
#

What format do you want the output in?

marble surge
#

integer is ok

ivory delta
#

You have an integer.

marble surge
#

we are talking about seconds or minutes int is ok

ivory delta
#

120 / 60 = 2. 2 is your integer.

marble surge
#

but it doesn't work as I expect

#

reread this numbers

#

timestamp_now = 58994.105547 (and now it 18:23)

#

state_attr('input_datetime.solarstation_activation_hour', 'timestamp') - timestamp_now
returns
7605.894453000001

#

if I divide 7605 by 60

#

I get 126

#

and it's not true

#

since the solarstation_activation_hour is set to

#

18:30

ivory delta
#

Write full sentences on one line, thank you. Don't flood the chat.

silent barnBOT
#

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.

For sharing code or logs use https://paste.ubuntu.com/.

marble surge
#

ook

ivory delta
#

Which timestamp do you think is wrong?

marble surge
#

at this point I don't know

ivory delta
#

Ok. Have fun.

marble surge
#

as_timestamp(utcnow().replace(year = 1970, month = 1, day = 1))

#

this should return the now timestamp

#

so it should be ok

#

state_attr('input_datetime.solarstation_activation_hour', 'timestamp') this is too simple to be wrong

ivory delta
#

That's the timestamp in UTC... you live in UTC+2...

marble surge
#

+1 not +2

ivory delta
#

And it's summer, no?

marble surge
#

yes

ivory delta
#

So... UTC+2?

marble surge
#

ah ok no GMT you're using UTC

#

damn

#

but is there a simple way to get the difference of a input_datetime and now?

ivory delta
#

Sure. Subtraction.

marble surge
#

what kind?

ivory delta
#

The kind where you subtract one number from another.

marble surge
#

lol

ivory delta
#

What does as_timestamp(utcnow().replace(year = 1970, month = 1, day = 1)) give? And what does as_timestamp(now().replace(year = 1970, month = 1, day = 1)) give?

marble surge
#

59606.619628 and 63206.619795

ivory delta
#

And {{ state_attr('input_datetime.solarstation_activation_hour', 'timestamp') }}?

marble surge
#

66600

ivory delta
#

Yeah... so you're going to have loads of fun with that, especially since summertime is going to mess with it.

marble surge
#

at this point I don't think that "is possible" with this kind of templating

#

at least

#

not in a "human readable" format

#

is there a better approach to the problem?

ornate ruin
#

your input_datetime does not have dates right? just time?

marble surge
#

if it helps

#

I can add the date as today

#

that input_datetime is referred at today

ornate ruin
#

here's what I understand (and I just briefly scrolled, there is too much text to read through line by line) - you want to be able to set a time of day using an input_datetime, and then every day do some automation based on that

#

is that correct?

#

ok no, you have two input_number's

marble surge
#

more or less yes, but I'll try to give you the context. I have an ESP that wake up every ten minutes and checks when it need to enable the water pump. this information is sent from HA to the ESP and it's the input_datetime.solarstation_activation_hour

ornate ruin
#

you want to use two input_number's, each which represent an hour and minute, to create a datetime for today at that hour and minute

marble surge
#

my ESP wake up every 60 minutes but if there is only 15 minutes between now and input_datetime.solarstation_activation_hour it should sleep only 15 minutes

ornate ruin
#

and then from there you want to compare that datetime to some other datetime and do some logic based on that

marble surge
#

I switched the two input_number to input_datetime as per suggestion

#

but I can use whatever I want to solve the problem in the easyer way 🙂

#

how can I calculate the 15 minutes?

#

that is what I need to calculate

ornate ruin
#

well, my suggestion is to create a second input_datetime (or first if you stick with the two input_numbers), and then create an automation that runs every day to set the datetime to today with that time

ivory delta
#

If this is all about controlling the behaviour of the ESP device, why not do all of this on the ESP?

ornate ruin
#

then you have two input_datetimes to compare and the formats are the exact same

marble surge
#

and removing it from his boxes is way too compllicated

marble surge
#

do you think that it will help?

#

doing a simple subtraction from one input_datetime and the second one should return the difference of the two time in seconds right?

ivory delta
ornate ruin
#

the state of any entity is a string

#

you'd need to use one of the filters to convert them both to a unix timestamp

ornate ruin
#

then yes, doing a subtraction would give you the difference between the two in seconds

marble surge
#

mmm ok, I need to prepare the dinner for my wife, I will try it later xD thanks for the suggestions, I really appreciate it

#

PS: after all of this, I'll give you a feedback if it will work xD

ornate ruin
#

no need, I get enough tags, but if it works I am happy for you

marble surge
#

ok

#

thanks bye bye

fathom osprey
#

hey! is it possible to get the first reading of the day from a sensor?

fossil venture
#

Maybe with a trigger based template sensor, two automations and an input_boolean. Turn off the input boolean at midnight with an automation (time trigger). Have another automation that triggers on any state change of the sensor (state trigger with no to or from) and a condition that the input boolean has to be off. Action: turn on the input boolean. Trigger based template sensor then triggers on the input boolean turning on and grabs the state of the sensor. Or if you don't need it stored in a sensor, store the sensor state in an input number in the second automation and forget the trigger based template sensor. Or if your sensor polls on a fixed interval you can forget all that and just use a trigger based template sensor that grabs the state of the sensor at time 00:<polling_interval + a little bit>.

bright quarry
#

i have a custom time template, but it keeps giving me errors [ https://paste.ubuntu.com/p/rCrTNZnm6d/ ] in my log. the template is;

    sensors:
      time_since_most_recent:
        value_template: >-
          {{ states.input_text.lastusedss.last_updated.strftime('%Y-%m-%dT%H:%M:%S') }}Z
        device_class: timestamp```
is there any way to hush the log or fix the template so it doesn't get mad?
mighty ledge
slim holly
#

Hi, i need help with a template which parse JSON, some of the keys in the JSON are numbers. I'm not able to access such keys from template/Jinja. Any idea what my fault is?

{%- set j ='{"count":12,"indices":["component id","component code","component symbol","component unit","component name"],"1":["1","PM10","PM\u2081\u2080","\u00b5g\/m\u00b3","Particulate matter"],"2":["2","CO","CO","mg\/m\u00b3","Carbon monoxide"],"3":["3","O3","O\u2083","\u00b5g\/m\u00b3","Ozone"],"4":["4","SO2","SO\u2082","\u00b5g\/m\u00b3","Sulphur dioxide"],"5":["5","NO2","NO\u2082","\u00b5g\/m\u00b3","Nitrogen dioxide"],"6":["6","PM10PB","Pb","\u00b5g\/m\u00b3","Lead in particulate matter"],"7":["7","PM10BAP","BaP","ng\/m\u00b3","Benzo(a)pyrene in particulate matter"],"8":["8","CHB","C\u2086H\u2086","\u00b5g\/m\u00b3","Benzene"],"9":["9","PM2","PM\u2082,\u2085","\u00b5g\/m\u00b3","Particulate matter"],"10":["10","PM10AS","As","ng\/m\u00b3","Arsenic in particulate matter"],"11":["11","PM10CD","Cd","ng\/m\u00b3","Cadmium in particulate matter"],"12":["12","PM10NI","Ni","ng\/m\u00b3","Nickel in particulate matter"]}' %} {%- set j1= j | from_json %} {{ j1.count }} {# is working --> result 12 #} {{ j1.indices }} {# is working --> ['component id', 'component code', 'component symbol', 'component unit', 'component name'] #} {{ j1.1}} {# is not working nothing will be displayed, should be ['1', 'PM10', 'PM₁₀', 'µg/m³', 'Particulate matter'] #}

ivory delta
#

{{ j1['1']}}

#

Keys should not start with numbers. If they do, you have to access them this way instead.

slim holly
#

Thank you so much, i searched the whole day and found no solution. This is not my JSON, so i have to use is with numbers in keys, but now i'm happy. 🍻

ivory delta
#

Yeah, you're not always in control of the data. Just remember there are two ways to access a key 🙂

#

I don't remember exactly why your first way doesn't work with numbers, only that it doesn't.

dreamy sinew
#

Because dot walking is a bit of a hack unfortunately. Best to use the direct python at that point via key lookup or .get()

ivory delta
#

I remember why. If you use a number, it just gets the character at that index:

{{ test.1 }}```
This returns 'b'.
#

Stupid Python 🐍

mighty ledge
#

That’s not python, that’s jinja

inner mesa
#

Indeed:

#
>>> test="abc"
>>> test.1
  File "<stdin>", line 1
    test.1
        ^
SyntaxError: invalid syntax
>>> test[1]
'b'
mighty ledge
#

I think jinja has that so you can properly use selectattr with strings 'x.1' etc

inner mesa
#

it's fewer characters, but it just gets me in trouble with keys that start with a number, or have spaces. I try to avoid it

#

but yeah, that is a nice use case for it where the bracketed notation wouldn't work

jagged totem
#

Trying to use a rest sensor and this value is too large for the state. Is there a way to template it in the rest sensor? https://paste.ubuntu.com/p/xrn2R4yjFx/
if there was a way I could map the description to a/b/c it would save lots of space. The services will change order and types so cant rely on them being like this always

inner mesa
#

you can use templates to define the value of teh sensor and any attributes you're interested in

jagged totem
#

oh I found it, value_template: "OK" then sets to attributes which skips the max length

inner mesa
#

right

jagged totem
#

I want all the data to avoid multiple calls, so I'll try that

fleet viper
#

I'm trying to get this label to show the relative time left on a timestamp or input_datetime, any help would be great!

#

label: | [[[ return 'Turns off in ' + states['sensor.attic_fan_turn_off_timestamp'].state ]]]

mighty ledge
fleet viper
#

Okay ugh, at least its only minutes/hours in the future

#

i saw it displaying so nicely on the default dashboard

mighty ledge
# fleet viper Okay ugh, at least its only minutes/hours in the future
        var statestr = states['sensor.attic_fan_turn_off_timestamp'].state;
        var date = new Date(statestr);
        let now = new Date();
        var tdelta = Math.floor((now - date)/1000);
        function plural(descriptor, divisor){
          var ret = Math.floor(tdelta/divisor);
          return (ret == 1) ? [ret, descriptor] : [ret, `${descriptor}s`];
        }
        var values;
        if (tdelta < 60)
          values = plural('second', 1);
        else if (tdelta < 60 * 60)
          values = plural('minute', 60);
        else if (tdelta < 60 * 60 * 24)
          values = plural('hour', 60 * 60);
        else if (tdelta < 7 * 60 * 60 * 24)
          values = plural('day', 60 * 60 * 24);
        else
          values = plural('week', 7 * 60 * 60 * 24);
        return `Turns off in ${values[0]} ${values[1]}`;
fleet viper
#

cool, thats a helpful start

mighty ledge
fleet viper
#

Hoe often does lovelace refresh that time?

#

on page load?

mighty ledge
#

page load only with a template like that

#

you can add a trigger entity to the button card, like sensor.time to have it update once a minute

fleet viper
#

so just adding entity: sensor.time into that card?

mighty ledge
#

No, there's a triggers_template field iirc

fleet viper
#

triggers_update:

fleet viper
#

awesome ty!

mighty ledge
#

did the template work?

fleet viper
#

finally getting this fan project close to done!

#

yep

#

just switched now and date in the math 🙂

mighty ledge
#

I ripped it from my setup

fleet viper
#

cant add an image here but yep its working great

#

the buttons below control the timer for the fan via its remote thru scripts operating a switchbot

mighty ledge
#

Nice

#

those are dice tho

fleet viper
#

ya that was the only 12 mdi 😄

fleet viper
#

but likely will jsut switch for text

mighty ledge
fleet viper
#

thanks for your help @mighty ledge !

twin cargo
#

hey, does anyone know if it's possible to pad left a string to always being 3 characters in a template?

thorny pike
#
at least 9 characters long, left padded with #: "{{ '{:#>9s}'.format('foo') }}"
twin cargo
#

very cool, thanks!

crisp pine
#

Is it possible to create template sensors from the web UI or yaml only?

inner mesa
#

Yaml only

rustic coral
#

if home assistant gives a template warning and it appears to be when using tap action: toggle on a Z2M entity group, would the issue be for Z2M or hass ?

#

if I change the action to mqtt with payload, it doesn't give a warning

ivory delta
#

.share the error and the config.

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

rustic coral
#

when I change the tap_action to a call-service for mqtt, there's no warning.

#

it also happens if the zigbee entity isn't a group

#

I don't know where to file the issue, hass or z2m

ivory delta
#

That error doesn't seem to be related to the toggle you're doing from the button.

echo ermine
#

Hi gang! I'm trying to create a template fan object. Because of some Insteon weirdness with a wall-mounted control, I have to do multiple calls to keep them synchronized, depending on fan percentage. I've created a template fan, and the state and percentage should reflect the existing Insteon fan. When I check states in dev tools, the template fan does not match the Insteon fan. This looks pretty straightforward, so I'm confused. Any help would be greatly appreciated. Thanks!

#

It looks like
"{{ states.fan.fanlinc_xx_xx_xx_fan }}"
returns the correct state

#

But
"{{ states('fan.fanlinc_xx_xx_xx_fan.state') }}"
as is used in the example does not

ivory delta
#

"{{ states('fan.fanlinc_xx_xx_xx_fan.state') }}"
That's invalid...

thorny pike
#
states('fan.fanlinc_xx_xx_xx_fan')
ivory delta
#

The states function expects an entity ID only.

#

{{ states('fan.fanlinc_xx_xx_xx_fan.percentage') }}
This is also invalid. You use state_attr to get an attribute's value.

echo ermine
thorny pike
#

yeah the example is wrong

#

wait

#

no it's not, 'input_number.percentage' would be a helper entity

#

different from your use case

echo ermine
#

I see, thanks for that. I'm still a template newb so I appreciate the help

#

That worked! Thanks for clarifying. Yes, I misread 'input_number.percentage' as an attribute rather than an entity. I appreciate the link to the right section of the template page!

echo ermine
#

I do have another question folks if you don't mind. I'd like to optionally call certain services based on the value of a passed-in number. I don't think this is correct, but if you could point me to the correct way to do it, I'd greatly appreciate it!
https://paste.ubuntu.com/p/XqBvyb4Cxt/

#

Namely what I'm trying to do with set_percentage

ivory delta
#

You can't do that - the keys (left hand sides) have to be set explicitly. It's only the values (right hand sides) that can sometimes be set with templates.

#

You'll want to head over to #automations-archived for the next part but basically you want to learn how to use the choose syntax.

echo ermine
#

OK Thanks! I'll keep digging. So in the template could I call a script then that would use automations to choose the correct actions?

#

Or are you saying I should just have automations triggered by the state change of the fan?

ivory delta
#

Neither. But take this to the correct channel.

proud crater
#

Hi guys im new in HA, i want make script for fan speed percentage and preset mode do you help me with code thx

ivory delta
#

You're not new...

proud crater
#

sorry amateur

inner mesa
#

There's not nearly enough info there for anyone to even start. But this isn't an "I'd like a burger and fries" place

ivory delta
# proud crater sorry amateur

That's more accurate. So now you can start by sharing what you've done so far, instead of asking someone else to do it all for you.

fluid cedar
#

What's the correct formatting for if/else in templates? This doesn't work.

    sequence:
    - service: light.turn_off
      {% if state_attr('light.test_bulb', 'brightness')|int > 63 %}
        data:
          transition: 1
      {% endif %}
inner mesa
#

You can’t do that. If you want to optionally add a transition, you need separate service calls and a choose:

ivory delta
#

There was an almost identical question asked earlier today, which may even be on screen still depending on your resolution: #templates-archived message

fluid cedar
#

So there is. Thanks guys. I'll add a choose instead.

tight lantern
#

Hi there!
Does anybody know why my binary sensor won't appear? (I'm looking in the dev tools, if that helps)

template:
  - sensor:
      - 8_hour_rain_total:
        friendly_name: "8 Hour Rain Total"
...

    binary_sensor:
      - name: "Rain Sensor Homekit"
        state: "{{ states('binary_sensor.rain_sensor') }}"
        unique_id: rain_sensor_homekit
inner mesa
#

friendly_name: "8 Hour Rain Total"

#

I see no evidence that that's valid

tight lantern
#

i've just switched from "the old format" to "new format" for my templates, probably that.

inner mesa
#

neither is this:

#

- 8_hour_rain_total:

#

yes, it looks like you're somewhere between the two

tight lantern
#

would not be surprised.
i'll have to have a go again

inner mesa
#

the syntax is different enough that I find it challenging to keep track of what's valid where. I've just left mine in the old format for now

tight lantern
#
template:
  - sensor:
      - name: "8 Hour Rain Total"
        value_template: >

better?

inner mesa
#

no, I don't think so

#

value_template: should be state:

tight lantern
tight lantern
inner mesa
#

the very first example is similar to yours

tight lantern
#

I probably copy pasted it!

  - sensor:
      - name: "8 Hour Rain Total"
        state: >

looks like this now. i think it's right?

inner mesa
#

looks better

silent barnBOT
inner mesa
#

there's an example in what you posted

tight lantern
#

yeah. i wasn't sure how to interpret that.
but now i've fixed the rest of the templates, i bet there's a good chance it could work?

inner mesa
#

the first bit is for a state-based sensor/binary_sensor and the second is for trigger-based sensors/binary_sensors

tight lantern
#
...
      - name: "Garage Spare Watts"
        state: "{{ state_attr('switch.garage_spare', 'current_power_w') }}"
        unit_of_measurement: "W"
        
    binary_sensor:
      - name: "Rain Sensor Homekit"
        state: "{{ states('binary_sensor.rain_sensor') }}"

would this be correct, then? I based it off off that.

inner mesa
#

assuming there's a - sensor: above that you've chopped off

tight lantern
#

there is.

#

restarting now. fingers crossed

inner mesa
#

you can just hit "Reload Template Entities" from configuration -> Server Controls

tight lantern
#

if I do that, it doesn't show any errors I don't think?
i restart core via supervisor because it does

inner mesa
#

it should

#

it's doing the same thing

tight lantern
#

huh, i'll use it next time

inner mesa
#

you can test

tight lantern
#

hey! it works!

#

thank you! i'll have a test see if the errors appear.

inner mesa
#

2021-07-18 11:35:02 ERROR (MainThread) [homeassistant.config] Invalid config for [sensor.template]: [value_foo_template] is an invalid option for [sensor.template]. Check: sensor.template->sensors->garage_door_state->value_foo_template. (See /config/sensors.yaml, line 62). Please check the docs at https://www.home-assistant.io/integrations/template

#

just reloaded via Server Controls

tight lantern
#

huh. must've been solar flares or something, because i swear they didn't appear for me.

#

¯_(ツ)_/¯

#

thanks again :-)

summer summit
#

Hello. I created an entity from the Utility Meter that takes values from the water meter. Everything works fine. It only shows values of 0.0001 L which is actually 0.1 L of water. I'm trying to modify the template to show it correctly in day mode, but it still doesn't work. I have this template but even this new one still shows values of 0.0001 L. Where is the error please?

Daily water template

  • platform: template
    sensors:
    daily_water_l:
    friendly_name: Water day
    unit_of_measurement: l
    value_template: '{{value | multiply (1000) float}} '
silent barnBOT
#

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

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

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

inner mesa
#

but your template is missing a |, and your cast is in the wrong place

#

where is value coming from?

summer summit
#

#Denní voda šablona

  • platform: template
    sensors:
    daily_water_l:
    friendly_name: Voda den
    unit_of_measurement: l
    value_template: '{{ value | multiply(1000) | float }}'
inner mesa
summer summit
#

it was copied badly, this is how I got it

inner mesa
#

still

#

and where does value come from?

summer summit
#
#Denní voda šablona
  - platform: template
    sensors:
      daily_water_l:
        friendly_name: Voda den
        unit_of_measurement: l
        value_template: '{{ value | multiply(1000) | float }}'
inner mesa
#

ok, still wondering where value comes from. More than likely you need value | float | multiply(1000)

summer summit
inner mesa
#

ok, so it's an MQTT sensor?

silent barnBOT
inner mesa
#

nothing is actually assigning anything to value, though

summer summit
inner mesa
#

something is not connecting here

#

where do you think value is coming from?

#

you just have a template sensor there

summer summit
#

it is inserted in the sensor section

inner mesa
#

it has no obvious relationship to the utility meter

summer summit
#

OK, where must it be located? Directly under Utility Meter?

inner mesa
#

you have to make the value_template rely on another entity, like your utility_meter entities

#

otherwise, value is just zero

#

which utilty_meter entity are you trying to convert?

#

something like sensor.daily_water_l?

summer summit
#

this ```
daily_water_l:
source: sensor.meric_vody
cycle: daily

inner mesa
#

then you want

silent barnBOT
inner mesa
#
#Denní voda šablona
  - platform: template
    sensors:
      daily_water_l_new:
        friendly_name: Voda den
        unit_of_measurement: l
        value_template: '{{ states("sensor.daily_water_l") | float | multiply(1000) }}'
silent barnBOT
#

Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).

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

inner mesa
#

you can't just replace the existing sensor, you need to create a new sensor with a modified value

summer summit
#

ok i will try it, thank you

inner mesa
#

you're just pasting snippets with minimal context, so it's hard to piece them together and fill in the blanks

#

but the point is that value won't mean anything by itself in a template sensor - it has no idea what it's supposed to refer to

summer summit
#

the numbers are so far 0.0 although the main water meter has already shown an increase, but I do not know if the utility meter has a delay and some cycle need 10 minutes.

#

its OK, and function 🙂 Thnak you wery much 🙂

young jacinth
#

how do i convert 01:30:00 into 90 mins?

mighty ledge
#
{% set h, m, s = '01:30:00'.split(':') | map('int') %}
{% set minutes = h * 60 + m + s / 60 %}
{{ minutes }}
young jacinth
#

thanks alot!!!

young jacinth
#

how do i subtract 3 mins from 01:30:00 so i would get 01:27:00 ?

deft timber
#

try timedelta

weary pumice
#

i need some help regarding a template sensor... can someone tell me why this sensor never turns to "off"?

#

- trigger: - platform: state entity_id: sensor.sonnen_batterie_verbrauch binary_sensor: - name: "Sauna angeschaltet" state: > {{ states('sensor.sonnen_batterie_verbrauch') | float > 800 }} delay_off: "00:00:30"

#

I swear to god the input sensor has been below 800w for at least 5 minutes...

#

This should turn off if my sensor value has been below 800 for 30 seconds right?

young jacinth
# deft timber try `timedelta`

i tried {{ 01:30:00 - timedelta(minutes = 3) }}
but it throws an error "TemplateSyntaxError: expected token 'end of print statement', got 'integer'"

ivory delta
#

Firstly, you need to quote strings. Secondly, you can't do a timedelta on a string.

young jacinth
#

i got it

                    {% set x = state_attr('timer.sleeptimer','duration') %}
                    {% set h, m, s = x.split(':') | map('int') %}
                    {% set minutes = h * 60 + m %}
                    {{ timedelta(minutes = minutes - 3 ) }}
mighty ledge
#
                    {% set x = state_attr('timer.sleeptimer','duration') %}
                    {% set h, m, s = x.split(':') | map('int') %}
                    {% set minutes = h * 60 + m %}
                    {{ minutes - 3 }}
young jacinth
mighty ledge
young jacinth
#

thanks

#

still having a hard time with time formats

inner mesa
#

everyone does

#

it's part of the human condition

ivory delta
#

Dates and numbers seem so simple... until you have to do any programming with them 😄

inner mesa
#

it's that meatspace<->logic space barrier

pastel moon
#

Is there a way of knowing what invoked a script?

#

ie another script or automation?

mighty ledge
#

it depends on the context and the information is stored (unironically) in the context property on the state object

pastel moon
#

Ok. I have a script for my hallway. It apply's a scene on motion. Normally I want that to be instant. But I also have an automation to adjust lighting throughout the day. That automation runs the same hallway script. When invoked by the automation I'd like to add a transition time to the scene...

mighty ledge
#

just add a condition and supply a variable

#

a choose*

#

if the variable doesn't exist, use service call without the transition

inner mesa
#

assuming that you call the script from the automation with - service: script.xxxx, you can check whether the automation's current attribute is non-zero. If so, the automation is running when the script was called (presumably would always be true)

pastel moon
#

Oh! That sound's neat

inner mesa
#

or a petro mentioned, either call the script with a variable to differentiate, or set an input_boolean before and after the call and check in the script

mighty ledge
#

personally, id go variable. Makes it easy and you can define a transition based on an automation

pastel moon
#

Those are all great suggestions, thanks! But global vars isn't available (yet)?

inner mesa
#

you wouldn't want that anyway

mighty ledge
#
- choose:
  - conditions:
    - condition: template
      value_template: "{{ transition is defined }}"
    sequence:
    - service: scene.xyz
      data:
        transition: "{{ transition }}"
  default:
  - service: scene.xyz
#

it's not global variables

#

it's simply calling your script like this

service: script.xyz
data:
  transition: 1

vs

service: script.xyz
pastel moon
#

Increadible... It sound so easy when you guys get started. I will try this, thank you much!

pastel moon
#

Hm. Formatting issues most probably, but eludes me... https://paste.ubuntu.com/p/kGH8p8tZRj/ Syntax check gives me this, which I don't fully understand "Invalid config for [script]: Unexpected value for condition: 'None'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['sequence'][0]['choose'][0]['conditions'][1]. Got None required key not provided @ data['sequence'][0]['choose'][0]['sequence']. Got None. (See /config/configuration.yaml, line 15)." Do I need a default value for transition?

inner mesa
#

the second choose: needs to be part of a sequence:

#

otherwise, it thinks it's another condition

#
  sequence:
  - choose:
      - conditions:
          - "{{ is_state('binary_sensor.hallway_motion_1_ias_zone', 'on') }}"
        sequence:
          - choose:
              - conditions:
                - condition: template
                  value_template: "{{ transition is defined }}"
pastel moon
#

Got it working! Thanks guys!

mighty ledge
#

if that's just your script you can also hammer the variables to make it less work to change things, and because you don't have a default you don't need the first choose.https://pastebin.ubuntu.com/p/Pf44pP4zrb/

silent barnBOT
silent ember
#

Guess that was too long 😅 Its a sensor that Im trying to create to get the trash pickup dates from my cities website. And I only get an unknown return value, even though it should work, as Ive tried via python directly and the template section in home assistant. If anybody has an idea what Im doing wrong, Id be thankful.

mighty ledge
patent sparrow
#

Can I set mode: queued on a template switch like for an automation? What is the syntax?

inner mesa
#

it doesn't make any sense there

patent sparrow
#

My template switches call broadlink operations and I get Already running warnings a lot that I think are causing error responses in my voice assistants.

#

Was trying to eliminate Already running warnings by changing it to like mode: queued or something.

inner mesa
#

that's only with automations

patent sparrow
#

I think the broadlink operations are internally scripts.

inner mesa
#

"internally"?

#

like the integration?

patent sparrow
#
Logger: homeassistant.helpers.script.1_zap_3
Source: helpers/script.py:1310
First occurred: 6:49:56 PM (2 occurrences)
Last logged: 6:53:17 PM

my_switch: Already running
inner mesa
#

is that not your script?

patent sparrow
#

my_switch is platform: broadlink

inner mesa
#

script.1_zap_3

mighty ledge
#

post the full error

patent sparrow
#
switch:
  - platform: broadlink
    mac: 'redacted_mac'
    switches:
      - name: 'my_switch'
        command_on: 'redacted_hex'
        command_off: 'redacted_hex'
mighty ledge
#

expand the error and post the error

patent sparrow
#

how do i expand it?

mighty ledge
#

ugh, apparently that's been changed too

#

how are you calling my swith from the script. It's odd that the error does not come from broadlink

silent barnBOT
patent sparrow
#

i don't have any scripts, just template switches that wrapper around broadlink switches (because some are multi-step)

#

so when the error says "script" i am just assuming either the template switch or the broadlink switch is internally using script and that's why i'm trying to change it to mode: queued

patent sparrow
mighty ledge
#

make a script and set the mode, use the script in the turn_on section. You'll want parallel

patent sparrow
#

baaaarf okay.

is there an easier way if i'm just trying to eliminate the warnings (i don't actually care about rerunning it, i just think the warnings are surfacing to voice assistant as bad error code responses (she says "something went wrong"))

mighty ledge
#

remove the delay

#

or make a script 🤷‍♂️

#

you won't way parallel, you will want queued if you want to delay it between presses

silent ember
# mighty ledge value is a string, you want value_json

I tried it with the assumption that value was a string as well and it was unknown just the same. Is there any way for HA to show me the value and value_json variables? If I just input value without changes HA complains about it being too long and value_json outputs nothing.

mighty ledge
#

the value is a string, so your template with value[0] is only looking at the first character.

#

value_json turns it into an object. You'll get errors if you're accessing things incorreclty.

#

so, use value_json and post the error. Otherwise if you just output value you can see what it see's but it'll only be the first 254 characters

silent ember
#

Yes, I understand that. I originally had it without the [0]. I tried it with it because beautifulsoup returns a list in python and it already wasn’t working

#

I’ll have to try some more tomorrow. So far I didn’t get any useful errors except the error I get if I try to straight output „value“ which is that the string is too long.

mighty ledge
#

what's the errors though...

silent ember
#

Well. None other than what I just mentioned

#

Other than that I only get either empty Sensor state values or „unknown“

mighty ledge
#

just output the first 200 characters to see what it sees

#

value[:200]

silent ember
#

I’ll try that tomorrow. Thanks.

pastel moon
silent ember
naive vine
#

Hello

#

I want to automate my colour picker - input number

#

anyone have an idea how to get this done ?

mighty ledge
# naive vine anyone have an idea how to get this done ?

use a custom:slider-entity-row with the following configuration. Replace your input_number, the range on that input number should be the range a color picker. You'll also need card mod.

      - type: custom:slider-entity-row
        entity: input_number.quick_strip_hue
        full_row: true
        hide_state: true
        style:
          .: |
            ha-slider { 
              background: linear-gradient(to right, red 0%, #ff0 17%, lime 33%, cyan 50%, blue 66%, #f0f 83%, red 100%);
              border-radius: 10px;
            }
#

The result is

#

You'll still need the automation with that logic fyi

#

that you posted

#

or you can use this logic, which works with rgb

              {%- set hue = states('input_number.quick_strip_hue') | int / 360 %}
              {%- set s = 1 %}
              {%- set v = 1 %}
              {%- set i = (hue * 6.0) | int %}
              {%- set f = hue * 6.0 - i %}
              {%- set p = (255 * (1 * (1.0 - s))) | int %}
              {%- set q = (255 * (v * (1.0 - s * f))) | int %}
              {%- set t = (255 * (v * (1.0 - s * (1.0 - f)))) | int %}
              {%- set v = 255 %}
              {%- set i = i % 6 %}
              {%- set ret = [
                (v, t, p),
                (q, v, p),
                (p, v, t),
                (p, q, v),
                (t, p, v),
                (v, p, q),
              ] %}
              {%- set r, g, b = ret[i] %}
              {{ 'rgb({0},{1},{2})'.format(r,g,b) }}
#

the range on the input number is 0 to 360

naive vine
#

@mighty ledge I was already working in that direction. However I like your card more and would like to replicate it totally. Can you share your full config ?
PS I went through your GitHub but didn't find the above.

mighty ledge
naive vine
#

@mighty ledge I understand but still it gives an idea how the cards look like, how they work together and which automations you have build. It will most probably speed up my project, starting with this. Please would you send me the relevant info.

mighty ledge
naive vine
naive vine
#

@mighty ledge The input boolean you use to distinguish between temp and colour where did you place this one ?

mighty ledge
#

You don't need to distinguish between the 2

#

I only had to do that because of the bytes that my hardware accepts

naive vine
#

well a light can't be temperature colour (white) or colour

mighty ledge
#

for you, I'd have 2 separate automations. One that moves the color temp and one that moves the color

naive vine
#

once you choose one you can't have the other

#

for a given light

mighty ledge
#

yes, so they would have 2 separate service calls

#

you can attempt to make it in 1 automation, but it would be easier for 2

naive vine
#

trying to make sense of your lovelace

#

😩

mighty ledge
#

well, that's what I was trying to explain to you

naive vine
#

you used a lot of lovelace_gen

mighty ledge
#

this device that I have is beyond stupid, so I had to jump through hoops to do it

naive vine
#

I've learned a lot this last year with HA

#

but Jinja wasn't one of them

mighty ledge
#

The jinja that you see there just colors the icons, it's not needed

naive vine
#

well i'm looking into your templates

mighty ledge
#

all you need for the light slider and the temp slider are the cards that display them

naive vine
#

yes but of course I found other stuff that you have done that looks really COOL

mighty ledge
#

like what

naive vine
#

for example that you have a way to see all the lights that are on

#

on your main dashboard

mighty ledge
#

that will be hard to replicate without lovelace_gen

#

my entire setup is to allow me to be lazy

naive vine
#

i understand

#

but it makes it quite difficult to understand from the outside

mighty ledge
#

those files generate upwards of 300K lines of lovelace

#

so if you were to do this without lovelace_gen, that's what you'll be dealing with

naive vine
#

well i played with the templates of custom button card and decluttering card

mighty ledge
#

Yep, I avoid decluttering and using the button card templates because lovelace_gen doesn't need them

naive vine
#

i know

mighty ledge
#

so translating it will be difficult

naive vine
#

probably i'll start with my colour picker cards

mighty ledge
#

not to mention, I have a card in between that builds views dynamically, which I constantly forget how it works

naive vine
#

haha

#

you are way ahead of me

mighty ledge
#

If you want to use lovelace gen, i suggest learning jinja first.

naive vine
#

i looked at your TV remote cards

mighty ledge
#

That one doesn't really use lovelace gen too much

naive vine
#

i know

#

but i did those already in the past

#

and quite happy with my results

mighty ledge
#

the card that displays the quick light effects doens't use lovelace_Gen too much either

#

so, you should be able to take that entire quick ligh teffect card and paste it.

#

you just need to take the equations for the RGB values and use them in an automation

#

also, you'll have to remove the {%raw%} and {%endraw%} that was needed for lovelace gen

naive vine
#

okay

#

here is my TV card by the way

mighty ledge
#

yah thats nice

naive vine
#

i'm very happy with this one - probably way too many lines of code

#

but still it works

#

and for a "stupid" sales guy not too bad

mighty ledge
#

btw, those pictures in my config are way out of date

naive vine
#

i got that

mighty ledge
#

like 3 years out of date

naive vine
#

haha

#

i understand, time is an issue with everyone

#

but it is because of people like you, that HA has become what it is !

#

i'm now going to try to replicate your cards and see how it goes

naive vine
#

@mighty ledge for the slider what are you starting values ?

mighty ledge
naive vine
#

thanks - you took Kelvin and not merid

mighty ledge
#

I like the stupid device, but it required backflips to get the quick lighting effects to work

naive vine
#

the --paper-item-icon-color variable, can only be used within the card ?

tight lantern
#

Is there a way to capitalise (sentence case) the output of a sensor via a template sensor?, eg "rainy" to "Rainy"
Other than, just doing "if, elif elif"

inner mesa
#

{{ ‘foo bar’|title }} capitalizes every word, but not what I would call ‘sentence case’

dreamy sinew
#

title will do every word

tight lantern
#

that could work. i'll have a look

dreamy sinew
#

|capitalize is what you want

#

first letter of the first word only

tight lantern
#

oh okay, i'll use that instead

dreamy sinew
#

just depends on what you actually want. both have their uses

tight lantern
#

Title works! Thanks.

#

is this in the docs? Where would I find it?

dreamy sinew
#

'foo bar'|title -> Foo Bar
'foo bar'|capitalize -> Foo bar

silent barnBOT
dreamy sinew
#

that's a default filter of jinja2

tight lantern
#

aah okay. I'll defo have a look through then.

tight lantern
#

oh great! that's really useful.

#

thank you!

hollow girder
#

anyone using mqtt_room?

dreamy sinew
hollow girder
#

tks

trail estuary
#

I have this template: {{ as_timestamp(states("sensor.tide2mqtt_6_time")) | timestamp_custom("%A @ %H:%M") | replace("@"," " )}} rendering this: Thursday 16:43. How can I add one hour to the time rendered?

inner mesa
#

a timestamp is in seconds, so add 3600 before calling timestamp_custom()

mighty ledge
trail estuary
#

Off by the timezone, yes...

mighty ledge
trail estuary
#

Really??

#

I am assuming that ignores the TZ?

mighty ledge
#

no, it treats the timestamp as utc

trail estuary
#

Ah! It works! Thanks! 😉

mighty ledge
#

np

thorny snow
#

How can I get state of a entity using variable? Something like this.
url: "http://192.168.1.199/api/start/zone/ {{ states('input_select.zonenumber') }}?time={{states('input_number.zone{{ states('input_select.zonenumber') }}timer')}}"

inner mesa
#

you don't nest {{ }} like that

#
    url: "http://192.168.1.199/api/start/zone/{{ states('input_select.zonenumber') }}?time={{states('input_number.zone' ~ states('input_select.zonenumber') ~ 'timer')}}"
#

something like that

thorny snow
#

It's working! Thank you very much 🙂

inner mesa
#

good, I was trying to figure out how to test it with the least amount of screwing around 🙂

thorny snow
#

My job to test 🙂 Noobies should be able to spend time trying your advice so you don't waste yours!

silent ember
#

template section shouldve worked fine, wouldnt it? with a {% set ... %}

inner mesa
#

for what?

#

could have set a variable to avoid repeating states('input_select.zonenumber'), but it wouldn't have saved that much

silent ember
#

for testing, i meant.

inner mesa
#

I wanted to test constructing the string and having states() evaluate it

#

which would have required having an entity that matched. anyway, testing was done

silent ember
#

yeah, but that should work with set, shouldnt it? if you take a different entity and set/update the dict. oh yeah. I was just talking generally.

thorny snow
#

Thank you for your help! Goodnight 🙂

glacial matrix
#

Morning All, I think i need to make a template, but i'm not sure how, I have some sensors created from the garbage sensor plug in, and they have show as sensor.dishwasher_child1 sensor.dishwasher_child2 sensor.dishwasher_child3 Then in lovelace I just showa card with the child's name on bassed on if that sensor state is stoday, I'd like to be able to have a sensor or template called Dishwasher day that Show's the Friendly name of one of the above sensors, but i'm not sure how to do it.

thorny snow
#

Goodmorning! I am trying to set the minutes of a timer form the input_number. In developer tools template the result of this line minutes: "{{ states('input_number.zone_' ~ states('input_select.zonenumber') ~ 'timer') | int }}" its correct minutes: "24" but when I press check config i get Invalid config for [timer]: expected float for dictionary value @ data['timer']['irrigationtimer']['duration']['minutes']. Got "{{ states('input_number.zone' ~ states('input_select.zonenumber') ~ '_timer') | int }}". (See /config/configuration.yaml, line 376). \

fossil venture
#

inputnumber.zone should probably be input_number.zone Also you may need |float instead of |int.

thorny snow
#

I tried float and it's the same resutl. The config is right (auto-format maybe?) minutes: "{{ states('input_number.zone_' ~ states('input_select.zonenumber') ~ '_timer') | int }}"

#

The above is input_number.zone

#

int reports without decimals

marble jackal
#

enter the error message between code tags to avoid the auto formatting (3 backticks `)

mighty ledge
silent barnBOT
mighty ledge
thorny snow
#

Ok, understood! I bypassed my problem using an automation.

naive vine
#

Hello, I am sorry for a newbie question. I want to create a template to count the number of persons inside the house into a sensor. Anyone did something similarly ?

jagged obsidian
#

number of what?

naive vine
#

Number of persons inside the home based on presence detection iOS app or/and unify

manic onyx
#

hi everyone. Can someone please help me with a scrape platform? Trying to get a value of the first line (0 in this case)
<td class="COL5 NET"><span>0</span></td>

https://pastebin.com/zvzNhwgL

manic onyx
# ivory delta What have you tried?

Currently I am getting the value through
select: ".COL5.NET"
index: 37
Just thought there is a better way. I can index on DAILY-CASES class, but I do not know how to do a subcall in the same select

ivory delta
#

Subcall? Do you mean children?

manic onyx
manic onyx
ivory delta
#

Your current select will find all matching nodes that have both class='COL5' and class='NET' because there is no space between them. If you want to specify a parent/child relationship, you include a space. Something like this should pick up the nodes that have those classes and are children of the first table:
select: ".DAILY-CASES .COL5.NET"

manic onyx
#

there are multiple tables on the page called <table class="DAILY-CASES">
I am trying to get the values from the first line

#

I tried but got underfined

ivory delta
#

Ah... so all the tables are the same class too. That's terrible design and one of the things that makes scraping annoying.

manic onyx
#

yeah. I am dealing with it by using indexes, but at the moment just trial and error to get the right one just on COL5.NET

ivory delta
#

I don't think there's a better way based on their design. It's also risky, since they might change the order of the rows/cells and your index will be incorrect.

#

If there's another source for the same data, I would suggest using another site.

manic onyx
#

its the best I have 🙂

#

I was hoping to get like the whole html data for the table and use that

marble jackal
#

I have the following template in use to determine which covers to open in case of upcoming rain: {{ expand('group.screens')|selectattr('state', '==', 'closed') | map(attribute='name') | list }}

#

However, these covers on report closed when they are completely they are eg 50% closed, they will report open, but also in those cases I want to open them completely

#

I tried to change the template so it works with the attribute current_position but I'm not sure how to do that

#

Somethink like this does not work {{ expand('group.screens')|selectattr('current_position', '!=', 0.0) | map(attribute='name') | list }}

dreamy sinew
#

selectattr('attributes.current_position', 'test', 'testvalue')

marble jackal
#

what I want is to show all covers which do have current_position: 0.0

dreamy sinew
#

selectattr('attributes.current_position', 'eq', 0)

marble jackal
#

aaaaah! I had to add attributes. before the attribute 🙂

#

Thanks a lot! 👍 🥳

marble jackal
lofty bolt
#

Hello everyone!

I am trying to create a floorplan with WLED item and I cannot apply a filter CSS option for changing the light color on the floorplan.

Here is my image item: https://pastebin.com/4VcHn6SD
I've also tryied to use the following for the filter setting: https://pastebin.com/9kj31rw3 (I checked it on the developer-tools/template page and it returns the following result: hue-rotate(37.647deg)

Anyway, there is no filter css attribute in the result at all.

But it works fine if I set up this option manually, eg filter: hue-rotate(45deg)

Can anyone suggest me anything or tell me what I am doing wrong?

dreamy sinew
lofty bolt
dreamy sinew
#

should definitely post there as there probably won't be anyone in here that can help. deleting is up to you

next shell
#

Would this work to use it as a trigger and get notified when a node goes dead?

    - platform: template
      value_template: "{{states|selectattr('entity_id', 'search', 'node_status')|selectattr('state', '==', 'dead')|list|count}}"
  condition:
    - condition: template
      value_template: "{{ trigger.to_state.state != 0 }}"
    - condition: template
      value_template: "{{ trigger.from_state.state != 0 }}"
    - condition: template
      value_template: "{{ trigger.to_state.state != trigger.from_state.state }}"```
marble jackal
#

A template trigger should evaluate totrue or false. Your template seems to evaluate to a number.

ivory delta
#

Compare the result to another number to return a boolean. e.g. count > 0

next shell
#

ok great, thanks. Didn't recall that it should evaluate to true or false.

#

"{{states|selectattr('entity_id', 'search', 'node_status')|selectattr('state', '==', 'dead')|list|count > 0}}" with this i can also get rid of 2 of the conditions.

#

could I use message: "Node {{ trigger.entity_id }} has died" in the data field of the action?

ivory delta
#

Doubtful. The trigger isn't an entity.

#

The fields available depend on the trigger type.

#

My guess... you'd have to come up with a template that lists the dead entities... which shouldn't be too hard, since it's basically a tweaked version of your trigger 😉

next shell
#

ok thanks for the pointer.

inner mesa
#

even for a template, some entity_id state change caused the trigger

#

and trigger.entity_id is valid for a template

ivory delta
#

Ah, noice

magic lance
#

is there an attribute that can be used to identify devices sourced from a particular integration in a template (shelly integration for example?)

#

the domain / type of devices is not unique to the integration

dreamy sinew
#

No

magic lance
#

thanks @dreamy sinew , I scoured documentation and could not locate such item.

inner mesa
meager orchid
#

Hey folks - I'm looking to make a REST sensor to chart river flow rate from USGS. The rate is BURIED in the JSON response, and I've not been able to figure out the proper path for the value_template. Anyone handy at extracting JSON?

dreamy sinew
#

.values is a function keyword and causes issues. need to either use ['values'] or .get('values')

silent barnBOT
#

@cinder lotus 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.

#

@cinder lotus 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.

cinder lotus
#

WTx is going on here. I'm not able to post. Always get a message 'Virus detected' by HassBot

silent barnBOT
cinder lotus
#

My post does not contain any link 😫

silent barnBOT
#

Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).

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

cinder lotus
#

And for pictures? Not allowed here...

inner mesa
#

not if you're going to post pictures of text

#

otherwise,

silent barnBOT
#

Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images.

cinder lotus
#

And if I'd like to show the result of Developer Tools - States..

ivory delta
#

6 lots of spam in only a few minutes. That's gotta be a new record.

#

Show it using text then. Copy/paste is a thing.

cinder lotus
#

15 lines, great rules...

#

A picture can tell more than a page of text 😉

ivory delta
#

If you don't like the rules, you don't have to use this server 🤷‍♂️

#

And pictures are really awful for sharing text. They're hard to read on small devices and they're difficult to edit in cases where we want to tweak something for you.

#

If you want support, share the attributes using a text sharing site.

mighty ledge
# cinder lotus 15 lines, great rules...

The rule is there to keep huge posts out, just use pastebin. Anways to answer your question...

sensor:
     - platform: template
       sensors:
         vandaag_actueel:
           value_template: "{{ state_attr('weather.buienradar', 'temperature') }}"
           friendly_name: Vandaag actueel
cinder lotus
ivory delta
#

Unfortunately for you, you're not the one setting the rules 🤷‍♂️

cinder lotus
ivory delta
#

👋

mighty ledge
cinder lotus
#

Seems, very quitte now 😉

honest slate
#

Hello. Which entity use to make "I'm home!" switch? Idea is to make such button on Lovelace , which can switch other switches, like water pump, motion sensor, etc. And can be switched manually via GUI or auto with some presence detection.

mighty ledge
honest slate
#

Ok. Thanks.

honest slate
#

And what's the trigger platform then? State?

mighty ledge
#

yea

sturdy rock
#

Hi Guys, Need your help on this please

21:55:29.775 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:29","APDS9960":{"Down":1}} 21:55:33.050 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:33","APDS9960":{"Up":1}} 21:55:37.584 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:37","APDS9960":{"Left":1}}

The adobe is how my sensor gives me response for which I've created the mqtt sensor as below and this gives me value as Gesture Sensor: {'Left':1}. how can I extract value which shows me only the direction like Gesture Sensor: Up or Gesture Sensor: Down

- platform: mqtt name: "Gesture Sensor" state_topic: "tele/gesture/SENSOR" value_template: "{{ value_json.APDS9960 }}"

meager orchid
#

@mighty snowhx with that I'm getting a "TypeError: the JSON object must be str, bytes or bytearray, not dict" in the test template.

#

@dreamy sinew ^

dreamy sinew
#

Wrap your sample json in quotes

meager orchid
#

Like this "{ my sample json }" or this {" my sample json "}

#

niether seem to work - both give me a "TemplateSyntaxError: expected token 'end of statement block', got 'name'" error. Name is the first key in the sample json

dreamy sinew
#

{% set my_json = '{}' %}

ebon yoke
#

i want to create a new template sensor just to discard erroneous values from the real sensor.. i'm getting a lot of negative values, so these need to be filtered out

#

how can i do that?

#

and do i need to use an automation for that?

#

so that every time the sensor changes, then update the template sensor?

fossil venture
#

Template sensors update whenever the entities they contain change. So no, you do not need an automation.

main steppe
#

value_template: "{{ (states('sensor.p1_rechtstreeks_verbruik') | round(2)) / (states('sensor.p1_totaal_verbruik') | round(2)) * 100 | round(1) }}"
Why does my code ignore the round(1) part? The result of this code is: 51.576292559

fossil venture
#

You are rounding the number 100: 100 | round(1) use some brackets

main steppe
#

Aha I see! Thank you @fossil venture

rugged forge
#

Home Assistant is not reading My soil moisture sensor after I had introduced a template to limit the display of values. Could you please help me?

fossil venture
rugged forge
weary drift
#

What would be the best way to "update entity" after something is done?
In this case my blinds doesn't report back state if i dont update the entity.
A script that open - waits - updates?
A switch in Nodered?
Or can i do this with a template?

fossil venture
#

How are your blinds integrated into Home Assistant? I have the same issue with my TV. Because its state is polled it takes forever to report back that it is on after I turn it on. So I do this in the turn on script https://paste.ubuntu.com/p/GMBWkKfMNh/ You could do something similar either in a template cover or in a script.

weary drift
#

It's IKEA Fyrtur so Zigbee with ZHA.

#

I'll check. Thanks

weary drift
#

Can i set the state on the template entity some how?

sturdy rock
#

21:55:29.775 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:29","APDS9960":{"Down":1}} 21:55:33.050 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:33","APDS9960":{"Up":1}} 21:55:37.584 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:37","APDS9960":{"Left":1}}

The adobe is how my sensor gives me response for which I've created the mqtt sensor as below and this gives me value as Gesture Sensor: {'Left':1}. how can I extract value which shows me only the direction like Gesture Sensor: Up or Gesture Sensor: Down

- platform: mqtt name: "Gesture Sensor" state_topic: "tele/gesture/SENSOR" value_template: "{{ value_json.APDS9960 }}"

ivory delta
#

This should do the trick:
{{ value_json.APDS9960 | list | first }}

sturdy rock
#

Thanks you so much @ivory delta This worked 😇

fossil venture
weary drift
past ocean
#

any reason that some devices continue to float in the topology map even when added right next to a router with "add devices through this device"?

ivory delta
#

It's probably just that they didn't report in when the map was being built. If they work, it's no big deal. The mesh self-heals anyway.

timber cliff
#

I'm having trouble understanding the documentation. how do I check if a string contains a literal string. I'm not seeing an .contains or .indexof

inner mesa
#

you can also do this:

#
{% for i in states.switch if 'keypad' in i.entity_id %}
    - {{ i.entity_id }}
{% endfor %}

{% for i in states.switch if i.entity_id.startswith(‘foo’) %}
    - {{ i.entity_id }}
{% endfor %}
timber cliff
#

somebody really likes { and %

scenic solstice
#

@timber cliff if this is for your calendar no school question. Using Google cal I have a calendar entity based on a string in the cal entry.

timber cliff
#

I am very new to templates and HA. Is that a helper?

timber cliff
inner mesa
#

Jinja templates are surrounded by {{ }} and it looks like you have a mismatched parenthesis. A better template would be this: {{ "NO SCHOOL" in state_attr('calendar.school_calendar', 'message')|upper }}, or something similar

#

better yet, just create a template binary_sensor with that template and it will automatically be true or false without the need for an automation

inner mesa
#

what does what look like?

timber cliff
inner mesa
#

Not if you have at least one. configuration -> Server Controls

main steppe
#

Is there an easy way to get the value of a sensors data yesterday at 23:59h?

#

I have solar panels and I would like to see how much power they produced. It resets every day at 0.00h. So I'd like to see the value it had yesterday at 23:59h.

eager sentinel
#

Is it possible to use a template to check the status of a lamp and if it is on to send the service call in the next line to turn it off?

can command be sent here? ```
#

I'm able to get the on/off readout of the lamp but just not sure if I can even send the call because none of what I am trying is working or I am not quite sure of the format

fossil venture
young shadow
#

Hey Guys!
is it possible to specify multiple actions via templating in an Automation?
Like this:

- service: delay
  hours: 1
  minutes: 0
  seconds: 0
- service: switch.turn_on
  target:
    entity_id: switch.mosquito_killer
{% else %}
service: switch.turn_off
target:
  entity_id: switch.mosquito_killer
{% endif %}```
fossil venture
young shadow
#

WOW Choose looks promising! Thanks for the quick answer!

grim flicker
#

i have this template. {{ is_state_attr('climate.airco_slaapkamer', 'fan_mode', 'High') }}
Is there a way to check if attr is not a specific value. i tried is_not_state_attr but offcourse that would be too easy lol

grim flicker
#

Thanks ill try that. i fixed it now by doing this:

#
    conditions:
    - "{{ is_state_attr('climate.airco_slaapkamer', 'swing_mode', 'Up') }}"
    - "{{ is_state_attr('climate.airco_slaapkamer', 'fan_mode', 'Low') }}"```
hollow sand
#

Hi everyone, i just updated hassio to 2021.7.4 and im experiencing issues with the light templates, it seems like the new way hassio is handling white and color brightness separately is giving me issues, i tried finding a solution but im stuck due to the light template not supporting rgbw values as color template (?) witch is the only supported mode my strip has.
Has anyone else experienced something similar and found a solution ?

bright quarry
#

i have a template that writes an entity _input_text.patiodoortime, but the value clears itself every time HAS restarts. how can i make it persistent across restarts? ex;

      - service: input_text.set_value
        data:
          value: |-
            {{ 'Patio Door -
             {}'.format(now().strftime('%a, %b %d at %I:%M %p')) }}
        entity_id: input_text.patiodoortime
inner mesa
keen sky
#

Hi, can I ask to guide me for one template. I have raindrop sensor , which is programmed with esphome and have entity , which show me Voltage (1.00, 0.78 and so on). I want to have binary sensor , when the sensor is 1.00 V to be off in other cases to be on.

#

{{ states('sensor.boiler_flood_2')|float == 1.00 }}

fossil venture
#

{{ states('sensor.boiler_flood_2')|float != 1.00 }}

granite pendant
#

What is the proper way to get a last_updated for a binary sensor?

state_attr(“binary_sensor.mysensor”, “last_updated”)
Or
states.binary_sensor.mysensor.last_updated

inner mesa
granite pendant
#

Thank you. Wish there was a ui for this

#

I’m having a lot of trouble stringing this together..

I just want to have a yes/no of whether another sensor has been opened today.

It was suggested to use last_updated, but after testing, it looks like that tracks Unavailable or closed, which I don’t want; I specially would like whether the sensor has been open today. Is there a combination of tests I can use for this? I’ve been going through several doc pages but cannot crack it

inner mesa
#

A trivial way is an automation that triggers when it’s open and sets an input_boolean and another that clears it at midnight

granite pendant
fast oracle
#

i have 2 different automation using the same wait_template, but seems to only work with the first automation to trigger. Is this a limitation of wait_template?

inner mesa
#

No

fast oracle
#

i use this in both automation - wait_template: "{{ states('sensor.powerwall_charge') | int < 90 }}"

#

but the 2nd automation never goes to the next step

inner mesa
#

wait_template is pretty straightforward:

#

WAIT TEMPLATE

This action evaluates the template, and if true, the script will continue. If not, then it will wait until it is true.

#

Review the automaton trace

fast oracle
#

this is from the trace ```Executed: July 25, 2021, 12:35:06 PM
Result:

wait:
remaining: null
completed: false

#

i use the same wait_template in both automation

#

the other automation show completed: true

inner mesa
#

I like using a persistent_notification to tell me the value of something before I check it

#

It might be fluctuating and just a timing issue

fast oracle
#

i'll take a look at that.. the sensor dropped to below 80 when i noticed the wait_template didn't complete (automation triggers at 95 and supposed to turn off when below 90)

#

(action to turn off when below 90 via wait_template)

inner mesa
#

I don’t use them often, but I don’t see why it wouldn’t work. It’s not waiting for a trigger, just an instantaneous test should work

fast oracle
#

it's just odd that it work on automation A, but not B. Only difference is A triggers at 93, B triggers at 95 and target different entity to turn on. Otherwise, the 2 automation is exactly the same.

inner mesa
#

~share them and perhaps there’s another clue

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

inner mesa
#

That’s why I posted the bot message….

fast oracle
#

deleted it..

inner mesa
fast oracle
#

thanks.. i'll try it out

pine musk
#

I am trying to read the RGB_color from a virtual entity, and when that virtual entity changes, update the equivalent actual entity

#

got as far as the following template {{ state_attr('light.virtual_uplights','rgb_color') }}

#

trying to figure out how to set the real uplight to match

pine musk
#

ok, so I have figured out how to rewrite the template to get the correct list format.

#

but this is not working for the setting the physical lamps:

type: turn_on
device_id: d77aa2e2df31f76210edfb049d7a16db
entity_id: light.002007915ccf7f498b41
domain: light
rgb_color: '{{ states("sensor.set_color") }}'
#

it does not like the rgb_color line

ivory delta
#

does not like
🤔

silent barnBOT
#

Please don't say I have an error or describe an error. Share the whole actual error message so we can help you.

pine musk
#

Message malformed: extra keys not allowed @ data['rgb_color']

ivory delta
#

Then it's not allowed for a device. Use entities and services like a sane person.

#

One of the problems with the device stuff is that it's not well documented.

pine musk
#

that seems to have accepted the template. But the automation does not trigger on any changes to the virtual entity

ivory delta
#

So it's time for the standard automation testing.

pine musk
#

ok, swinging over to automations at this point, but looks like manually triggering the automation works.

left patio
#

Whats the simplest way to get an timer counting up when a smartplug is turned on? I want to display it on my lovelace ui but its way harder to accomplish then i thought. 😄

#

currently i build an sensor with history_stats which works but now i have the problem with resetting it after turning the smart plug off again.

silent barnBOT
plain mural
#

Hello,
I want to have an overview over gas prices in the area around me, so I created two groups (Super E5 and Diesel) for. Works so far, but does not look that good.

Best would be to have a table that can be sorted which contains columns for city, brand, e5 and diesel, is that possible?

Current markdown looks like: (Code see Paste by HassBot)

mighty ledge
plain mural
#

oh, damn, i hoped for a quicker solution. Can I use two groups then in the same table? See paste above, there i have the diesel list after the gas list even if the gas stations are the same

mighty ledge
plain mural
#

Oh, i guess im too new for that at the moment

tardy dove
#

Are there NEW and OLD ways to implement Template Entities? I just bumped into the limitation where you can't use Template Integration in packages. I'm reading some refer to these as "legacy templates" ? What is the NEW way to setup template entities ?

mighty ledge
#

Yes there is a new way, it's covered in the docs extensively. The 'legacy' way still works and works with packages.

tardy dove
#

@mighty ledge Any chance you have a link to a doc that mentioned "legacy" vs "new way" so I can understand which is which?

silent barnBOT
mighty ledge
#

that's wrong

silent barnBOT
#

Integrations integrate Home Assistant with devices or services, or provide functionality within Home Assistant. Add-ons provide additional software or services, which an integration could possibility integrate with. Add-ons are for Home Assistant OS and Supervised only, other install methods can install software other ways.

mighty ledge
#

just go to the integration docs and search template, it's covered there

#

click on the one that's just labeled 'template'

tardy dove
mighty ledge
#

yep

tardy dove
#

But the new way doesn't work in packages?

mighty ledge
#

nope

#

before you complain, the old way isn't going away

#

so stick with the old way.

#

Can you tell this has come up 100000 times 😆

tardy dove
#

I was actually wondering why there isn't support for packages in the new format. I'm a bit confused at times why it seems there is an "either/or" approach to YAML vs UI config in HA. I went with packages so that it would be easier to share as well as backup. (snapshots arent as accessible)
Would think this is the format most power users would prefer.

mighty ledge
#

It's 100% the opposite way I think.

tardy dove
#

Sorry?

mighty ledge
#

packages

#

they don't help with organization for me

tardy dove
#

how do you organize than and share config with others?

mighty ledge
#

I organize via files

#

just not packages

#

anyways, packages are ham-fisted into home assistant. A major refactor is needed in order to properly support packages everywhere, including template.

#

So, you'll have to wait for the new template style to be added to packaging

tardy dove
#

very interested if there is a better way to organize as an alternative to packages

#

Would be helpful to see an example config structure that just uses files and not packages

mighty ledge
#

the problem I have with packages is this: If I have a problem with a cover, where do I look?

tardy dove
#

essentially its all organized by "integration" and not by logical buckets?

mighty ledge
#

Well, I now need ot remember where I thought the cover should be packaged, then I need to go search for it

#

with an organization based on integration, I know exactly where it is. Immediately.

#

logical buckets aren't logical when editing though

#

also, i means you need to have 2 sections of the same file open in different editors when editing or making changes

tardy dove
#

fair. Packages is how I think. If I have an issue with something security related (cameras, locks, alarm) its all in security.yaml including all their templates, automations etc.

mighty ledge
#

what happens when you use a template that's used in 2 different packages?

#

seems like you'd create a new package, then forget about said package, and then spend an hour looking for it

tardy dove
#

hasn't happened yet. But likely there are going to be edge cases. Most importantly, I'm more inclined to use what is closest to the direction that the core is going. So if the plan is to walk away from packages.... then I'd likely do so as well.

mighty ledge
#

I don't think that is the plan, but it's spagetti code currently so it's not 100% safe

#

but so many people use it that I doubt itwould go away

tardy dove
#

K... thanks for the incite.

mighty ledge
#

so, it would probably be a major refactor at some point, then it would be added everywhere

#

but, currently, there are no maintainers for that section of code. So I'm not sure when any of this will happen.

timber cliff
#

is either way preferable? {{ state_attr("calendar.school","message") }} or states.calendar.school.attributes.message

inner mesa
#

the former. it's in the docs

timber cliff
#

one day I'll read the docs. But seriously there is a lot of information to consume. I appreciate the humans here.

#

and the bots.

low blaze
#

I know I'm being dense but I've attempted many times to use the wiki to figure this out. how do I get the "time" of 2hrs ago

#

now().something? (hours=2)

#

?

#

timedelta doesn't seem to work

inner mesa
#

It will

low blaze
#

do i do it like this? end: "{{ now().replace(hour=0, minute=0, second=0) }}"
duration:
hours: 24

#

just use now() as end

#

?

inner mesa
#

{{ now() - timedelta(hours=2) }}

low blaze
#

Thanks Rob!

primal snow
#

Hey guys, does anyone know how to pass a predefined variable to be used in templates

  • platform: wake_on_lan
    name: "RPI"
    mac: "DC:A6:22:13::"
    host: "192.168.1.43"
    turn_off:
    service: shell_command.ssh_cmd
    data_template:
    username: pi
    ip: >
    {{ host }}
    cmd: 'sudo reboot'

I want to pass the host to ip so it doesn't repeat itself in the data_template but it just doesn't work

fossil venture
#

No, no one knows how because that option does not accept templates. Very few integration configuration options do. And if they do, they say so explicitly in the documentation. Templates are mostly used for services and service data in automations and scripts.

primal snow
fossil venture
#

You could define and use a secret host: !secret my_ip_address but that's longer than typing out the ip address.

primal snow
#

yep. typing it is then 😄

fossil venture
#

Actually i thought you meant templating the host: option. You can actually use a template in the turn_off action. The problems with using {{ state_attr('switch.rpi', 'host') }} are twofold, 1) I don't know if that attribute actually exists, and 2) Even if it does exist after the WOL switch is initialised, it wont exist while the WOL switch is initialising, which is when it is needed.

floral shuttle
# mighty ledge what happens when you use a template that's used in 2 different packages?

as someone who's complete config is organized in (75) packages, I can assure you forgetting a package is not very likely to happen. And in the edge case a config item (like a template, or maybe an automation, heck a global script even) should be needed in more than 1 package, creating a 'meta' package for those is very easy. And keeps the logic of the complete config in tact. Only exceptions I encountered are the browser_mod settings and the 'new' template: integration. Not sure why we would need a 'major refactor' just for those, though appreciative of the efforts it would take to only support packages for template: alone.

#

and if one is really lost in their own config, a global search in the editor is very quick 😉

safe meadow
#

Trying to wrap my head around templates for effect_list. Monitoring the MQTT device, it publishes "rgb_cycle" or "color" or "white", but to set it, I set with 0,1,2. So Right now, I can have an effect_list with the correct names but doesn't push the right data to the device, or I can set the list as "0,1,2" but the device status shows the string, not the number... so it is broken either way. I'm having problems figuring out where/how to set the "0 == rgb_cycle" and "1 == color" settings

fossil venture
mighty ledge
floral shuttle
#

sure, and please have it your way, totally appreciated. then again, that needn't necessarily be the absolute truth for HA. Many users use packages and organize the config around their sense of logic.. To me pushing the domain concept as central to the organization is not how I feel my surrounding.

safe meadow
#

thanks @fossil venture ! I was looking for a mapper and just could not find the right keyword (granted, i wasn't thinking of the word "mapper")... but this still doesn't quite solve it. The command to send to the mqtt device is with a number, but the stat/%topic%/effect output is in the string... so if I define the strings with the mapper, it will still have a problem with reading the current state, or can I set a mapper for both the input select as well as the current state value?

fossil venture
#

Share your config.

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

safe meadow
true otter
#

what am I missing

mighty ledge
# true otter what am I missing

You're missing the actual code. You just placed the entity_id in there. Take a look at any example and compare it to what you wrote

#

every one of those templates has a basic error in them

#

how do you get a state out of an entity?

true otter
#

okay so looking at the template guide this is what I have now {{ states('sensor.garage_smoke.attributes.battery_level') }}. I am no longer getting an error, but now I am getting this ```Result type: string
unknown
This template listens for the following state changed events:

Entity: sensor.garage_smoke.attributes.battery_level```

dreamy sinew
#

what you have there is not an entity_id

true otter
#

is the unkown a limitation of the device or my understanding of templates. Okay can you share an example with me?

dreamy sinew
#

the unknown is because you passed something that isn't an entity id to states() which is expecting an entity_id

true otter
#

this is the entity_id of the device sensor.garage_smoke_detector_battery

dreamy sinew
#

ok, that's step one

true otter
#

so this is my new template {{ states('sensor.garage_smoke_detector_battery') }}

dreamy sinew
#

that will get you the state of that entity

true otter
#

so it should be this `{{ state_attr('sensor.garage_smoke_detector_battery') }}, but that give me an error in Dev/Template.

#

UndefinedError: 'states_attr' is undefined

#

so I changed the entity id and I now hove a reading . {{ states('sensor.garage_smoke_battery_level') }}

#

but this how not triggered an error during the config check process
Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states('sensor.garage_smoke_battery_level')", None)])"
in "/config/packages/emergency.yaml", line 102, column 0

arctic sorrel
#

With no context on where you're using the template how the heck do you expect anybody to be able to help you?

true otter
#

I have trying to understand why this is throwing this error and correct the problem.

#

I plan to eventually use the output in some notification about changing batteries.

arctic sorrel
#

Those templates are coming from somewhere in your config

true otter
vestal arch
#

Hi, is there a way to get in a template, from HA's config, the working local HA url (http://x.x.x.x:8123) and the User Profile Language selected?

ivory delta
#

Not directly in a template. Maybe you can set up some kind of sensor that exposes that (head to #integrations-archived for that).

vestal arch
inner mesa
#

base_url was eliminated last year

vestal arch
#

base_url, internal_url, external_url

inner mesa
#

ok, I don't know what uses that anymore

#

it's all about internal_url/external_url now

vestal arch
#

I need to access the internal_url from a template but I guess I'll need to do an API call with a rest command

#

I couldn't find the language setting in the API though

sonic nimbus
#

Hello, how to get source of input of my tv?

#

`is_state('media_player.kitchen.source', 'Tuner')'

#

I know how to ask if device in some state => True/False, but I really need to get the actual source name

#

for example Spotifyor Plex..

#

I tried this but I have still None : {{ state_attr('media_player.livingroom_tv', 'source') }}

naive vine
#

I want to get the status out the follow API/JSON output {"status":"OK","meta":{"time":"2021-07-29T16:19:09","tid":"1627575549_MtLg","version":"1.0","token_limit":2000,"token_remaining":1019,"last_active":"2021-07-29T16:19:09","token_reset":"2021-07-30T00:00:00"},"data":{"sensor_data":[{"id":13169891,"time":"2021-07-29T16:04:02","local_date":"2021-07-29","local_time":"19:04:02","moisture":14,"sunlight":0.832,"celsius":28.0786,"fahrenheit":82.5415}

inner mesa
#

.status

naive vine
#

i have the following code

#
- platform: rest
    name: whisperer
    json_attributes_path: "$.[0]"
    json_attributes:
      - moisture
      - sunlight
      - celsius
    resource_template: "http://www.api.com"
    scan_interval: 3600
    value_template: "{{ value_json.status[0].status }}"
#

but don't get the status

inner mesa
#

why are you treating status as a list?

naive vine
#

i probably made a mistake

#

i got the attributes good out

inner mesa
#

"{{ value_json.status }}"

naive vine
#

Effectively, that did the trick !

#

thank you so much !

ivory delta
#

.share your config

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

ivory delta
#

And what do you get from {{ value }}?

fossil hearth
#

all nothing

ivory delta
#

Then you're probably getting nothing back from the command. Where are you running it from when you see it work?

fossil hearth
#

am running it in ssh to home assistant

#

the community one

ivory delta
#

Then there's a chance it's not running where you think it is. But this is a topic for #integrations-archived, since the problem isn't with your template.

fossil hearth
#

i see , what do u mean by where you think it is ?

ivory delta
#

Well first... move to the right channel.

fossil hearth
#

on it 🙂 doing now

supple sparrow
#

I created a template to know if a certain spot is covered by my west-facing awning or exposed to the sun. https://hastebin.com/qewafelebe.cpp
y0,z0 mark the position of the awning with respect to the spot when closed
y1,z1 mark the position of the awning with respect to the spot when fully open
yc,zc mark the position of the house roof (which also can cast a shadow on that spot) with respect to the spot

It is working, so I hope it could be useful for someone else.
Also, any comments on how to improve it would be really welcome. Please do @ mention me.

mighty ledge
# supple sparrow I created a template to know if a certain spot is covered by my west-facing awni...

I think you just made it more complicated using dictionaries and you made it lengthier and harder to read and edit. Also, you made some unnecessary float casts. Attributes hold their type and don't need to be cast because they are not strings.

template:
  - binary_sensor:
      - name: "Toldo1 sol"
        state: |-
          {% set y0 = state_attr("cover.toldo1","y0") %}
          {% set y1 = state_attr("cover.toldo1","y1") %}
          {% set yc = state_attr("cover.toldo1","yc") %}
          {% set z0 = state_attr("cover.toldo1","z0") %}
          {% set z1 = state_attr("cover.toldo1","z1") %}
          {% set zc = state_attr("cover.toldo1","zc") %}
          {% set pos = state_attr("cover.toldo1","current_position")/100.0 %}
          {% set elev = pi*state_attr("sun.sun","elevation")/180.0 %}
          {% set azim = pi*state_attr("sun.sun","azimuth")/180.0 %}
          {% set y = y0*(1-pos) + y1*pos %}
          {% set z = z0*(1-pos) + z1*pos %}
          {{ elev > 0 and 
             (y*sin(elev)/z - cos(elev)*sin(azim) > 0) and
             (yc*sin(elev)/zc - cos(elev)*sin(azim) > 0)
          }}
supple sparrow
mighty ledge
#

Those suggestions are just nitpicks

#

good template otherwise

supple sparrow
#

Next thing I did is I created an automation that makes sure that the spot is actually in the shadow at all times, by slowly opening the awning as needed, using those binary sensors in automations.

#

Then I turned the automation into a blueprint (so that I could more easily change the logic for my three awnings)

#

But the template binary sensors... I don't see how I can "factor them away"

mighty ledge
#

You can factor them away by putting all the constants into variables in the automation and performing the calc live as a template trigger.

supple sparrow
#

That (variables in template triggers in automations) does not work - I tried

#

In conditions, I have not tried (I would need that to work too)

mighty ledge
vocal linden
#
{% set power = states.sensor | selectattr('attributes.unit_of_measurement', "equalto","W") | selectattr('attributes.device_class', "equalto","power") |map(attribute='state') |list %}
{% set powerTotal = 0.0 -%}
{% for value in power -%}
  {% set powerTotal = powerTotal + value|float -%}
  {% if loop.last -%}{{powerTotal}}{% endif -%}
{% endfor %}
#

it is not summing up powerTotal, what im doing wrong?

#

Trying to automatically get all values from all power sensors and sum their values up, thats my main goal so i can make a template sensor which has the sum of all power entities.

dreamy sinew
#

need to use namespacing

#

stuff in a loop can't affect stuff outside of a loop without namespace

vocal linden
#

Ahh thanks that was the only thing i needed for the fix 😄

mighty ledge
vocal linden
#

Theoretically yes, but later I do add some logic to only sum up all sensors which are lights and i do this via the firendly_name if it contains "Light". This sorting is easier in a for loop for me via if statements

mighty ledge
#

you can still filter to find out if it contains light

vocal linden
#

But im doing this directly from brain to terminal without making any concepts, so it could be that a better solution exists for that case 🤪

mighty ledge
#

| selectattr('attributes.friendly_name', 'search', 'Light')

#

The use cases for namespace are extremely small in the current version of home assistant

vocal linden
#

is search case sensitive?

mighty ledge
#

it is

#

and 'match' is equivalent to startswith

#

so, namespace is barely needed unless dealing with datetimes

vocal linden
#

yeah i hope theres nothing named "ight" that isnt a light so then i can search without worrying witch casesensititvity😂 Thanks for the help

mighty ledge
#

then filter based on the domain

#

before checking light

vocal linden
#

the domain is sensor cause which I created with a custom component for each light. So the other created power sensors e.g. my pc is also on that domain. But should work this way. Otherwise i can take the old ugly solution or i can introduce a manual naming convention for the sensors instead of letting the custom component create the friendlyname

sturdy rock
#

Hi Guys

I'm trying to set a sensor which show me the battery in % from voltage I've tried the following, how ever this will give me wrong results as the Li-Ion battery min voltage is 3.2 that is it should tell me 0% and 4.2 is 100% how do it do it in a template, help please.

cube_battery_level: friendly_name: 'Battery Level' unit_of_measurement: "%" value_template: > {% set bat = states('sensor.power_cube_battery') | float %} {{ ((bat / 4.2) * 100) | round(1) }}

inner mesa
#

{{ ((bat - 3.2) * 100) | round(1) }}

sturdy rock
#

Thanks much @inner mesa

glad geode
#

Can I call a service in a template?

inner mesa
#

No

#

That’s a pretty strange thing to want to do

glad geode
#

Thanks 😄

#

I haven't got a lux sensor in my bedroom so I was going to make a template sensor to act as one, but it would need to convert the light brightness value to lux, which I have in a function in pyscript. But I've just realised that I'm setting light_lux on the pyscript entity so the template sensor can track that

#

Until I get the lux sensor, of course

inner mesa
#

services don't return anything, so it's not possible to call one and get a result that you can use later. And only Jinja is supported in templates

glad geode
#

Good point. Didn't think of that

#

The no return value

trail estuary
#

Templating time... I give up...
I have a sensor (sensor.docker_adguard_up_time) that has a state in this format: 2021-07-31T22:38:16.301019+02:00. How can I calculate how long ago that is??

sturdy rock
#

value_template: "{{ relative_time(states.sensor.docker_adguard_up_time.last_changed) }}" Try this @trail estuary

trail estuary
sturdy rock
#

As far as I remember yes it dose.

#

and yes it works with any entity

trail estuary
#

Brilliant! Thank you!! 😄

#

The only problem with that is of course that it will reset when I restart HA... That wont work....

sturdy rock
#

Yes that's true, I was using it to check when was the last time any of my door or motion sensor was triggered and with every reboot it use to reset.

glad geode
#

There's always pyscript (or python_script). It would be utterly trivial then

trail estuary
#

This {{(as_timestamp(now()) - as_timestamp(states.sensor.docker_adguard_up_time.state))}} gives me this: 3823.7006199359894. I am sure there is way to print that in a human readable format?

silent barnBOT
sturdy rock
#

and it gives output as 1 Day, 4 Hrs & 56 Mins

trail estuary
#

I'll give it a go! 😉 Thanks!

trail estuary
#

That worked perfectly! I get the logic behind but the formatting you use is magic!

median mason
#

i have a button containing motion icon. i am using custom button card. i want to use variable to change the color of the icon. i am using following code for this. but its not working. can anyone correct the code?

custom_fields:
        motion:
          - color: >
              [[[ if (states.binary_sensor.hue_motion_sensor_1_motion.state === 'on') {return var(--primary-color)} ]]]

working code:

custom_fields:
        motion:
          - color: var(--primary-color)
scarlet kernel
#

I've hit some odd situations in which despite specifying an availability_template that should evaluate to false the value_template renders with bad data; I think there's a race condition and problem with evaluation order but I'm having a devil of a time chasing the flow of the code

#

To work around the issue is it sufficient to just return the string "unavailable" in the value_template or will that have side effects? While my template takes a number of inputs limiting with triggers has been successful

scarlet kernel
pastel moon
#

How would I return a dict from a sensor? I have this in DevTools https://paste.ubuntu.com/p/xcKSxCfJHk/, but cant figure how to create something like ['K': K, 'B': B] to be picked up by my scripts... Ideas? Background is I do a lot of the same calculations in many scripts/automations. It would be neater to have this done once and then reuse the sensor value/dict

#

a simple list like this {{ [K,B] }} is easy, but a dict? I guess I could always expect values are in the same order, but calling by name would be better

pastel moon
#

got it I think, please correct if can be done better; ```
{% set dict = {"Kelvin": K} %}
{{ dict }}

pastel moon
fossil venture
pastel moon
#

Thanks, modified {{ dict }} to {{ dict | to_json }}, and restarted HA, no change yet tho...

#

I get this in DevTools Template tab, so it seems to work somewhat at least? { "Brightness": 88, "Mireds": 286, "Kelvin": 3500, "Pod": "day" }

fossil venture
#

Looks like it is working to me.

pastel moon
#

Ok. Perhaps States tab can't show this? I'll give it a try in the script then. Thanks 🙂

fossil venture
#

The States tab should be able to.

pastel moon
#

So I thought, but it still reports as unavailable. Same result when tried to access it in a script. What else can be at fault here?

#

I made a small script with this declaration```
variables:
map: "{{ states('sensor.lad') }}"
brightness: "{{ map['brightness'] }}"
pod: "{{ map['pod'] }}"

pastel moon
#

Think I found it... 😦 Variables was defined in DevTools, forgot that when adding to configuration.yam, so unavailable was indeed correct. Thanks @fossil venture for the help

supple sparrow
final mulch
#

Hi. I noticed that my REST sensor with a value template updated the state every 3 minutes and write it to the Database. As the value doesn't change that much I do not need so much information.
So is there a way to prevent writing the state to the DB when old and new value are the same? I tried it already but it doesn't work 😦
Here is how it looks like: https://pastebin.com/2ghJLRx6

ivory delta
#

That's only the template, not the full sensor config. Share the whole thing.

thorny snow
#

im not sure if this is the right place. Is it possible to stream local music stored on the raspberrypi to a media player in the form of a playlist? Singel mp3 files work fine.

ivory delta
thorny snow
#

thanks 🙂

final mulch
#

But I think I just got it by myself as I added force_update = true

#

🤦‍♂️

ivory delta
#

Yeah, that was going to be my guess 😄

edgy umbra
#

I have a group light.all_lights with all my light entities. I made a template to use a brightness slider only for the lights that are on from the light.all_light entity. For some reason soon as i adjust the slider all other lights from the group will become on. Anyone know what is wrong in my template? 🙂 https://pastebin.ubuntu.com/p/dcBvpw8Z24/

final mulch
#

any idea how I cloud remove the duplicate entries in the madiadb now?

ivory delta
#

Why would you want to? Just let them expire naturally.

final mulch
#

bacause the DB is grown to multiple GB of data -.-

ivory delta
#

And now you've figured out how to stop it growing so quickly. Those entries will disappear after a few days.

#

If it's filled your disk and you desperately need the space back, you can either delete the DB or you can go learn some SQL to delete specific things.

final mulch
#

yes... was looking for a SQL that deletes entries with same states value of the same entity (but different time). To just keep the oldest... but didn't find one

edgy umbra
#

Anyone here can help with the history stats template? Have made one for today, week and month stats but i'm not sure how to start at monday 00:00. 🙂

#

What exactly means the end: "{{ now() }}" part? Is that the time you made the sensor or?

mighty ledge
#

It’s the end of the dataset

#

Start is the start of the dataset