#templates-archived

1 messages Β· Page 95 of 1

muted berry
#

Gawddamn, success

#

Atom

inner mesa
#

that might be okay, as long as it's using 2-space tabs. VSCode is nice in that it shows you indentation levels by color and you can tab and shift-tab to adjust

muted berry
#

I'll have to look into that

inner mesa
#

anyway, you're good to go?

muted berry
#

I'll try it in the morning, the config check checks out

#

If this works, I def owe you a beer

#

Ive been scratching my head for the past 3 days with this shit

inner mesa
#

if you're going bed, I'm going to assume that we're geographically separated

muted berry
#

Sweden

inner mesa
#

yeah, San Diego

muted berry
#

ah

inner mesa
#

ok, hopefully it works. once you have some good working examples, the rest become easier

muted berry
#

Well..I'll PM in the morning. I ain't forgetting that beer πŸ™‚

inner mesa
#

and be wary of copying somebody else's stuff, especially when it seems like they don't know what they're doing

muted berry
#

It's more that I wasn't sure what I was doing

#

lol

inner mesa
#

a little from column a, a little from column b

muted berry
#

yeah..

#

welp..tried it..no bueno

#

current temp is 22.5

#

it sets the fan at 3

#

but it should be at 2

inner mesa
#

you can debug the template in devtools ->Template

muted berry
#

hmm...template returns 3..?

#

the heck..?

#

am I missing something?

inner mesa
#

it's probably still rounding

muted berry
#

if I use this

#
  • data_template:
    entity_id: climate.huvudvaningen
    fan_mode: >-
    {% set temp1 = states('sensor.temperature_5')|float %}
    {% if temp1 > 22 %} 2
    {% elif temp1 > 23 %} 3
    {% elif temp1 > 24 %} 4
    {% else %} 4
    {% endif %}
    service: climate.set_fan_mode
#

It sets it correctly

inner mesa
#

that's not a useful template, though

muted berry
#

not at all

#

Argh..I'll go at it tomorrow again

#

might pm

#

sigh

#

hmm..

#

changed the values around from rising to falling

#

works as well

#

oh, nevermind

inner mesa
#

I think you just need to set the precision via round(), or via format(). there are some good references on the web

muted berry
#

too late..can't think.. I'll look into it tomorrow

inner mesa
#

this one, for example:

#
{{ "$%.2f"|format(value|float) }}
#

where value is replaced with states('sensor.temperature_5')

#

if that doesn't help, I recommend more Googling

muted berry
#

{% set temp1 = "%.2c"|format(states('sensor.temperature_5')|float %}?

inner mesa
#

you're missing a paren

#

after float

#

I've never used that construct before, but it's typical in a Google search

muted berry
#

yeah, I'll check tomorrow. Thank for all your help so far bro

inner mesa
#

or this:

#

{{ "${:.2f}".format(value|float) }}

#

sure, no problem

#

also, you put %.2c instead of %.2f

#

"f" is for "float"

#

not Fahrenheit, if that what you were going for

muted berry
#

Mernin'

#

So, I did a test..

#

Just to see if it's actually the float value that messes things up and it seems to be the case

arctic sorrel
#

Works fine for me

muted berry
#

which does? mine or floats?

arctic sorrel
#

The original of yours

muted berry
#

do your temp sensors report with or without decimals?

arctic sorrel
#

With, but that doesn't matter here

#
        {% set temp1 = 23.4|float %}
        {% if temp1 < 22.0 %} 2
        {% elif temp1 < 23.0 %} 3
        {% elif temp1 < 24.0 %} 4
        {% else %} 2
        {% endif %}
``` returns 4
#

Change 23.4 to another value and it updates accordingly

muted berry
#

hmm...

little gale
#

What would a value template look like in order to extract bytes from a command line sensor that provides the following data:
{"count":39,"bytes":166760163267}

muted berry
#

and if I do this

#

{% set temp1 = 22.2|float %}
{% if temp1 < 22 %} 2
{% elif temp1 < 23 %} 3
{% elif temp1 < 24 %} 4
{% else %} 2
{% endif %}

#

it returns 3

jagged obsidian
#

@little gale {{ value_json.bytes }} should be enough

muted berry
#

heck, if I put 23, it returns 4..

little gale
#

thanks

jagged obsidian
#

as it should

#

#maths

muted berry
#

I ment 22*

#

and 3

arctic sorrel
#

Also expected

#

22 isn't less than 22 after all

little gale
#

do I need to create a template sensor if I wish to convert the value of bytes to GB?

arctic sorrel
#

Yes

muted berry
#

uh.." {% set temp1 = 22|float %}
{% if temp1 < 21 %} 2
{% elif temp1 < 22 %} 3
{% elif temp1 < 23 %} 4
{% else %} 2
{% endif %}"

#

returns 4

arctic sorrel
muted berry
#

fuck am I actually this stupid? πŸ˜„

#

lol

arctic sorrel
#

Yes, yes you are

jagged obsidian
#

have you ignored a few grades in math?

arctic sorrel
#

Are you actually looking for less than or equal to?

#

<=

jagged obsidian
#

maybe you're looking for the following construct temp1 <=22

#

if something is < it means less than, so it can't be equal at the same time as being less than

muted berry
#

basically between 22-23 = 2

#

between 23-24 = 3

#

and above 24 = 4

jagged obsidian
#

between it is

arctic sorrel
#

Then <= for less than or equal to

jagged obsidian
#

between means not including 23 and 24

arctic sorrel
#

Also, the logic of what you said doesn't cater for is 24

#
        {% if temp1 <= 23.0 %} 2
        {% elif temp1 <= 24.0 %} 3
        {% else %} 4
        {% endif %}
```That matches what you've been saying better than what you're using just now,
little gale
#

Can values be defined in the template editor?

arctic sorrel
#

Yes

#
        {% set temp1 = 23.4|float %}
muted berry
#

then basically this should work as I want it to

#

{% set temp1 = 22|float %}
{% if temp1 < 23 %} 2
{% elif temp1 < 24 %} 3
{% else %} 4
{% endif %}

#

anything below 23 = 2

#

anything below 24 = 3

#

and anything else 4

muted berry
#

oh, didn't read, sorry

arctic sorrel
#

Depends on whether you want 23 and below, or below 23

#

You've been saying one thing, and doing the other

muted berry
#

no, below 23, so once I hit 23, it should switch to a higher fan speed

#

so <

#

and not <=

arctic sorrel
#

Yes, but that's what you've had and been confused about

muted berry
#

To say the least.. I wasn't actually understanding what < was doing

#

amongst other things....so I've learned a lot from this

arctic sorrel
#

This, I'm afraid, is basic maths - if you're going to be playing with more templates it might not hurt to refresh yourself on that

muted berry
#

And I hate math...also sucked at it (as can be seen)

final mulch
#

Hi together
I've just a short question. I know .. I can solve this with a template sensor as well but may there is an easier way to do that.

I have this line at the moment:
{% set h, t = states('sensor.shelly_shht_1_123456_humidity') | float, states('sensor.shelly_shht_1_123456_temperature') %}

Now I've a new entity which delivers humidity and temperature as attribute (not state).
How can I rewrite this to directly use the attributes of the new entity weather.location?

#

If I understand it right, it should be something like this
{% set h, t = state_attr('weather.location', 'humidity') | float, state_attr('weather.location', 'temperature') %}

hot coral
#

is there a way to skip updating/refreshing a binary sensor if a condition isn't met? or is it always either true / false?

i have data coming from a serial port which looks like this: https://paste.ubuntu.com/p/9DqfzvWQ32/

and my binary_sensor templates are set up like shown in the above paste.

basically, if i have an active alarm (let's say smoke, for this example), and another alarm (battery) comes in, the smoke sensor will evaluate as false even though it could still be active because state_attr('sensor.kidde_serial', 'command') != "smoke")

#

maybe some kind of 'if' which returns old_state if command != smoke?

hot coral
#

got it actually i think:

kidde_battery:
  friendly_name: kidde battery
  value_template: >-
    {% if state_attr('sensor.kidde_serial', 'command') == "battery" %}
      {{ state_attr('sensor.kidde_serial', 'active') }}
    {% else %}
      {{ state('binary_sensor.kidde_battery') }}
    {% endif %}
harsh tiger
#

hey folks, strptime stopped working for me....it outcomes with a string, not with a time value, as I can't do anything else with it, anyone else got some problems?

#

{{ as_timestamp(now()) }} works

#

{{ as_timestam(strptime("17-03-1993","$d-$m-$Y")) }} results None

arctic sorrel
#

πŸ€”

#

That's correct

#

Scroll down to strptime and then click the format link

harsh tiger
#

damn change $ and %...will try now

#

there I go....and now I know why it stopped working...made not enought backup from my templateeditor and lost everything before using this formation and did a reconstruct from brain...

#

wastet 2h with this 😦

#

thank you very much....once again

fallen tulip
#

Hi

#

Got a question for the action part of an antomation

#

Can i do that ?

arctic sorrel
#
action:
    - service: cover.set_cover_position
      data_template:
        entity_id: cover.potager_electrovanne
        position: "{{ states('input_number.valve_1_duration') }}"```
fallen tulip
#

thanks :

#

Yes it's logical

#

thanks πŸ™‚

#

not working 😦

#

The value is well templated

#

but.... not taken into account 😦

#

seems is not possible to template with position

arctic sorrel
#

What's the error in the log?

fallen tulip
#

noting

#

I found something in communauty

#

β€˜{{ states.input_slider.cover_position.state | int }}’

arctic sorrel
#

Yeah, don't use the states...state format

#
β€˜{{ states('input_slider.cover_position') | int }}’
fallen tulip
#

ok

#

still not working 😦

#

in direct it's working

#

position: 50 for example

#

the templating gives me 50 too

silent barnBOT
#

If you're having problems with your updates to your configuration:

  • Check the troubleshooting steps
  • Check your log file - remembering you may need to set logger to info or debug
  • Explain what the problem you're having is - sharing configuration, errors, and logs
fallen tulip
#

It's my fault πŸ™‚

#

I forgot "data_template:"

#

πŸ™‚

#

Works like a charm πŸ™‚ thanks

queen flicker
#

Howdy! I want to be able to detect guests via their presence on my wifi. I have a Unifi gateway, so I can see via the attributes what network a device is connected to. The question: is it possible to make a template for a binary sensor which will return true if ANY device_tracker has an essid of Guest and false if none do?

scenic mica
#

Hey guys ... how can I retrieve only the first 5 characters of an input_select?

hollow bramble
#

"{{ states('input_select.dvdo_switch')[0:5] }}"

scenic mica
#

@hollow bramble thank you πŸ™‚

ivory delta
#

World's quickest answer πŸ˜‰

#

It's almost like he saw it coming.

scenic mica
#

damn you guys are good!! lol

ivory delta
#

You were asking the right person and your question was clear. It was just in the wrong place πŸ™‚ Better to keep it here so other people can search for answers in the future.

scenic mica
#

yeah I understand ... thanks very much for the help!

hollow bramble
#

the fact that you already had the template setup made it pretty trivial

#

I think just [:5] would also work

scenic mica
#

I'm very new to Home Assistant ... I'm still copying/pasting from the forum, etc. I wasn't even sure that was called a template

hollow bramble
#

remember to always test templates in the templates dev tool

scenic mica
#

Also good to know, thanks! I have lots of learning to do....

#

Trying to learn MQTT, Node-RED, and Home Assistant at the same time πŸ™‚

#

Template works... thanks again guys!

hollow bramble
#

Come to #node-red-archived if you get stuck on something. That's also one of my areas of semi-expertise

scenic mica
#

Awesome ... I found a bug in the node-red-node-serialport but dceejay fixed it right away. Seems like an awesome group of people like you guys πŸ™‚

hollow bramble
#

There's generally not much gatekeeping in home automation. We're all just trying to make things work

#

Unless you mention the system on which you are running your home automation services. Then you're likely to get a 🀒 from @wise arrow

arctic sorrel
#

Only if it's not HP πŸ˜›

scenic mica
#

SuperMicro motherboard with dual Intel Xeon E5-2643 v2

ivory delta
#

Nah. We've got people running this on everything from a Pi to an entire server farm. It's all good.

arctic sorrel
#

Some even run on Pi Zeros

#

Poor sods

scenic mica
#

lol

harsh tiger
#

Hey Mates, i have 4 arrays I set in a sensortemplate. Is there a way to set them globaly as I need them in a few templates. To be clear its a translationarray for days and months names.

arctic sorrel
#

Store them in an input_text?

harsh tiger
#

Really???

#

Sounds strange but I'll search for it.

ivory delta
#

The input_x helpers are awesome. Learn them all.

harsh tiger
#

Doing my very best. Checked out how to split my config right now....will do so now and then i hope that the magic begins soon

#

Thanks for your help you both

scenic mica
#

@hollow bramble @ivory delta the template you helped me create is working great, but the opposite direction isn't working

#

my input_select has options such as "HDMI1 (MiSTer)" and "HDMI2 (OSSC)"

#

you helped me create the template to only send [0:5] to MQTT so it only sends "HDMI1" or "HDMI2", etc.

#

However, how can I read the value from MQTT and select the correct option? a different system changes input and publishes "HDMI1" but I need my input select to select "HDMI1 (MiSTer)"

ivory delta
#

For that, you'll need a different template πŸ˜‰ That one's going to be messy.

scenic mica
#

Yeah, I thought so ... a bunch of if statements?

ivory delta
#

Yup

scenic mica
#

ok, thanks a bunch

gaunt peak
#

Ok really basic question about templating. I'm working on an animation and I figure I'd have a much easier time if I understood templates a little better. I'm working with Input Numbers so I'm reading the docs but how do I put the info under SERVICES into a template to test it?
https://www.home-assistant.io/integrations/input_number/

#

oop, nevermind I just found the services tab

dreamy sinew
#

Note that the services tab doesn't support templates

peak haven
#

Hi Guys, is there a way i can show the total power usage of the 24h from yesterday? I do have the current usage but would like to keep an eye on daily usage too

arctic sorrel
lunar osprey
#

Hello

#

is it possible to display a state-label with a text that is made with a template?

arctic sorrel
#

Not with any stock card. Some custom cards may be able to

peak haven
#

Thankyou, i will take a look at utility_meter!

harsh tiger
#

Once again I#m not sure if I'm doing the "right" thing. I have a entity from an custom component (ICS, reading a calendar showing my waste plan) which is configured via integrations (not config.yaml). I have a template reading the next occurence of the event and converting the date in a german readable date. This results in another entity. Can I "extend" the given entity with templates?

arctic sorrel
#

Extend, no

harsh tiger
#

check....then I have to stick at 2 Sensors πŸ™‚ Thanks once again saving me hours in search and try and fail πŸ™‚

#

Am I right that my "new" Entity replaces the other one? I used a glance card and I can't chose different sensors for one Icon...phaaa...I dunno how to explan it better, sorry

arctic sorrel
#

No, you can't "replace" entities

harsh tiger
#

Sorry...I meant that I have 2 entities and need too use one of them.

#

My brain is a lil stuck right now... sorry

thorny snow
#

Is it possible for a rest sensor to attach the complete response as sensor attributes?
I use a value_template to extract the expected value for the sensor.
But I need also the complete response to be able to use it with further templates

west spoke
#

hi all, I have a script which calls some services, each one using 'data_template'. is it possible to use a variable, but assign it a default value at the top of the script?

#

i mean, use the variable in each 'data_template', using the single variable declaration/assignment

charred dagger
#

Not really. But I've seen workarounds where you store the variable as an attribute to an entity using customize and use state_attr to recall it in templates...

west spoke
#

oh, thanks @charred dagger - do you have any links/examples you could share please?

#

for clarity - my use case is increasing the brightness of a bunch of lights, using some 'step' value

buoyant pine
#

You could use an input_number for that

charred dagger
#

I actually found an old overly complicated package I made which uses this

west spoke
#

@buoyant pine @charred dagger using an input_number is exactly what I was just trying πŸ™‚

#

it works well; I wasn't familiar with the syntax but a bit of messing around and conversion to int and all good

#

one example :

- service: light.turn_on
  entity_id: light.floor_light
  data_template:
    brightness: >
      {% if is_state('light.floor_light', 'on') %}
      {{states.light.floor_light.attributes.brightness + 10}}
      {% else %}
      {{ states.input_number.brightness_step.state | int }}
      {% endif %}
#

bonus in that I can modify the step value via the ui

buoyant pine
#

Oh, there's a brightness_step and brightness_step_pct service data option for light.turn_on

#

Oh nvm I see what you're doing here, that wouldn't apply

arctic sorrel
west spoke
#

thanks @arctic sorrel

#

hi all. I'd like to have a script that will cycle through some states each time it is called. is this do-able?

I'm thinking the last value could be stored in a helper. But to do the cycling I'd possibly need an array-like variable (or a long if/elseif/else statement πŸ™‚ )

silent barnBOT
arctic sorrel
#

You could use one of those, for instance

west spoke
#

Oh, nice! Thanks @arctic sorrel - let me have a read through that

west spoke
#

worked a charm, thanks @arctic sorrel !

restive flume
#

I haven't done this for far too long... where am I going wrong with this?

#
{% macro humidex(T, H) %}
{% set t = 7.5*T/(237.7+T) %}
{% set et = 10**t %}
{% set e= 6.112 * et * (H/100) %}
{% set humidex = T+(5/9)*(e-10) %}
{% if humidex < T %}
{% set humidex = T %}
{% endif %}
{{humidex}}
{% endmacro %}
{{ humidex(states('sensor.family_room_temperature'),states('sensor.family_room_humidity')) }}
arctic sorrel
#

I'd say you're forgetting that states and attributes are strings

restive flume
#

oh.. yes I am

arctic sorrel
#
{{ (states('sensor.family_room_temperature'),states('sensor.family_room_humidity')) }}
``` should make that pretty clear
restive flume
#
{% macro humidex(T, H) %}
{% set t = 7.5*T/(237.7+T) %}
{% set et = 10**t %}
{% set e= 6.112 * et * (H/100) %}
{% set humidex = T+(5/9)*(e-10) %}
{% if humidex < T %}
{% set humidex = T %}
{% endif %}
{{ '%0.1f' % humidex }}
{% endmacro %}
{{ humidex(states('sensor.family_room_temperature')|float, states('sensor.family_room_humidity')|float) }}
#

there we go.. much better

#

hmm.. it would be nice if you could jump to customize from the settings on an entity.. I find myself wanting to do that pretty often

jagged obsidian
#

New Tab is a feature in most browsers

restive flume
#

it won't jump there.. you still have to navigate through multiple menus

#

it's not possible to customise a template sensor? I can't find it in the list

#

it's probably just the integration...

worn nova
#

How would I change the below to show the friendly state?

data:
  message: '{{ states(''alarm_control_panel.area_1'')|title }}'
  title: House Alarm
service: notify.all_devices
ivory delta
#

First of all, format your posts

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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

ivory delta
#

Make sure to include the proper indentation. What you've posted won't work, for several reasons.

worn nova
#

Make sure to include the proper indentation. What you've posted won't work, for several reasons.
@ivory delta I have edited my post, it does work but and shows the state, id just like it to show the friendly state instead

chrome temple
#

@worn nova what exactly do you mean by "friendly state"? Do you mean what's shown in the frontend? If so, I don't think that information is available there, since that's a, well, frontend thing.

coarse tiger
#

i have a power meter which sums up consumptions from different devices in a template.
the resulting value fluctuates a lot, how can I make an average out of that for the past x minutes?

narrow ginkgo
#

@coarse tiger use the statistics sensor

silent barnBOT
worn nova
#

@chrome temple yes, I want the notification to show "Armed" or "Armed Away" currently it shows "Armed_away" or is that not possible?

inner mesa
#

Depends on what’s displaying it. Any custom card that supports templating can do that. Or you could create a template sensor

#

The latter is the traditional way to report a different state name

chrome temple
#

@worn nova how about message: "{{ states('alarm_control_panel.area_1')|replace('_', ' ')|title }}"

coarse tiger
ivory delta
#

Probably because there's been no stats in the last two minutes. You have max_age set to 2 minutes.

coarse tiger
#

oh, i mixed the meaning of max_age and sampling_size up, thx

granite steppe
#

I've created a switch template for the unifi add-on controller. Aiming to expose this to HomeKit so i can ask Siri (via homepod) to turn it on / off when necessary. It works turning it on but anyone know what i do for the value_template so it can report its state correctly?

thorny snow
#

hi. have a problem with a binarysensor template who never change states...

- platform: template
  sensors:
    coffeemaschine_usage:
      value_template: "{{ states('sensor.coffeplug_power') | float > 200 }}"
      delay_on: '00:00:30'

plan is: if sensor.coffeeplug_power is higher as 200Watt for more than 30Sec turn coffeemaschine_usage to on. but never happens... whats wrong?

coarse tiger
#

you cannot use a template for that, you need a automation with that value_template @thorny snow

thorny snow
#

i use similar with 2 phonechargerplugs - works perfect. what i really wanna do is to prevent my coffeemaschine for beeing turned of (by automation) while its pooring coffee. if its pooring it needs more than 200W and longer than 30secs. i solved it by this template + an automation. is there a better way to solf this problem?

#

if its not pooring it may happen that it reheat - so more than 200W but most of the time not longer as 10secs.

#

therefor my thinking: if > 200W > 30sec =pooring - dont turn of

tidal heart
#

Did this channel just got removed? For some reason when I'm in it it shows up under "Support" but as soon I'm clicking out out of it it get's removed from the list ponder

arctic sorrel
#

No

#

You've found a not-very-hidden feature of Discord

#

v SUPPORT is the Support section being "open"
> SUPPORT is it collapsed - so that channels without unread messages don't show

#

Also, if it was removed... how would you be able to post here πŸ€”

tidal heart
#

TIL! Never noticed that before

arctic sorrel
#

Nobody does, until they find channels missing and panic... 🀣

inner mesa
#

It’s a great feature

tidal heart
#

It is, if you know about it hehe

ivory delta
#

Even better... you can mute channels too πŸ˜‰

inner mesa
#

But then you have to actually hide them. It’s two steps for something that should be one

tidal heart
#

Okay, with that sorted I'm struggling with figuring out how to use nested attributes in a template. So I got this https://hastebin.com/qeqaluyiho.coffeescript and want to be able to pick from the last_checkpoint "layer". I've managed to get the first layer with the likes of {{ state_attr('sensor.aftership', 'trackings',)[1].name }} but the that second layer?

arctic sorrel
#
{{ state_attr('sensor.aftership', 'trackings')[1].last_checkpoint.location }}
tidal heart
#

Thanks a bunch!

#

Now I see what I did wrong... was trying to do this {{ state_attr('sensor.aftership', 'trackings')[1].last_checkpoint.[1].location }} πŸ€¦β€β™‚οΈ

buoyant pine
#

@ivory delta even even better, you can hide muted channels

bleak cipher
#

What would a value template look like if I wanted to have a value displayed in minutes if it is under one hour, and if it is over one hour, have it be displayed as something like 1 hour, 12 min? I don't think relative_time will work; the HA docs say that will only return the largest unit. TIA, pls @ me

stone lintel
#

Does anyone know what the attribute would be for a template sensor showing what the current weather is? I.e sunny, cloudy etc so that I can use in a template sensor? This is using the Met.no weather integration

inner mesa
#

it's the state for my weather.home entity

#

currently 'partlycloudy'

#

can confirm

#

Just look at devtools ->States

stone lintel
#

Thanks!

thorny snow
#

hello, surely obvious but i couldn't find answer, how could i set horizontal-stack to take the entire screen ? within lovelace-ui (dynamique mode) i tried to add sytle : width: 100% with no effect my horizontal-stack still stay as a element like the other one - thanks

buoyant pine
rigid coral
#

Needing some guidance. Using the restful I am trying to pull into a sensor the price from the following.

silent barnBOT
rigid coral
#

Nevermind

buoyant pine
#

...as in you figured it out?

rigid coral
#

yes

#

Its sad but i game I play has some open api links. So i created a few home automations to give me updates when im away

buoyant pine
#

Hey, you do you

#

Also keep an eye on the line limit in the future

rigid coral
#

yea my mistake

merry ravine
#

can someone help me with a template, i want it to return true if the time of day is between 545a and 615a

dreamy sinew
#

Need to create a time sensor and compare against it

merry ravine
#

can you elaborate? i have another template that compares time without a time sensor, but i dont care about the minutes so its an easy comparison {{ now().hour < 23 and now().hour > 12 }}

dreamy sinew
#

That won't work because it will never update

merry ravine
#

it does work :/

#

guess cuz i'm using the built in time sensor?

#

entity_id: sensor.time

dreamy sinew
#

If you are using that sensor you are fine

merry ravine
#

i just thought there might be an easier way to do what i was wanting than checking that the ((hour = 5 and min >= 45) or (hour = 6 and min <= 15))

dreamy sinew
#

{{ '05:45' < states('sensor.time').strftime('whatever it is) < '06:15' }}

#

Something like that

#

Or you could use now().strftime()

merry ravine
#

what is 'whatever it is'?

#

format string?

dreamy sinew
merry ravine
#

yea, sorry, new to python and jinja...thanks..i think this does it..testing now with ```{{ '00:45' < now().strftime('%H:%M') < '00:46' }}

dreamy sinew
#

That will get it for between those times. Might want to do <= etc

#

Depending on what you want

merry ravine
#

yea

#

thanks, that is much cleaner and easier to read

hollow river
#

Hey guys
I'm a bit stuck
I'm trying to make my own input_datetime changer using custom button cards
I'm struggling to get the statement correct for input_datetime to accept it
Error I'm getting: Invalid time specified: 12:"{{14}}":00 for dictionary value @ data['time']
I'm just starting at the basics to get input_datetime to accept the template before I carry on as the problem is I'm not giving it in the right format

hollow river
#

Examples of what I have tried:
time: '10:11:00' works
time: "{{00}}:00:00" doesn't work
time: '1:1:1' works

       {{ now().timestamp() | timestamp_custom("%H:%M:%S", true) }}```  example from https://www.home-assistant.io/integrations/input_datetime/ doesn't work
`time: "{{ now().strftime('%H:%M:%S') }}"` from the page above also doesn't work
ivory delta
#

You're using button-card?

arctic sorrel
#

Cards generally don't support templates

hollow river
#

yes custom button card

ivory delta
#

It's not HA templates, so you're probably better off asking for help in #frontend-archived since it's specific to a card.

hollow river
#

I actually used the JS to determine the name for the card😡 πŸ’©
Thanks mono
will try with JS

hollow river
mighty ledge
#

@hollow river you can make that generic so it works with any input datetime.

hollow river
#

Should I just make the input_datetime a variable?
Or did I miss something on how to use entity in the button card?
Thanks for taking a look @mighty ledge

fierce hornet
#

I'm trying to use a template within the data of a service call but cant seem to get it working. Would someone be able to help me?

#

I'm using Assistant Relay to send messages from HA to my google home speakers. But I want to include the state of a specific sensor. When using developer tools I can add command: This line will be broadcasted to google home speakers as service data to the service that broadcasts. How can I template in this?

#

Nevermind... Just had to use data_template: instead of data: πŸ€¦β€β™‚οΈ

mighty ledge
#

@hollow river the the entity gets passed through the entity field. So inside js all you need to use is entity.state to get the state

hollow river
quiet kite
#

hey, any one can help me? I need to print value_json.20

{% set value_json = '{"20":true,"21":"colour","26":0}'|from_json
%}

stringified object: {{ value_json.20 }}
#

this give me:

Imitate available variables:


stringified object: 
hollow bramble
#

value_json['20']

quiet kite
#

thanks πŸ˜‰

#

My device is ON when mqtt send: 20: true

jagged obsidian
#

your state_template is wrong

#

move what you have in value_template into state_template

quiet kite
#

i try this, but without any changes

#

HA after turn on device, stil thinks that is turn off.

jagged obsidian
#

then your statement doesn't match the mqtt payload

quiet kite
#

should match:

2020-06-22 23:26:14 DEBUG (MainThread) [homeassistant.components.mqtt] Transmitting message on tuya/ver3.3/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/command: { "multiple": true, "data": { 
  "20": true,
  "21": "colour",
  "26": 0} }
2020-06-22 23:26:15 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on tuya/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/dps: b'{"20":true}'
2020-06-22 23:26:15 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on tuya/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/dps: b'{"20":true}'
2020-06-22 23:26:16 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on tuya/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/dps: b'{"101":"QgAAAAGsJgEABwQh"}'
jagged obsidian
#

but you have messages without "20" on the same topic

quiet kite
#

so, you thinks that last message change state to off?

jagged obsidian
#

i don't think, i know

#

your statement makes it so

quiet kite
#

i change IF to if not value_json['20'] but this still dont help. Do you know better way?

#

{% if not value_json['20'] %}off{% else %}on{% endif %}

jagged obsidian
#

that's just the same statement written differently

#

you need to grab last known state of the device from HA in case the message sent to the watched topic doesn't contain "20"

quiet kite
#

is special option for this?

jagged obsidian
#

special option?

quiet kite
#

optimistic ?

jagged obsidian
#

you're not understanding what is happening with your current statement

#

it says if there is value with key 20 make the device on, if not make it off

quiet kite
#

yes

jagged obsidian
#

so whenever, f.e. "101" is received it makes your device off since 101 != 20

quiet kite
#

no

jagged obsidian
#

ok, good luck then

quiet kite
#

maybe this? {% if '20' in value_json %} ?

hollow bramble
#

@jagged obsidian that's not what the if statement is doing. it's if value_json['20'] equates to true

#

{% if value_json['20'] == true %} would be redundant

jagged obsidian
#

and i said what?

hollow bramble
#

if there is value with key 20 make the device on, if not make it off

jagged obsidian
#

and that is not true why?

hollow bramble
#

Because it's evaluating the value of value_json['20'] not just whether it exists

quiet kite
#

this works:

    state_template: >-
      {% if value_json['20'] is defined %}
        {% if value_json['20'] %}
        on
        {% else %}
        off
        {% endif %}
      {% else %}
        {{ states('mqtt_led_schody_gora') }}
      {% endif %}
jagged obsidian
#

if it doesn't exist it will throw an error in logs anyway

mighty ledge
#

no

hollow bramble
#

it would equate to false

mighty ledge
#

yup

#

@quiet kite that looks good.

#

you can shorten it a bit

jagged obsidian
#

his statement said if value_json has a key "20" make it on, in all other cases make it off

quiet kite
#

but now i dont know how to add control to set color and brightness.. When i add ``` brightness: true
rgb: true

mighty ledge
#
      {% if value_json['20'] is defined %}
        {{ 'on' if value_json['20'] else 'off' }}
      {% else %}
        {{ states('mqtt_led_schody_gora') }}
      {% endif %}
hollow bramble
#

no, that's not what it's doing

jagged obsidian
#

for template schema you need to define brightness value and rgb value

#

the true flags are for json schema

quiet kite
#

@mighty ledge: is possible to change string "mqtt_led_schody_gora" for any variable with current name?

hollow bramble
#

if value_json['20'] is equal to false then if value_json['20'] would return false

mighty ledge
#

@quiet kite I don't follow the question

#

@jagged obsidian it's not python and it's not json.

#

it's a dictionary in jinja

#

and jinja's rules for existence are different.

jagged obsidian
#

i'm explaining to wmp that he's looking at wrong mqtt.light setup pertaining to the config he posted first

quiet kite
#

how can i get brightness state from HA memory, when mqtt dont send me current?

mighty ledge
#

pull it from the state machine state_attr('xxx.xxx', 'brightness')

quiet kite
#

thanks

mighty ledge
#

if the light is off, that attribute may not exist

quiet kite
#

when i add brightness support, i have problem with state...

2020-06-22 23:49:06 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on tuya/bf24dd734a72585e44yw96/cf6b639ab2ef6a3b/192.168.123.54/dps: b'{"22":255}'
2020-06-22 23:49:06 WARNING (MainThread) [homeassistant.components.mqtt.light.schema_template] Invalid state value received
mighty ledge
#

lol, just noticed {{ states('mqtt_led_schody_gora') }} you don't have a full entity_id here.

#

needs to be domain.object_id

#

so, if thats a light, i would expect the entity_id to be light.mqtt_led_schody_gora

quiet kite
#

ahhh, thanks!

#

this is my first device

#

my LED controller set RGBW as: 00b7035c0064, i thinks this is R: 00b7 G: 035c B: 0064. This can be true?

jagged obsidian
#

make it so its red only to 100% and then repeate for G, B and W and you'll know

quiet kite
#

true

#

how can i split this json value: "24": "00b7035c0064" to 4 bits?

jagged obsidian
#

here's my experience with tuya led color: 14 char value in hex (can define only RGB and send HSV value as max: RRGGBBffff6464)

#

but that's RGB only

quiet kite
#

so i have: RRGGBBWWCWHV

#

and i have connected RGBWW led

jagged obsidian
#

here's how i dealt with it {{ (value_json['TuyaReceived'].Type3Data[0:2]|int(base=16),value_json['TuyaReceived'].Type3Data[2:4]|int(base=16),value_json['TuyaReceived'].Type3Data[4:6]|int(base=16)) | join(',')}}

#

change ['TuyaReceived'].Type3Data to your key

quiet kite
#

thanks

#

ok, i must fix set color... thanks for all, bye!

wraith shell
#

Hi guys, need advice, I'm trying to set a random range in the attribute 'zones' from the lifx.set_state servive. Documentation says it should look something like '[12,13,14,15]'. Tried this template and won't work even though under dev tools it prints it ok

#

zones: > {% set t = range(3,20)|random%}
{% set y = range(0,49)|random%}
{% set i = range(y,t+y)%}
{% for i in i %}
{%- if loop.first %}
[{{i}},
{%- elif loop.last-%}
{{i}}]
{%- else -%}
{{i}},
{%- endif -%}
{%- endfor -%}

#

sorry, I pasted it wrong: ```

buoyant pine
#

Templates always return a string even if it looks like a list or another data type

wraith shell
#

that explains the 'expected int error' I guess

#

you mean it can't be done?

dreamy sinew
#

I'm not even sure what you're trying to do

wraith shell
#

I want the attribute zones to be random

#

first time I call it [1,2,3,4,5] for example, next time I call the service [30,31,32,33,34,35,36,37,38] for example

dreamy sinew
#

{{ range(y,t+y)|list|tojson() }}

buoyant pine
#

Output is still a string though

dreamy sinew
#

But jsonified at least

wraith shell
#

yep, still the 'expected int' error

#

it can't be done then?

buoyant pine
#

You could make it a fixed length list with templates in each of the list items

#
zones:
- {{ }}
- {{ }}
- {{ }}
wraith shell
#

yeah I know but fixes length is something I don't want πŸ™‚

buoyant pine
#

SOL then unfortunately

wraith shell
#

thanks anyways

hexed galleon
#

What's the easiest way using templates to convert last_changed to local TZ?

#

And is it dangerous to self-reference templated sensor? I want to add a attribute to the same sensor where I'd be pulling the last_changed from (for easy AppDaemon access).

mighty ledge
#

@hexed galleon as_timestamp(states.switch.foo.last_changed) | timestamp_local. Also, you can self reference all you want. Just realize that it will be the result prior to the current change. I.e. if a sensor updates and you reference itself, the result is prior to the update.

#

Also, why even do any of this when you can just use appdaemon to do it

hexed galleon
#

Because I can't actually work out how to resolve an iteration to a function call in AD. Probably a pretty simple Python thing, but I'm still new to coding.

#

This is where I got to in AD:

            "Washing Machine": "binary_sensor.washing_machine",
            "Dishwasher": "binary_sensor.dishwasher",
            "Vacuum": "binary_sensor.vacuum"
        }

        for k,e in entityMap.items():
            strTest = f"self.entities.{e}.last_changed"
            self.log(self.convert_utc(strTest).timestamp())```
#

Can't reference e directly inline with self.entities.e.last_changed, so thought I'd try and resolve via string, but that doesn't end up using the actual self object.

mighty ledge
#

you could just get the state state = self.get_state(entity_id=e)

#

and what you have there doesn't really make sense

#

you're formatting a string, then sending the string and having it convert to utc?

#

but the string is the name of the entity and you add self to it. I donno, that's just all over the place

#

Do you understand the difference between a string and a object?

#

Well anyways, I suggest you take a basic python tutorial. Make sure to touch base on Classes, it will describe what self means. But you really need to understand the difference between a string and an object. Without that knowledge, you'll have a bad time. This line here tells me that you don't understand that difference. strTest = f"self.entities.{e}.last_changed"

hexed galleon
#

I do understand, I just wanted to know how to parse the e object so that it could be used inline. And using self.get_state() returns the state, when I need the last_changed, which isn't actually a normal attribute, so couldn't use the attribute= arg for get_state().

mighty ledge
#

E isn’t an object tho, it’s a string

#

And then you’re using format and placing it in another string

hexed galleon
#

Sorry, yes - I tried that way because I couldn't use self.entities.e.last_changed as it wouldn't parse e, instead referencing it.

mighty ledge
#

If you want the full state you need to use attributes=β€˜all’ as an argument for get_state

hexed galleon
#

Ohh, didn't realise that would also return the hidden/system attributes. That is likely the solution then! Thanks.

mighty ledge
#

Also, entities is a dictionary

#

self.entities.get(e)

hexed galleon
#

Oh, well now I feel even dumber. Didn't realise there was a simple get function that I could assign to a variable >_>

mighty ledge
#

That’s why you should take a basic python tutorial

hexed galleon
#

Lots of learning today! Thanks again πŸ™‚

mighty ledge
#

It covers uses of dictionaries, lists, classes

hexed galleon
#

That stuff is AD-specific though, right? I understand dicts/lists. Just didn't realise there was a .get function, and didn't know that AD would return all the attributes (even system ones that are generally harder to find in HA).

mighty ledge
#

Nope, not AD specific

#

.get is on dictionaries

hexed galleon
#

Ohh, great tip then! Will help a lot.

mighty ledge
#

The function call get_state is AD specific

#

Everything under self. is AD specific

#

self is the class you’re inside, and it’s the appdaemon main class

hexed galleon
#

Yeah, worked that out a while ago. Helped with variable scope to understand that.

mighty ledge
#

Right but that doesn’t mean an object under AD has all AD specific methods

#

Er, functions. Python lingo

hexed galleon
#

Yeah, makes sense. Thanks again for all your help. Much clearer now!

hexed galleon
#

Why would the last_changed attribute of a template sensor be reporting the last reboot time of HA? Is it because the device/template referenced in the value is momentarily unavailable at startup?

dreamy sinew
#

Something like that

hexed galleon
#

What about for an input_boolean then? Seems illogical to have that "changed" to the same state it was before restart.

dreamy sinew
#

Because at startup it has no state until it is restored from the db or defaulted via initial:

hexed galleon
#

Rough 😦 So the only real way you can persist a true last_changed would be to write it as a timestamp to an input_number or as a string to a input_text then?

dreamy sinew
#

Something like that

restive flume
#

is it possible to pass an entity to a macro and then have its stage read inside the macro?

mighty ledge
#

@hexed galleon with appdaemon, you can store date times using json and dump it to a file and restore on startup

viscid junco
#

Not sure if this is the right channel or not, but I am wondering if there is a way to assign an area to a light template entitiy?

arctic sorrel
#

No

hollow bramble
#

Areas are currently very limited

viscid junco
#

ok, do we know if there is a plan to add that functionality in the future?

hollow bramble
#

When they were first introduced balloob was saying they were effectively going to replace groups for entity control, allowing control of multiple entities as one without the overhead of tracking states like groups. That was over a year ago, and to my knowledge they haven't changed much since then. They seem to still be directly tied to "devices"

#

I don't know what the plan for them is moving forward, but I wouldn't expect much anytime soon

viscid junco
#

oh ok, I was trying to clean up my HA config... but I can use regular groups instead of areas. thank you for your help.

solemn dirge
#

I'm having trouble getting the brightness_pct of a lamp. brightness seems to work but with brightness_pct I always get 0

#

Any idea why?

dreamy sinew
#

brightness_pct is not an attribute

solemn dirge
#

Oh, that explains a lot. Thanks.

buoyant pine
#

@solemn dirge you could get the brightness_pct equivalent by dividing the brightness by 2.55

autumn inlet
#

Hey All not sure if this the correct area... I am trying to track how long a scene been on for I have three Day night and Evening, an Automation will kick each one off. I wanted to track them via a sensor or something like this. any help would be great

inner mesa
#

scenes don't ever turn "off", so it's not clear what the endpoint would be

#

seems like that's key to solving the problem

autumn inlet
#

Technically mine do πŸ˜‰ ( turn off some lights etc.. ) I was just going to try and track when the house goes from each mod. Maybe I have to achive this in a different way

ivory delta
#

Set an input_datetime at the same time you activate a scene, then use that to determine the time that's passed.

autumn inlet
#

@inner mesa @ivory delta cheers for you input tho πŸ™‚

inner mesa
#

right, and then trigger on whatever your "off" event is, activating a new scene, turning some lights off to modify the "scene", or whatever, and do the math

green wasp
#

Looks like {{states.sensor.fpl_1034853430.attributes.details[0].date}} gets me the first result, which is great, but without having a total of results first, is there a way to get the last value instead of setting a key?

#

ok, so looks like {{states.sensor.fpl_1034853430.attributes.details|last}} will allow me to get the last group

dreamy sinew
#

[-1]

wraith shell
#

Hi guys, I'm having issues with a template, dunno why

#

trying to run a Plex playlist through a template

#
      media_content_id: >
        {% if is_state('input_select.party_scenes_verano', 'Modo Energizing Verano')%}
          {"playlist_name": "Energizing"}
        {% elif is_state('input_select.party_scenes_verano', 'Modo Intense Verano')%}
          {"playlist_name": "Intense"}
        {% elif is_state('input_select.party_scenes_verano', 'Modo Hoguera Verano')%}
          {"playlist_name": "Hoguera"}
        {% elif is_state('input_select.party_scenes_verano', 'Modo Tibet Verano')%}
          {"playlist_name": "Tibetan"}
        {% elif is_state('input_select.party_scenes_verano', 'Modo Lucy Verano')%}
          {"playlist_name": "Lucy"}
        {% elif is_state('input_select.party_scenes_verano', 'Modo Final Fantasy IX Verano')%}
          {"playlist_name": "Final Fantasy IX"}
        {% endif %}
#

gives this error: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

dreamy sinew
#

.share the full thing

silent barnBOT
wraith shell
#

it's a play_media service

#

that's what creating problems

#

I've been able to run that very same service when just calling a single playlist

#

the service yielded the very same error when I single quoted every playlist_name line

#

wow, apparently I solved it by mere luck, I just changed every line with this {{ '{"playlist_name": "Energizing"}' }} istead of this '{"playlist_name": "Energizing"}'

#

thanks anyways

open snow
#
    doors_open_count:
      friendly_name: Doors Open Count
      entity_id: 
        - binary_sensor.door_down_patio
        - binary_sensor.door_up_deck
      value_template: >-
{{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'eq', 'door') | list | count }}
#

just want to confirm something - a template sensor like that written above will always return a string, correct?

arctic sorrel
#

Technically a template always returns a string

open snow
#

but even if I appended " | float" to the end of the value_template, home assistant would not consider the result a number?

#

I'm trying to do math with the result of this value_template and it keeps failing, so I'm trying to confirm that this is the issue

arctic sorrel
#

In your maths, ensure you're filtering the entity state into some form of number

#

You have to do that with any entity state anyway

open snow
#

I'm doing this in node red, so this may be better posted there, but when I try to use the Wait Until node and compare the result of that template sensor to 0, it does not work

arctic sorrel
open snow
#

so using " | float" and having it display as XX.X in the Dev Tools doesn't necessarily mean HA considers it a number, if it comes from a Template Sensor with the following value template, it's still a string that needs to be converted

{{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'eq', 'door') | list | count | float }}
open snow
#

thanks for the help @arctic sorrel. I just made another template sensor dependent on the other but this one returned true/false which let me do a string comparison in node red

little gale
arctic sorrel
#

Upload, download, or ...?

little gale
#

Both

arctic sorrel
#

Both added, both separately, both both?

little gale
#

Whichever you think is optimum

arctic sorrel
#

FFS

little gale
#

Ultimately I want to convert the value to Mb/s

arctic sorrel
#

If you don't even know what you want, why are you asking for help?

#
{{ THING.download.bytes }}
{{ THING.upload.bytes }}
#

Replace THING with the relevant context

little gale
#

didn't get that

#

Is that supposed to be the value template?

arctic sorrel
#

You said I should provide you with whatever I wanted, so I did

#

It's unlikely to be terribly useful

little gale
#

Could you be any less rude?

arctic sorrel
#

Yes

#

I asked what you wanted, and you basically shrugged

#

Why should I help you if you can't be bothered to decide what you want

little gale
#

Alright, I will rephrase. I want the values (bytes) extracted and converted to Mb/s in a single command line sensor

arctic sorrel
#

Do you want one for upload and one for download? Do you want a combined total? What do you want?

little gale
#

The former, but the command should only be run once

arctic sorrel
little gale
#

That does not add the two values?

arctic sorrel
#

It probably needs an |int after the second

dreamy sinew
#

yup, otherwise string math

little gale
#

The values are simply getting added
"{{ ((value_json.download.bytes|float/1048576)|round(1))|int + ((value_json.upload.bytes|float/1048576)|round(1))|int }}"

inner mesa
#

kinda seems like you have everything you need to solve this, though

arctic sorrel
#

You keep posting asking for complete solutions, you've already got all the parts you need to solve these yourselves

little gale
#

Yes I am close but not there, yet

little gale
#

What should a value template look like to extract latency from here?
entity - sensor.speedtest_net_download

upload:
  bandwidth: 11690788
  bytes: 42436536
  elapsed: 3628
ping:
  jitter: 0.735
  latency: 1.957
unit_of_measurement: Mb/s
friendly_name: Speedtest.net Download
icon: 'mdi:speedometer'
ivory delta
little gale
#

I have tried this:
{{ state_attr('sensor.speedtest_download','ping').latency }}

#

This seems to work but should not be used as per docs??
{{ states.sensor.speedtest_net_download.attributes["ping"]["latency"] }}

ivory delta
#

And why does it say it shouldn't be used?

little gale
#
Avoid using states.sensor.temperature.state, instead use states('sensor.temperature'). It is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup).
hollow bramble
#

Did you try {{ state_attr('sensor.speedtest_download','ping')['latency'] }}

little gale
#

Just did, doesn't work

ivory delta
#

That format definitely works. I get a value back for a template in my HA ({{ state_attr('sensor.sonarr_upcoming_media','data')[1].airdate }})

hollow bramble
#

What comes up with just state_attr('sensor.speedtest_download','ping')

ivory delta
#

Quotes πŸ˜„

#

Are you testing this in devtools > Templates?

little gale
#

Yes

#

What comes up with just state_attr('sensor.speedtest_download','ping')
None

ivory delta
#

Then it doesn't have a ping attribute.

hollow bramble
#

Let's play a game

little gale
hollow bramble
#

spot the difference sensor.speedtest_net_download sensor.speedtest_download

ivory delta
#

You mean you can't just make up names?!

hollow bramble
#

You can, but the results won't change

little gale
#

What comes up with just state_attr('sensor.speedtest_download','ping')
Yeah corrected this and it works

#

Thanks for your help @hollow bramble

slate tundra
#

hey guys, how do I take the timestamp from last time a door was open and let's say in last 5 minutes, something like this?

{{ ((as_timestamp(now()) - as_timestamp(states.binary_sensor.lumi_magnet_aq2_door_entrance_on_off.last_changed)) | int < 300) }}
{{ ((as_timestamp(now()) - as_timestamp(states.binary_sensor.lumi_magnet_aq2_door_entrance_on_off.last_updated)) | int < 300) }}
  • the problem is when I restart ha this becomes true for the first 5 minutes, how do I overcome this, I am interested to know if the door was open in last 5, 10 minutes for tracking proposes
silent barnBOT
#

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

simple sage
#

Can this be done?
When I type in "module" and get the result
stat/xxxxx/MODULE = {"Module":{"46":"Shelly 1"}}
I only want to get "Shelly 1" but I am not sure how to do that in the templates

mighty ledge
#

valur_json.Module[β€œ46”]

simple sage
#

what I needing is 46 to be a wildcard so I can write it up like this, so no matter if its 46 or 28, it will just give me the answer "Shelly" or whatever it is

value_template: " + '"' + "{{ value_json['Module'][???] }}

buoyant pine
#

Sounds like the key (46 or 28) really needs to be the value

#

What's the ultimate goal here though?

simple sage
#

I have sensors to give me certain data for each device... I want a sensor to tell me what module is set for that device

buoyant pine
#

Separate template sensors then with petro's suggestion (value_json of course)

simple sage
#

but what if the key is say 50?

buoyant pine
#

Add another template sensor for it? I'm not sure what that number is supposed to represent but if it's some kind of ID for a device, why wouldn't it be static?

simple sage
#

I forgot to mention,, this was the output from a tasmota device... so each different module name has a number and there is a lot of them built in. However I don't have a list of what each number is for each module

#

which is why I was hoping there was some wildcard value so it did not make a difference if it was 25, or 46 or 50. I just want the value regardless of the number

buoyant pine
#

this should work:

{% for val in value_json['Module'].values() %}
{{ val }}
{% endfor %}
#

@simple sage ☝️

simple sage
#

Thanks, giving it a try

#

@buoyant pine
Thanks, that works

versed gyro
#

I am trying to see if my variable 'mode' is equal to any of these values: sleep, chill, away. I wrote this but it doesn't work. What is the proper way to write this?

#

{% if occ == 'occupied' and mode == "sleep" or "chill" or "away" %}

buoyant pine
#
{% if occ == "occupied" and mode in ["sleep", "chill", "away"] %}
versed gyro
#

Thank you!!

stray raptor
#

Does anyone know how to access Event data when templating?

#

in the Dev tools i can see the event being fired when i listen for it, but i'm not sure how to access the data that is returned when the event gets fired.

inner mesa
#

it's in the docs

stray raptor
#

I saw that page before, i'll take another look.

inner mesa
#

when in doubt, read the docs. they're generally excellent

stray raptor
#

I guess i'm just not connecting the dots. I'm trying to get the value of "actionName" when an actionable notification is fired.

inner mesa
#

need more about the event from you, then

#

one of mine:

#
- alias: 'iOS Widget: Arm Alarm Night'
  initial_state: 'true'
  trigger:
  - event_data:
      actionName: Arm Night
    event_type: ios.action_fired
    platform: event
#

the name is whatever name you gave it

stray raptor
#

my event looks like this in the Dev Tools:

silent barnBOT
inner mesa
#

ok, and you have my example

#

mine is old and probably outdated. I don't use it anymore

#

looks like the event_type has chnaged

stray raptor
#

Yes, but i'm not trying to trigger off of it, i'm trying to set a helper's value

#

(I need to pass the value of actionName to a rest_command)

inner mesa
#

you have to start with a trigger

#

and the trigger will be for a particular actionName

#

so I'm not really following

#

how else are you going to pass it to something else?

stray raptor
#

Yes, i'm triggering on the action name, but i also need to pass the action name along to a rest api command in the "Action" section of the automation

inner mesa
#

but you already know what it is

#

you're trying not to type it a second time?

stray raptor
#

right, but i have multiple triggers based on different actions

inner mesa
#

oh, I see

stray raptor
#

so do i need to setup separate automations for each possible actionName?

inner mesa
#

I would assume trigger.event_data.actionName

stray raptor
#

i'd like to just reference the ActionName in the Action sectoin of the automation.

#

ok, cool, i'll give it a shot.

inner mesa
#

I have an example somewhere

stray raptor
#

is there a way i could test that in the "Template" secton of the dev tools?

inner mesa
#
    - platform: event
      event_type: isy994_control
      event_data:
        entity_id: sensor.kit_remote_kit_lights
        control: DFON
  condition: []
  action:
    - data:
        entity_id:
          - switch.kit_overhead_lights_scene
          - light.kitchen_table_light
      service_template: >-
        homeassistant.turn_{{ 'on' if trigger.event.data.control == 'DFON' else 'off' }}
    - service: script.fix_scene_states
stray raptor
#

oo nice.

inner mesa
#

so, just data

#

usually there's an example somewhere in the docs of the integration that's sending the event

stray raptor
#

ok, thanks! i'll give it a shot after dinner. sounds promising.

stray raptor
#

@inner mesa I'm struggleing with using the template like you have in your example. I'm trying to use a template when setting the value of an input_text helper

#

the template doesn't seem to be rendering:

data:
  value: '{{trigger.event.data.actionName}}'
entity_id: input_text.babybuddy_diaper_solid
service: input_text.set_value
inner mesa
#

indent entity_id:, probably

#

and data_template:

dreamy sinew
#

Nope, rule 1 of templating

silent barnBOT
stray raptor
#

πŸ€¦β€β™‚οΈ

#

I was trying to do it via the webUI and totally forgot about the data_template

#

Remembering these simple rules will help save you from many headaches and endless hours of frustration when using automation templates.

inner mesa
#

or, you can just spend that time πŸ™‚

stray raptor
#

and then still need to ask for help!

idle cargo
#

@stray raptor do u use NODE RED?

#

I'm working on something similar with actionable notifications

#

if your notifications are going into android

stray raptor
#

@idle cargo No

#

My notifications are for iOS. I migrated away from NodeRed recently. I felt like it was becoming too difficult to share/backup

idle cargo
#

I just started using node red this week...and seems pretty powerful

#

for this exercise I was able to create actionable notifications in node red and receive the actions as well.

#

I also was able to use node red to call HA Automation... and also receive the actions as well

#

@stray raptor .... not sure maybe this might help

vagrant monolith
#

how can i do a state + state math operation? in template?

arctic sorrel
#
{{ states('thing.one')|float + states('thing.two')|float }}
#

See the templating docs

vagrant monolith
#

Thx!

#

What is problem here?

#

{{ states('sensor.server_1_disk_1_usage')|float * 100 / states('sensor.server_1_disk_1_usage')|float + states('sensor.capacity_disk_1_free')|float }}

#

it should return 20

arctic sorrel
#

BODMAS

#

Aka operator precedence

#

If in doubt, use brackets

vagrant monolith
#

?

arctic sorrel
#

High school maths

#

a + b * c is a + (b * c)

vagrant monolith
#

Ow

arctic sorrel
#

But, if you wanted a+b * c then you needed to write (a + b) * c

vagrant monolith
#

Could you please correct that code?
{{ states('sensor.server_1_disk_1_usage')|float * 100 / states('sensor.server_1_disk_1_usage')|float + states('sensor.capacity_disk_1_free')|float }}

arctic sorrel
#

Not without knowing your intent

royal vortex
#

I'm trying to come up with a template loop that shows me all the entities in the light domain so I can make sure I've got them all named right (I have a lot), but it's not working.

  {{ entity_id | lower }}
{%- endfor %}```
vagrant monolith
#

i have like 400 * 100 / 2000 which wll make me the percentge of usage off totalt

arctic sorrel
#
{{ ( states('sensor.server_1_disk_1_usage')|float ) * 100 / ( states('sensor.server_1_disk_1_usage')|float + states('sensor.capacity_disk_1_free')|float ) }}
``` Maybe
vagrant monolith
#

Thanks!

#

I will look at the code and see what was my problem

arctic sorrel
#

Have a look at the default in devtools -> Templates @royal vortex

{% for state in states.sensor -%}
  {{ state.entity_id | lower }}
{% endfor %}
royal vortex
#

@vagrant monolith why are you multiplying by 100 and dividing by the sum of used + capacity? shouldn't it be (usage/capacity)*100?

#

Have a look at the default in devtools -> Templates @royal vortex

{% for state in states.sensor -%}
  {{ state.entity_id | lower }}
{% endfor %}

@arctic sorrel seeing it stated slightly differently helped.

  {{ state.name | lower }} {{- '\n' -}}
{%- endfor %}```
dreamy sinew
#

If you're using that as a sensor it will never update

hollow river
#

Hey guys
I would like to know how to strip the "," out of 2020-06-28, 22:46 using templates
I want to use it to trigger an automation with input_datetime

buoyant pine
#
{{ states('sensor.whatever').replace(',', '') }}
hollow river
#

ahh
.replace thanks @buoyant pine ! I was trying to use replace as a filter🀒

royal vortex
#
  {{ domain.name | lower }}: {{- '\n' -}}
  {% for entity in states[mydomain] -%}
    {{ entity.entity_id | lower }} {{- '\n' -}}
  {%- endfor %} {{- '\n' -}}
{%- endfor %}```
I'm trying to iterate through each domain and list the entity id of all of the entities within that domain, is there a collection of domains? I can't figure out what it is and it doesn't seem to be listed in any of the docs I've looked through
buoyant pine
#
{% for state in states %}
{{ state.entity_id }}
{% endfor %}
royal vortex
#

Beat me to it!

mighty ledge
#

{{ states | selectattr(β€œdomain”, β€œeq”, β€œlight”) | map(attribute=β€œentity_id”) | list }}

dreamy sinew
#

use the filters luke

buoyant pine
#

Nah jk, I should learn how to make templates like that

fallen sorrel
#

trying to get a template going,.. but failing miserably,.. so I turn for some help and guidance from the noble few,.. Ok so i'm trying to enable a light to be on for set delay times,.. and to be active only 1hr before sunset until 1hr after sunrise,.. but to also change the countdown timer value depending on whether it is evening or night,.. I have cobbled together a template,.. from many different threads,.. ( and although HA is happy to execute it) it does not deliver,... can anyone help,.. and can anyone shed light on the meaning of code differences such as 'duration: >-' or 'duration: >'... the dash being the only difference... rules here:- https://pastebin.ubuntu.com/p/3TQMWCGckd/ many tx guys/gals

inner mesa
#

Not specific to your template, but I recommend using sun elevation rather than sunset/sunrise to simplify and improve the conditions

hollow bramble
#

> removes line breaks, but leaves a trailing break at the end. >- gets rid of the trailing break

fallen sorrel
#

ok,.. tx,.. I'll go for the elevation stuff,.. have tried a variant or two along the way,.. but I will revert back and try some more,... is my timer template good,? or is that missing some refinement,.. ah >, >- I get it now... rather than having one long line,... sort of similar to \ in linux.

fallen sorrel
#

Ok,.. have revamped to a previous incarnation of my automations.yaml with elevation the driver,.. but this is still not working as expected even though it is now dark in the UK,.. πŸ™‚ https://pastebin.ubuntu.com/p/w3KzyzYDVq/ thanks for the pointers help

ivory delta
#

The sun's elevation isn't below -6ΒΊ in most of the UK yet πŸ˜‰

fallen sorrel
#

ahhhh,.. I would not have found that ,... πŸ™‚ so what is a good number for the UK.. say London Now....

ivory delta
#

A good number? I like -90.

#

Surefire way to make sure your automation never triggers πŸ€·β€β™‚οΈ

#

If you don't know what values you want, experiment. If you want to see what the sun's elevation is at your location, check in devtools > States

#

I can't tell you, cos I'm not in London... and basic math says it's gonna vary based on latitude and longitude πŸ˜‰

real flint
ivory delta
#

Well that's great if you're talking about the colour temperature or brightness or bulbs... but when you want a 'night mode' for timers... πŸ€·β€β™‚οΈ

real flint
#

sorry, wasn't thinking.. I have an automation that does something similar. It uses the sunset event and offsets by 15 minutes. That worked well for me but am still thinking of building a lux measurement.

velvet gate
#

wait what are we talking about?

#

I do a decent amount with lights.

#

I use node red though

fallen sorrel
#

@ivory delta,... ah tools=>states,.. perfect,.. now I can see -6 was never going to work,... more like 25,.. as mid-day is at approx. 60degrees...

#

thanks for the pointers

ivory delta
#

Midday is around 60 degrees at some times of the year.

#

Seasons exist because of the Earth's tilt. The sun's elevation varies year round.

#

If you want a more accurate solution, you'll have to take that into account... but elevation is good enough for most purposes.

arctic sorrel
#

at some times of the year, at some latitudes...

ivory delta
#

Well, yeah. I was taking it as a given that diyhouse won't be moving around the globe constantly πŸ˜„

trim leaf
#

Can someone bring some sanity here? Here is a self contained template that sets var, then sets entity based on the value of var, then prints it. It works fine if var is less than < 10, but the moment i get into 2 digit numbers, it breaks.

Practically speaking, var is actually a counter, but its working the same way


{% if var <= '1' %}
{% set entity = 'light.osram_lightify_flex_outdoor_rgbw_2904a300_level_light_color_on_off' %} 
{% endif %}
{% if var >= '6' %}
{% set entity = 'light.kitchen_island_lights' %}
{% endif %}
The entity is: {{ entity }}```
#

so if var is set to 1-9, I get the value entity, the moment I set it to 10 it breaks

hollow bramble
#

You're trying to do math on a string

trim leaf
#

is this because I wrapped the int in single quotes?

hollow bramble
#

wrapping something in quotes makes it a string

trim leaf
#

right, when I remove the quotes the template fails completely though

hollow bramble
#

fails in what way?

trim leaf
#

let me test it again, it is possible I had quotes in portions of the template, and not others.

hollow bramble
#
{% set var = 10 %} 

{% if var <= 1 %}
{% set entity = 'light.osram_lightify_flex_outdoor_rgbw_2904a300_level_light_color_on_off' %} 
{% endif %}
{% if var >= 6 %}
{% set entity = 'light.kitchen_island_lights' %}
{% endif %}
The entity is: {{ entity }}

this renders The entity is: light.kitchen_island_lights

trim leaf
#

yeah im looking at my git history and thats what I did

#

ugh, sorry

#

thanks!

buoyant pine
#

Also why separate if statements

#

Instead of if, elif, else

trim leaf
#

@buoyant pine if we're being honest I didnt realize there was elif in jinja, but clearly I didnt look hard enough

#

soooo thank you lol

#

admittedly new to templating. thank you both!

#

Ah, small update I knew I wasnt totally crazy. Looks like the result of my state call to the counter

states('counter.kitchen_occupancy_counter') was actually returning a string, which is why when I tried to compare it to an int the template failed

Now that I filter the state response into an int states('counter.kitchen_occupancy_counter') | int everything works as expected.

Thanks again!

daring ingot
dreamy sinew
#

try trigger.id

daring ingot
#

@dreamy sinew gives me the same error.

hollow bramble
#

Is it possible whatever "{{.Service.Id}}" is rendering to is breaking the json string?

silent barnBOT
hollow bramble
#

{{trigger.to_state.name}}

#

@daring ingot try just rendering {{trigger.data}}

daring ingot
#

@hollow bramble Same error I'm afraid

silent barnBOT
#

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

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

daring ingot
#

was that for me @arctic sorrel ?

arctic sorrel
#

Not as such...

hollow bramble
#

same error as what? Your other error was json related. You're still getting a json error when you use {{trigger.data}}?

daring ingot
#

@hollow bramble Yes same error as in the link.

hollow bramble
#

try changing the payload to a static json string

daring ingot
#

sorry example?

hollow bramble
#
{
  "id": "id",
  "online": true
}
daring ingot
#

again same JSON error. Just going to reboot HA as previously it was triggering but getting no json output in the persistent message.

#

@hollow bramble and the same error. A reply in the HA forum suggested that the payload wasn't being sent as JSON but looking at Statping it shows the correct content type (application/json) and POST.

#

@hollow bramble thanks for your help, I'll keep testing and trying πŸ™‚

hollow bramble
#

It does seem like it's not posting a json string, but if you don't have access to what it's really sending then it's pretty much impossible to know without introducing something other than HA

daring ingot
#

is there anywhere in HA to intercept the actual payload and display whats been sent/received or another tool that does something similar?

hollow bramble
#

Node red would work

livid pawn
#

Hello all, i have a question about json, mqtt and directing the data to different sensors.. am i in the right place or is there somewhere more appropriate?

arctic sorrel
#

You're possibly in the wrong place, but until you say more we won't know

livid pawn
#

ok, so i have some homemade sensors giving me json messages like this.. ESPNow/key {"temp":"29.00","station":"1"} ESPNow/key {"temp":"29.00","station":"2"}
I can extract the temperature, they are all coming in on the same mqtt topic.. what i am looking for is to find out if there is a way to look at the "temp" and the "station id" and decide to which topic the data should be assigned...

#

so 2 different sensors coming in to the same gateway

arctic sorrel
#

No

livid pawn
#

ok, so just not manageable? i guess i will have to build that in at an earlier stage or preprocess in node-red

#

Well thanks anyway

hasty spindle
dreamy sinew
#

hmm, i don't see anything wrong with that. Only problem would be if you're not getting valid json back from that topic

hasty spindle
#

It works if I publish from node red, but not from the code itself, however, I can hear the code publishing from node red

buoyant cliff
#

hi I'm just wondering if it's possible to make my automations a little more dry with a template and how I'd go about this. I've used a consistent naming convention throughout so for example the entityId for the lights in a room would be light.<room_name> and lamps would be light.<room_name>_lamp(s) and the timer would be timer.<room_name> and finally the motion sensor would be motion.<room_name>. With that in mind my light motion automations are all identical and very repetitive. So I wondered if it would be possible to some how match the motion and timer triggers using a wildcard and extracting the room name to control the time and light entities accordingly

tulip viper
#

hi, so i got the int comparison to work. now the next step i can't figure out is the same for a string

#

train_a1:
value_template: >-
{% if states.sensor.a_to_b.attributes.products = AKN, S %}
off
{% endif %}

arctic sorrel
#

And... quotes πŸ˜‰

#

There's also no else

dreamy sinew
#

eh it would just do off / none πŸ˜›

tulip viper
#

didnt copy it :/ Here is the complete one
{% if states.sensor.a_to_b.attributes.products = AKN, S %}
off
{% else %}
failed
{% endif %}

arctic sorrel
#
          {% if is_state_attr('sensor.a_to_b','products','AKN, S') %}
            off
          {% else %}
            failed
          {% endif %}
#

Didn't copy it...

#

You copied the whole thing then cut parts out... don't do that

tulip viper
#

ok sorry! won't do it again

dreamy sinew
#
value_template: "{{'off' if is_state_attr('sensor.a_to_b','products','AKN, S') else 'failed' }}"
arctic sorrel
#

That is indeed the most compact version

tulip viper
#

If I create a sensor for the products i get ['AKN', 'S']. Seems like they are 2 seperate strings? How can i do this?

#

Or is it possible just to match the AKN string? Something like a products contain AKN = true

tulip viper
#

So with ['BUS'] it is working good when there is only a bus. But when there is a the aforementioned string, then i does not work :/

#

Ok yeah now it's working even though it was the first thing i tried.. super weird. Thanks for your help!! How do i make quotes like you?

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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

tulip viper
#
test
#

Great, thanks!

hasty spindle
ivory delta
#

Same answer as the last time you asked... the payload doesn't have the property value_json

#

'value_json' is undefined means it doesn't exist.

hasty spindle
#

Okay but how do I fix it?

ivory delta
#

First, check what you actually get back in the payload.

#

Second, use something that exists.

#

Where's it coming from? Where's your config?

hasty spindle
ivory delta
#

So you're using MQTT Cover... what's the MQTT payload for that device?

hasty spindle
#

That's my config

#

The MQTT payload is exactly what I declared it in the config

ivory delta
#

No. No, it's not.

#

Listen to that topic (AB_Left_Curtain/state), wait until there's a message, share that message here.

#

devtools > MQTT > Listen to a topic

hasty spindle
#

I am working on coding the curtains from scratch, that's how I can verify the messages

ivory delta
#

I don't care how you made it. Share the message.

hasty spindle
#

Okay

ivory delta
#

Found it?

hasty spindle
#

I had to restart my HA because of a network issue, I'll share it as soon as I can!

#

I keep getting a socket err on the program, I think I'll just retry this tomorrow as I've been getting issues all day, thank you anyways though

odd flare
#

Does a logged error tell me which template is having an issue?

#
Source: helpers/template.py:230
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 3:02:58 PM (2 occurrences)
Last logged: 3:02:58 PM

#

Anyone know where I should look?

dreamy sinew
#

Check the actual log file

edgy dirge
#

with 0.112.0 Update i see MQTT tab missing under developer tools

buoyant pine
hollow bramble
#

not even really a question

arctic sorrel
#

Damn, didn't even notice that had moved there

#

I kind of get why it's there, but it's slightly odd πŸ˜„

hollow bramble
#

yeah... maybe an "integrations" tab on dev tools would have been a little easier of a transition

buoyant pine
#

It has been...quite jarring

buoyant pine
#

That's why I have a server controls panel redirect now (to get to the logs quicker)

hollow bramble
#

using the frontend logs GWspenderSpongeTriggered

buoyant pine
#

And reloads for automations, scripts, etc

hollow bramble
#

jk that's pretty much all I use

#

What did you use to do that again?

buoyant pine
edgy dirge
#

What is wrong with this script

#
  alias: Ring_test
  sequence:
  - data:
      data_template:
        filename: '{{state_attr(''camera.front_door_2'', ''friendly_name'')}}'
        subdir: '{{state_attr(''camera.front_door_2'', ''friendly_name'')}}'
        url: '{{ state_attr(''camera.front_door_2'', ''video_url'') }}'
    service: downloader.download_file```
buoyant pine
#

data_template: doesn't go under data:, it replaces data:

edgy dirge
#

oh what should i do

#

replace data: with data_template: ???

buoyant pine
#

that is what i said πŸ˜›

edgy dirge
#

now i get invalid error for url error

silent barnBOT
fallen sorrel
#

help,.. so I placed/copied a template in the dev. tools template,.. and then triggered it from an Events form and check result,... Humm that does not work for me,.. well more correctly 'I aint doin' right',.. pls help,.. what should I be doing,.. I'm a wally for missing the obvious I assume...

silent barnBOT
arctic sorrel
#

Without seeing what you're doing, and you explaining what you want... 🀷

fallen sorrel
#

Invalid config for [sensor.mqtt]: [time_of_day] is an invalid option for [sensor.mqtt]. Check: sensor.mqtt->time_of_day. (See ?, line ?).
Component error: time_of_day - Integration 'time_of_day' not found.
Component error: entity_id - Integration 'entity_id' not found. Component error: time_of_day - Integration 'time_of_day' not found. Component error: friendly_name - Integration 'friendly_name' not found.
Error loading /config/configuration.yaml: while scanning for the next token found character '%' that cannot start any token in "/config/configuration.yaml", line 89, column 6

#

line 89 is the start of the if statements in my configuration.yaml file....

#

but I was trying the template tester stuff out that has just popped up on the chat here,. so I thourght I'd give that a whizz..

buoyant pine
#

that needs to go under

sensor:
  - platform: template
``` in your config
fallen sorrel
#

sorry guys,.. this is the error message I get from my config.yaml...Invalid config for [sensor.mqtt]: [time_of_day] is an invalid option for [sensor.mqtt]. Check: sensor.mqtt->time_of_day. (See ?, line ?).
Component error: time_of_day - Integration 'time_of_day' not found.
Component error: entity_id - Integration 'entity_id' not found. Component error: time_of_day - Integration 'time_of_day' not found. Component error: friendly_name - Integration 'friendly_name' not found.
Error loading /config/configuration.yaml: while scanning for the next token found character '%' that cannot start any token in "/config/configuration.yaml", line 89, column 6
Invalid config for [sensor.template]: [time_of_day] is an invalid option for [sensor.template]. Check: sensor.template->time_of_day. (See ?, line ?).

#

https://pastebin.ubuntu.com/p/TQpMfCNvsK/ and this is my config.yaml,.. I have tried the code supplied by Tediore,.. and many variations,.. there of,.. trying to get my 2 spaces correct,.. I assumed because I have a 'sensor:' entry already in the file I add extra sub sensor: bits by prefix'ing with a dash '-',.. but apparently not!... where is my formatting failure... many tx for your patience...

carmine fog
#

hello my dearest friends πŸ˜„

buoyant pine
#

@fallen sorrel your indentation is off, check the template sensor docs again

carmine fog
#

I hope someone here may help me πŸ˜„ iam currently building a rest sensor and wanting to query "tomorrow as yyyy-mm-dd"

#

resource_template: http://192.168.5.195:8089/api/mealplancount/{{ now().strftime('%Y-%m-%d') "Idontknow what I shoudl do here because Iam a noob" }}

#

today is no problem works with resource_template: http://192.168.5.195:8089/api/mealplancount/{{ now().strftime('%Y-%m-%d') }}

#

wah discord encodes it πŸ˜„

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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

carmine fog
#

sorry thank you

#

:bot πŸ˜„

dreamy sinew
#

stops that problem

carmine fog
#

ok

tulip viper
#

heyy πŸ™‚ i wanted to add 2 minutes to a timestamp but can't figure it out.. can you help me?

      train_akn:
        value_template: "{{(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')+(120|timestamp_custom('%H:%M', false))) }}"
#

heyy πŸ™‚ i wanted to add 2 minutes to a timestamp but can't figure it out.. can you help me?

      train_akn:
        value_template: "{{(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')+(120|timestamp_custom('%H:%M', false))) }}"
#

The output is somehow departuretime00:02

#

The output is somehow departuretime00:02

arctic sorrel
#

You could convert it to a timestamp (seconds since the epoch) then add 120 seconds, then convert back

carmine fog
#

@arctic sorrel sry to bother, do you maybe also know how I can add one or two days to {{ now().strftime('%Y-%m-%d') }} in resource_template: http://192.168.5.195:8089/api/mealplancount/{{ now().strftime('%Y-%m-%d') }}

arctic sorrel
carmine fog
#

eeek ss πŸ˜„

arctic sorrel
#

As above

#

Convert to timestamp, do maths, convert back

carmine fog
#

ok I'll try ty !

tulip viper
#

i use as_timestamp for the conversion right?

#

so

#
        value_template: "{{(as_timestamp(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure'))) }}"
#

should give me some number right? only getting none..

arctic sorrel
#

as_timestamp requires the right kind of input πŸ˜‰

#

Odds are that your entity isn't providing an actual datetime

tulip viper
#

The output is like 20:44

arctic sorrel
#

Then you can't convert that to a timestamp

#

Add a date

#

You need something like 2016-06-02 20:44:00

tulip viper
#

is the an option to test such commands except in the configuration.yaml?

silent barnBOT
tulip viper
#

Ah way better, thanks!

fleet condor
#

Hi! I'm trying to get the max value a sensor has been. I've been trying through examples on the web but no luck yet. Anyone have a good idea?

arctic sorrel
fleet condor
#

Yeah I have that, then did {{ state_attr('sensor.total_solar_energy_stats', 'max_value') }} so the attribute is the statistics version of the sensor but it seems to output the current state

arctic sorrel
#

The attribute has the correct value?

#

You may also need to play with the max age setting

fleet condor
#

Ah that looks to be it. It doesn't say in the docs, do you know what format the max_age should be?

arctic sorrel
#

time

#

You can specify days, hours, minutes, and seconds

fleet condor
#

alright, thanks!

tulip viper
#

still working on the smae problem with another try. I got 22:34 and want to seperate both and then add the time. Time adding is working good so i get 36 with the code but when i want to add the hour i can't render anymore

#
        value_template: "{{((state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')[0:3])+(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')[3:5]|int+2) )}}"
#

So last part is working good with conversion to int, but now i want to keep first part as a string

#

got it working

warm isle
#

now when I'm finished πŸ˜›

tulip viper
#

ohh sorryyy

#

but you can post anyways

warm isle
#

[0:2]?

tulip viper
#

my solution is not very elegant

#

value_template: "{{((state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')[0:2]|int)|string+":"+(state_attr('sensor.hamburg_horgensweg_to_hamburg_langenfelde','departure')[3:5]|int+2)|string )}}"

warm isle
#

I actually dont know what you try to do

tulip viper
#

i wanted to add 2 to the "mins"

#

but I am too stupid to find an ewasy way

#

easy*

warm isle
#

your issue meight be taht you take the semicolon with

#
Imitate available variables:
{% set my_test_json = {
  "temperature": "22:34",} %}
 {{ (my_test_json.temperature)[0:3] }} 
 {{ (my_test_json.temperature)[3:5] }} 

 {{ (my_test_json.temperature).split(':')[1] }} 
 {{ (my_test_json.temperature).split(':')[1]| int+2 }} 
#

=

#
 22: 
 34 

 34
 36 ```
tulip viper
#

so the split takes everything after the ":" ?

warm isle
#

you set the symbol where you like to cut stuff and pack it in an array
[0],[1],[2].... to get the data out

tulip viper
#

ah okay nice. thank you!

warm isle
#
{% set my_test_json = {
  "temperature": "22:34:i want to:27:50:say hi",} %}
 {{ (my_test_json.temperature).split(':')[2] + " >>:<< " +(my_test_json.temperature).split(':')[5] }} 

i want to >>:<< say hi

#

I need inspiration with this Ikea Tradfri on/off dimmer switch.
I can compfortable turn on / off devices but got my issues templating the brightness_down > brightness_stop messages.
some pointers maybe?

peak flame
#

is there a place other than configuration.yaml to put template sensors? I don't like having to restart home assistant to add one, and you can add scripts etc without doing so

hollow bramble
#

not yet

violet oyster
#

god willing, one day...

dull ledge
#

can anyone help me template out the NWS weather. I'm trying to get just a single forecast from the list.

#

I have {{ state_attr('weather.kelp_daynight', 'forecast') }}

#

But if I try to do {{ state_attr('weather.kelp_daynight', 'forecast')[0] }} It fails

violet oyster
#

{{ states.weather.kelp_daynight.attributes.forecast[0] }}

dull ledge
#

thats not returning anything in the template editor

#

heres an example of the data.

silent barnBOT
dull ledge
violet oyster
#

try {{ states.weather.kelp_daynight.attributes.forecast.detailed_description[0] }}

dull ledge
#

nada

silent barnBOT
#

@dull ledge 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.

dull ledge
#

oh.

violet oyster
#

you must have something wrong in the name or something. i just tried {{ states.weather.home.attributes.forecast[0] }} in my own editor and it worked fine

#

returns {'datetime': datetime.datetime(2020, 7, 4, 12, 0, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>), 'temperature': 82.8, 'condition': 'sunny', 'pressure': 1016.1, 'humidity': 65.7, 'wind_speed': 12.2, 'wind_bearing': 20.5}

dull ledge
#

I have a weather.home entity as well.

#

But still don't get a return out of it.

violet oyster
#

and weather.kelp_daynight is a different entity?

dull ledge
#

yes

#

it is using the National Weather Service Addon

violet oyster
#

idk what is wrong then. should be working based on what you have said

#

try restarting ha i guess?

buoyant pine
#

what version of home assistant are you on? i think there was an issue with dev tools > template in 0.112.0

violet oyster
#

oh yeah

buoyant pine
#

also Barbados, it's good practice to use {{ state_attr('weather.home', 'forecast') }} instead of the method you're using

dull ledge
#

112

buoyant pine
#

same idea with using states() instead

violet oyster
#

ill be honest, i'm too lazy to hold shift for the parentheses

#

but i know you are right lol

buoyant pine
#

lmao

#

@dull ledge your syntax looks fine, the template tool is just acting up and cuts off the first few lines of output

dull ledge
#

so this should be valid then?

buoyant pine
#

yeah

violet oyster
#

im on 112.1 and it is working for me so update and youll be good

dull ledge
#
      tomorrows_forecast:
        friendly_name: "Tomorrows Forecast"
        value_template: "{{ state_attr('weather.kelp_daynight', 'forecast')[3].condition }}" 

buoyant pine
#

and yeah, just update to 0.112.1 (i'm doing it now)

dull ledge
#

mashing that button

buoyant pine
#

SMASH THAT MF UPDATE BUTTON

violet oyster
#

like & subscribe

dull ledge
#

alright. Thanks for the help. Hopefully when it comes back up everything will behave.

buoyant pine
#

this is how i update πŸ˜›

matt@debian-server:~$ update
What Home Assistant version do you want to update to? (Enter x to cancel.)
[1] Stable
[2] Beta
[3] Dev
[4] Custom
1
Update to the newest stable version? (y/n)
y
Ok, updating.
violet oyster
#

do you snapshot beforehand?

dull ledge
#

does that work on the docker supervisord install?

buoyant pine
#

i don't run supervised so i don't have snapshots

violet oyster
#

oooo

buoyant pine
#

that's a bash script i made

dull ledge
#

livingOnTheEdge.gif

buoyant pine
#

i mean, i have automated backups

violet oyster
#

big dick tediore

buoyant pine
#

lmaooooo

#

got that BIG DOCKER ENERGY

violet oyster
#

hahahaha

dull ledge
violet oyster
#

i loled at that

#

im such a pussy, i had an update fail like 2 years ago and ever since i wont even look at the update button without snapshotting

buoyant pine
#

non-supervised is nice though in that it doesn't roll you back if there's a config issue, you can just check the logs, fix the issue, and restart

dull ledge
#

lol. I've been playing with this for 3 weeks

violet oyster
#

wow and you are already templating

#

i was still figuring out what an entity was

buoyant pine
#

look at the big brain on BigD

dull ledge
#

I was trying to build it all with docker-compose. But it was a PITA so I went to an easier install

buoyant pine
#

i just have a separate compose file for everything lol... kind of defeats the point but it works for me

violet oyster
#

ive always used frenck's install script for docker and never had reason to look elsewhere

buoyant pine
#

but it ties in to my update bash script for EZPZ updates

warm isle
#

I need inspiration with this Ikea Tradfri on/off dimmer switch.
I can compfortable turn on / off devices but got my issues templating the brightness_down > brightness_stop messages.
some pointers maybe?

real flint
#

zha, DeCONZ or Ikea Bridge?

warm isle
#

Oh forgotten about the other integrations. The 4th, zigbee2mqtt

ivory delta
#

Don't just say you have issues. Explain what you're trying to do, and share any relevant logs/config.

#

Bad padawan. Bad.

warm isle