#templates-archived

1 messages · Page 142 of 1

inner mesa
#

generating a list of states from the list of entity_ids

#

you're not using my latest one, BTW, which has less repetition

trim leaf
#

oh, didnt notice the edit. one sec

inner mesa
#

just refactored a bit

trim leaf
#

wasn't expecting a change, but still not getting any back from temp_bool

#

when just testing these very specific parts of the template

{% set temp_bool = states.input_boolean|selectattr('object_id', 'in', bools)|map(attribute="state")|list %}
{{ temp_bool }}```
inner mesa
#

You’ve mixed things up

#

Go back and revisit the example

#

Note that you have full entity_id in the first line and you’re checking object_id in the second

trim leaf
#

ahhhhh

#

ok

#

thank you

#

i made a small change to use a sensor entity for all_temps and this is exactly what I need. Just need to play around with last_updated/last_changed to calculate if its been in an on state for 10m

#

much appreciated for the guidance!

trim leaf
#

@inner mesa I think there might be something amiss with the loop logic. no matter which input_boolean I set to on, its always pulling the temp from the first sensor on the list.

It seems like the condition if logic on the for loops might be throwing off the index counter

inner mesa
#

Could be. You can just move the ‘if’ inside the loop

trim leaf
#

just tried, getting odd behavior still. will keep playing!

trim leaf
#

It was both the combo of moving the if into the loop + needing to start the loop at index0

#
  {% if temp == 'on' %}
    {% set ns.temps = ns.temps + [all_temps[loop.index0]] %}
  {% endif %}```
inner mesa
#

yeah, I arrived at that too, but I think it's still broken

trim leaf
#

so far, it seems to be working as expected, by manually switching the input_booleans on/off

inner mesa
#

you're depending on the order in which the states are evaluated in each of the lists, and it might not align

#

worst case, you can just make the lists manually with the states of each entity, but that gets annoying fast and I was trying to avoid it.

#

if it's working for you, that's what matters. just keep that issue in mind

trim leaf
#

yes I noticed that during troubleshooting, that the new lists that were created are not the same order as how they are defined in temps/bools. The outputs however did match up

#

im guessing this is the order of which they exists in states

inner mesa
#

yes, you might get lucky

trim leaf
#

is it possible to define a dictionary where we can tightly align the bool and the temp?

#

im guessing you cant do that in jinja

inner mesa
#

yes, you can

#

was just thinking about that

#

it's just more cumbersome and again I was hoping to avoid typing it all out. but it might be unavoidable here

trim leaf
#

makes sense. alright ill keep at it. appreciate the guidance

inner mesa
#

meh, losing interest. I can simplify it, but problem remains

#
{% set temps = ['input_number.test', 'input_number.test2']|expand|map(attribute="state")|list %}
{% set bools = ['input_boolean.test2', 'input_boolean.test1']|expand|map(attribute="state")|list %}

{% set ns = namespace(temps=[]) %}
{% for bool in bools %}
  {% if bool == 'on' %}
    {% set ns.temps = ns.temps + [temps[loop.index0]] %}
  {% endif %}
{% endfor %}

{{ ns.temps }}
trim leaf
#

right, im gonna give a dict a try tomorrow. ty 😄

inner mesa
#

I was making it way more difficult than it needed to be:

#
{% set map = {'test1': 'test', 'test2': 'test2'} %}

{% set ns = namespace(temps=[]) %}
{% for bool in map %}
  {% if states("input_boolean." ~ bool) == 'on' %}
    {% set ns.temps = ns.temps + [states("input_number." ~ map[bool])] %}
  {% endif %}
{% endfor %}

{{ ns.temps }}
#

that should work reliably

#

@trim leaf

silent seal
#

Is the delay_on and delay_off for binary sensors hours:minutes:seconds? I'm assuming it is, but it doesn't explicitly say as far as I've seen (so far, I may have missed that)

mighty ledge
# trim leaf right, im gonna give a dict a try tomorrow. ty 😄

just match the object_id's for the input booleans with the object_id's on the sensors and it becomes an easier to manage, only 1 list:

{%- set object_ids = ['test1', 'test2'] %}
{%- set on = expand(states.input_boolean) | selectattr('object_id', 'in', object_ids) | selectattr('state','eq','on') | map(attribute='object_id') | list %}
{{ states.input_number | selectattr('object_id','in', on) | map(attribute='state') | map('float') | list }}
trim leaf
#

How do you use a variable to reference an object? For example:

    {{ states.input_boolean.test.last_changed }}```

this doesnt work, im not sure what syntax to use here?
mighty ledge
#

[]

#

states.input_boolean[test].last_changed

inner mesa
#

What doesn’t work there?

#

Oh, never mind

trim leaf
#

thanks, that worked!

swift glade
#

Not sure if template question but might me the answer.

Can I have more than one state topic in mqtt binary sensor? OR logic.

mighty ledge
floral shuttle
#

in a multi user config, can we jinja template the current logged-in user, preferably to see if current user is_admin?

#

need that for conditional cards (not views)

#

found the attribute in browser-mod browsers, but that is not device independent, so we'd need to know And hard-code those devices...?

mighty ledge
#

Possibly in the front end but the backend doesn’t really have a concept of who is logged in

low blaze
#

Likely a silly question but this template works fine until I add a decimal, what syntax do I need to surround it with to keep functionality? {% set ectarget1 = states('input_number.ec_1') | float %} {{ (ectarget1 + 2) }}

#

I need + .2

#

I've tried ".2" (".2") and (.2)

#

What I didn't try was 0.2 lol

floral shuttle
placid stirrup
#

Hi guys, noob question, but I cannot figure out what I'm doing wrong with the 'new' template sensors. I have the following in my sensors.yaml file.

- platform: template
    sensors:
    - name : "Avg zolder temp"
      state: >
        {{ ((states("sensor.zolder_temp_sensor") | float) + (states("sensor.avg_temp_plants") | float)) | float| round(1) /2}}

But it keeps saying this? The indention is correct, right?

in "/config/sensors.yaml", line 135, column 12```
floral shuttle
placid stirrup
marble jackal
#

the new template format will not work in sensors.yaml as it is not part of the sensor integration. It is part of the template integration.

floral shuttle
#

Unless ofc that is a package name 😉 still, what Mike posted is incorrect in more than 1 aspect

swift glade
mighty ledge
# swift glade yes

Make 2 mqtt sensors and then a template sensor using the other 2. If the topics are event topics, make 2 template sensors using mqtt topic triggers. Then make a template sensor from those.

silent barnBOT
floral shuttle
#

or in the template format:```
template:

  • sensor:
    • unique_id: avg_zolder_temp
      name: Avg zolder temp
      state: >
      {{ ((states("sensor.zolder_temp_sensor") | float) +
      (states("sensor.avg_temp_plants") | float)) | float| round(1) /2}}
      icon: >
#

(blindly copied your template) so didnt comment on that

placid stirrup
#

Thanks guys! You were right, I've placed it under 'template' instead of sensor and now it's working! I prefer to have it in the sensor file, but your first example isn't working.. but the second is, so I keep it that way! Thanks!

floral shuttle
#

and yes, if you use an sensor: sensor.yaml in your configuration.yaml, you can not use the template: there

placid stirrup
#

Exactly, that's my mistake haha. Thanks again! Appreciated.

floral shuttle
#

if on the other hand you use packages, you can throw them all in that same file, and copy the top level integration names template: and sensor: in there

swift glade
marble jackal
#

oh sorry, it seems to be working since 2021.8 as I just saw in the FR you created

mighty ledge
marble jackal
mighty ledge
floral shuttle
#

yep, working wonders here ever since, and superior file organization, very glad with that change

marble jackal
#

so back to my one line configuration.yaml: homeassistant: !include_dir_merge_named /config/include/home_assistant

mighty ledge
#

That doesn’t make sense

#

Remove config if you just have include/homeassistant folders

limpid acorn
#

They might be using it to organize themselves more than anything, does it really cause a problem?

floral shuttle
#

use: packages: !include_dir_named packages and all packages files go in to config/packages.
doesnt get easier than that

#

every package file the uses the identical order of things, with all top level integrations unindented or un '-' listed

mighty ledge
floral shuttle
#

but in Lovelace I do need to use - !include /config/lovelace/buttons/buttons_shortcut_menu.yaml, because all is relative to /config/lovelace/views/ ?

mighty ledge
#

I don't

#

I created a folder called lovelace and I just use lovelace/...

floral shuttle
#

sure, ofc all depends on where you store,

mighty ledge
#

config is usually always implied.

marble jackal
#

It works fine as it is now.. with the /config
I had some issue with an include at some point, and this seems to solve it at that time. And it is stil working 🙂

#

The packages include is in /config/include/home_assistant btw, and includes /config/include/integrations (I actually only use it to split the integration config)

modest sparrow
#

Hey guys, I'm trying to get a list of sensors for my alarm system. I've figured out i need to loop through states.sensor and use the selectattr() function, but I can't figure out how to match them if they have a 'tamper'/'contact'/'occupancy' attribute, to check if the binary sensor has been triggered in the last n seconds..

#

Could anybody give me a lead/example/a way to figure this one out? 🙂

zenith drum
#

Is it possible for an end user to create their own template filters without having to create a custom version of HA? I have the docker version of HA on debian.

inner mesa
#

No, you’d need to modify the HA code

zenith drum
#

Would it be easy to build this feature? My python knowledge is limited but I could look in to making a PR at some point. I feel like it would be useful for people.

inner mesa
#

I suppose such a plugin interface could be built, but I imagine that yes, it would be a lot of work and prone to cause breakage

zenith drum
#

Okay, thanks for your feedback 👍

inner mesa
late island
mighty ledge
mighty ledge
zenith drum
#

Its related to raw data processing using bitmasks and bit-shifting (I know the bitwise_and filter exists but it is limited).. but I feel like I am also going to come across other things where I want to create a custom function in the future too. Maybe I am just more of a power user than the average user 🤣

mighty ledge
#

can you provide an example? You can convert bits to values and do your operations that way

#

there's ALOT of things jinja can do that are not listed in the docs.

#

that are 'advanced'

#

and if you want to actually bitshift, just add those to core and make a PR. I'm sure people would accept it... because everyones had to use it at some point in their career

zenith drum
#

Well there are a few open PR's which I am waiting to see the outcome of before doing anything, but some were closed without being merged so I was considering implementing them myself if they weren't added officially, but I couldn't figure out how I could persist my changes when updating HA that's all.
A theoretical example to extract and convert 5 bits in a 2 byte array would be something like ((value & 0x7C) >> 2) / 10 - currently I can use bitwise_and and perform 'hacky' bit-shifting by subtracting a decimal from the value, but I can't think how I can work with arrays of unknown/variable length. I'd like to test conditions and then perform bitwise operations based on the outcome.

late island
mighty ledge
#

you're using it like 3 times in that

#

line 5

#

line 10

late island
#

both removed

#

thats the error message i send

#

thats the actual template

mighty ledge
#

right but look at the template it responds with

late island
#

Yea thats what I dont understand..

mighty ledge
#

the reload didn't occur because your config is invalid somewhere

#

run a config check and look at the logs

late island
#

by docker exec home-assistant python -m home-assistant --script check_config --config /config ? The Check Configuration button in HA itself not showing anything and also nothing in the logs expect the spamming template warning

mighty ledge
#

you have to look in your logs after you do a config check

#

home-assistant logs

ebon yoke
#

it's not possible to use friendly name on template sensors no more?

mighty ledge
#

name is friendly_name

#

however it will determine your entity_id

zenith drum
late island
mighty ledge
#

sorry not familiar with the argument --files

#

I'd just run the config check the normal way

#

you know

#

through the UI

#

then look at the logs

#

via ssh or samba

buoyant pine
#

The config check command is apparently the proper way

late island
#

Yea thats what I am doing. Thats not giving me anything. I am looking at ssh/samba/portainer.

#

Yea thats what i also read somewhere. But I guess its not even really working, since that error message above.

buoyant pine
#

docker exec -ti home-assistant hass --script check_config -c /config

late island
mighty ledge
#

you can do it either way, just the results go to your logs

late island
#

thats it

mighty ledge
#

instead of being printed in your face

#

I don't use the docker script so I don't know the commands or arguments

buoyant pine
mighty ledge
#

🤷‍♂️ never failed me yet, but I know how to debug shit prior to checking

late island
#

Either way, there is nothing in both. In ssh where I execute the command and in my logs after pressing check configuration. I am so omw to just removing that automation.

mighty ledge
#

are you sure you're editing the correct file?

#

are you sure you reloaded your automation?

late island
#

I mean I shift + f the exclude.entity over visual studio code over samba. Nothing there expect the entries in the log files. Also restarted HA completely. I guess I can try to restart my Nuc..

#

Yea still the same.. I guess I am just going to remove it then

snow laurel
#

I was wondering what the best way would be to template the last zone location that a device had been to? if I just use device_tracker.name.last_changed, that would give me "Away" too. I want to make one template sensor that looks to see if Im at work, and then sets my "desitnation location" as home for instance.

#

I think I can achieve it with two sensors, but I was interested in having it all be in one. Cant I create a variable inside the template with my last named location?

#

Maybe I can use a trigger-based template sensor.

mighty ledge
#

SQL is the only way to get old states

#

it's a pita

snow laurel
#

Im not familiar with what you mean by pita? :P

mighty ledge
#

pain in the ass

snow laurel
#

Ahh.

mighty ledge
#

you need to know how to query things in the database

snow laurel
#

I think I can use a trigger to update the sensor only when I am at work to say "Home" or the lat/long coords.

#

So when Im at work it updates to say my destination is home

#

(trying to get only one sensor for google maps travel time with dynamic sensors)

mighty ledge
#

yeah but that doesn't really "tell you what the last state was"

snow laurel
#

true, but I guess it would work for my sepecific case.

mighty ledge
#

if that's all you want just make a template sensor that provides the lat/lon attributes for where you want to go after you enter a zone.

#

you don't need a device tracker for the travel time integraitons, they accept sensors with lat/lon attributes or a state which is lat/lon

#

lat/lon attributes are easier because then you don't need to know the order, unlike when you use lat/lon as the state.

snow laurel
#

I'll be using the device tracker on the phone as the origin point, so the destination will be a sensor for lat/lon depending on where I am.

#

I think I know what to do now, thanks ;)

little lion
#

are you able to group lights and switches together in home assistant?

#

or do you have to convert the switches to lights then group the lights

silent barnBOT
#

Groups allow the user to combine multiple entities into one.

static anchor
#

Is there a template I can use to control a linear actuator using L298N and ESP32?

modest sparrow
uneven pendant
#

{% set value = states('counter.chore_ava_counter') | int %}
You've earned ${{ value / (50) * 15 }} so far.

#

This returns a float no matter what I do

#

I'm using this in a markdown card

#

And I'm trying to get it to round to the hundreds place instead of doing this.....

#

Oh, I can't post screenshots

#

2.699999999997

#

Is what it returns

#

I want it to be 2.70

#

When I try....
{% set value = states('counter.chore_ava_counter') | float %}
You've earned ${{ value / (50) * 15 | round(2) }}

It doesn't do jack

#

Just still spits 2.699999997

#

Btw, that value of the counter is 9. Not sure it matters

inner mesa
#

You’re rounding 15

uneven pendant
#

Oooo

#

Parenthesis?

mighty ledge
#

Pemdas

uneven pendant
#

Wow. I guess I didn't think round would do work before the rest of it

#

That works. Thanks

mighty ledge
silent seal
#

I was wondering if someone can help me with a template. I have an input select for "manual alarm setting" where "unset" means I didn't set it manually, "on" means I set it manually to on, and "off" means I set it manually to off. If it's "unset" I want to use the workday sensor to specify if an alarm should go off, but in all cases I only want it to trigger an alarm if it didn't already today. I currently have this: https://www.codepile.net/pile/jMQRq7E6
(Sorry for formatting it in Twig, but codepile doesn't have Jinja support and Twig is fairly similar.)
Is there a better/easier/simpler way to do what I'm trying to do?

sonic nimbus
#

how can I put in my template level of light brightness? I want every single time, when lights goes on to put maximum brightness to 60%

#
  trigger:
    - platform: state
      entity_id: light.livingroom_ceiling_led_1, light.livingroom_ceiling_led_2
      to: 'on'
  action:
    service: >
      light.turn_on
        #here I need to put brightness value#
        
    entity_id: >
      {{trigger.to_state.entity_id}}```
#

but I don't know how? as a data_template maybe?

silent seal
#

Usually services are like this:

service: light.turn_on
data:
  brightness_pct: 100
target:
  entity_id: light.bed_left
sonic nimbus
#

thanks

#

now I have a different problem, when I do check config it shows me an error

#

so this OR condition makes me trouble, if I remove this condition OR automation passes as it should

#

but what I really want to do is to put some and conditions and then to put or

silent seal
mighty ledge
# silent seal I was wondering if someone can help me with a template. I have an input select f...

there's really not much that you can do other than refactoring it.

{% set lastNotToday = state_attr('automation.wake_up_light_alarm_with_sunrise_effect', 'last_triggered') < today_at() %}
{% set setting = states('input_select.manual_alarm_setting') %}
{% set alarmOn = is_state('binary_sensor.workday_sensor', 'on') if setting == 'Unset' else setting == 'On' %}
{{ alarmOn and lastNotToday }}
silent seal
mighty ledge
#

you did have a bug

#

you'll have to fix it in yours

silent seal
#

today_at() is a nice trick. Didn't know about that.

#

What was the bug?

mighty ledge
#

states('binary_sensor.workday_sensor') doesn't return true/false

#

so i made it is_state(...,'on')

silent seal
#

Ahhh, thank you! It has been working, but I presume that was by accident rather than by design

mighty ledge
#

well yeah

#

it would have failed if workday_sensor was off

#

well, by fail i mean it would have still triggered

silent seal
#

That might explain my alarm clock last Saturday

mighty ledge
#

because a populated string resolves true

#

and 'on' or 'off' is a populated string

silent seal
#

Yup, makes perfect sense in the world of truthy evaluations

mighty ledge
#

yep

#

it's a pita sometimes, but always work in True/False if you can

silent seal
#

Yeah, makes perfect sensor. For some reason I assumed the state of a binary sensor would equal that. Now I know better

mighty ledge
#

well, all states are strings

#

tbh, I don't like it but that's what it is

#

I'd rather have states be typed and the frontend take care of it. Then templates would be super easy, but it's an old design decision from years ago.

#

TBH, I think they are moving that route long term

silent seal
#

Yeah, the mistakes of years past easily come back to haunt you in programming. Though there was likely a logical reason at the time.

mighty ledge
#

no, it's just how base jinja works

#

jinja always returns strings

#

This typing stuff that it does was added recently

silent seal
#

It's all a programmer's fault somewhere down the stack (says the programmer)

mighty ledge
#

IIRC the original reason jinja was developed (outside HA) was an "easy" language to create forms of populated information without a huge memory overhead

#

which is why namespace and if/else scoping is so limited

silent seal
#

Yes, twig, blade and liquid are all much the same thing.

near meadow
#

What does it take for my template sensor to be selectable in the Energy dashboard? I have device_class: energy and kWh as units...

near meadow
#

Roger that. state_class and last_reset got it selectable. Now it just says" statistics_not_defined"

gleaming depot
#

I have this entity which grabs some data from my local school's menu, but also a ton of other stuff. I want to grab todaysFood from the entity in this screenshot: https://imgur.com/a/mOdKucv and use it in a text-to-speech intergration.

#

I'm using the "skolmaten" intergration from HACS

inner mesa
#

It’s just an attribute

gleaming depot
#

And how would I go about using it in TTS

inner mesa
mighty ledge
#

Issue isn’t related to templates

mortal sundial
#

I would like to build a template that evaluates to true if a light has been on within in the last 10seconds. How can get the template to evaluate states from the past?

{{ ( as_timestamp(now()) - as_timestamp(state_attr('automation.mail_notification', 'last_triggered')) |int(0) ) > 30 }}

I tied using last_on with the above example but I had no success.

mortal sundial
# inner mesa <https://www.home-assistant.io/integrations/template/#delay_on>

Thanks for sharing this.

According to the description this would check the condition until x time has passed.
The amount of time (ie 0:00:05) the template state must be met before this sensor will switch to on. This can also be a template.

I would like to check if the condition has been true within the last 10sec but not for the last 10 seconds.

mighty ledge
#

with a count

inner mesa
#

The other should do that too. It has a count

mighty ledge
#

i do that all the time

inner mesa
#

Anyway, OP has vanished

mighty ledge
#

sorry, had to give you crap

#

go go go do do do

#

if you even noticed what I did 🤣

silent seal
#

I pop into this channel just to get ideas from time to time. It's amazing how often I see the solution to a question I had in the back of my mind. Thanks for pointing out statistics!

inner mesa
#

I always forget about history_stats, so there are many such exchanges where I suggest statistics and history_stats is more appropriate. They each have their own uses...

silent seal
#

This will also help me set up some things because I now remember I can look at past data to see how things change

wise cedar
#

A bit unsure where to put this one:
Looking to set up a sensor that records max energy used by the hour. The sensor should automatically reset each month.
Have set up a utility meter, and was looking at long-term statistics which look to have the data I need, but not necessarily available to an automation?

ebon yoke
#

i'm a bit confused regarding the use of unique_id, name and friendly_name .. i want to have something that i can change throught the UI.. for instance for a sensor that's moving around..

#

and also i may want to use some special characters in the name visible in the UI

#

what is the correct/best way of setting up sensors to accommodate this?

fossil venture
wintry bay
#

Hey, i'm adding switchbot curtain to HA. I noticed a issue in the code here: https://community.home-assistant.io/t/switch-bot-api-integration/270550
Which is value_template: '{{ value_json.body.slidePosition }}' this should be a float (or int) because the output of curl is: <output-truncated>"slidePosition":100},"message":"success"}

How can I edit the value_template correctly? I'm not that great at coding stuff :/
On HA the error is: 2021-12-04 16:11:32 ERROR (MainThread) [homeassistant.components.template.cover] could not convert string to float: '' but of course if i remove the double ' or use double quotes, it won't work. HA complains of an issue in the code.

Solved 🙃 a typo in the curl

mighty ledge
#

the only time it would be needed is if you are trying to round the sig figs

#

otherwise, home assistant will type it after the resolution of the template

wintry bay
# mighty ledge you shouldn't ever have to cast the ending result. People do that in error

right, i thought that actually but kept seeing that error and that mislead me. At the end was really the url the issue. copy/paste didn't work properly and had empty deviceId everywhere in the secrets file.

Anyway. New issue 😄
https://www.home-assistant.io/integrations/cover.template/#position_template
Legal values are numbers between 0 (closed) and 100 (open).

Mine are inverted. 0: open, 100: close.
Do you by any chance know how to invert that?

wintry bay
#

was looking to a "change direction" option but turns out the math way was easier. wow. thanks!

mighty ledge
#

the math is stupid easy if you know templates

wintry bay
#

yes i'd say so too ponder

dull flicker
#

hey guys if I want to have a customer variable for my AC unit can I not put it in the climate.yaml?

#

current_blower_speed isn't allowed apparently

rare panther
#

Need help in understanding this

{{ states('sensor.cam_storage') }} MB
{{ states('sensor.cam_storage') | filesizeformat }}
{{ states('sensor.cam_storage') | int*1000000 | filesizeformat }}
{{ states('sensor.cam_storage') | float *1000000 | filesizeformat }}
{{ 12920000.0 | filesizeformat}}

The results of the above are

12.92 MB
12 Bytes
1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB
TypeError: can't multiply sequence by non-int of type 'float'
12.9 MB

the sensor is a folder platform which provide the state info as a size of the files within that folder in MB. However, when applying the filesizeformat it behaves quite strange in 3rd and 4th values Shouldn't it display the value correctly like 5th value? I understand that the 2nd value is incorrect since the state returned is 12.92 and hence it tries to convert only that value

The reason I want to use the filesizeformat is that it dynamically applies the correct notation kb,mb,gb etc

inner mesa
#

Order of operations

#

You need some parens

rare panther
#

ah okay - so this works {{ (states('sensor.cam_storage') | float *1000000) | filesizeformat }} gives 12.9 MB - thanks!

fierce imp
#

a little lost how do I update this template so a default is provided? - name: "Garage OctoPrint Time Remaining" unit_of_measurement: 's' availability: > {{ not is_state('sensor.garage_cr6se_estimated_finish_time', 'unavailable') }} state: > {% set finish = as_timestamp(states('sensor.garage_cr6se_estimated_finish_time')) %} {% if is_number(finish) %} {{ (finish - as_timestamp(now())) | int }} {% else %} unknown {% endif %} attributes: start_time: "states('sensor.garage_cr6se_estimated_finish_time')"

inner mesa
#

If you’re just seeing the warning at HA start, there’s an issue in 2021.11 that can cause that despite the availability template. It’s fixed in 2021.12

fierce imp
#

Ah good to know beta time 😂

foggy owl
#

has anyone gotten Dwains Dashboard working

mighty ledge
daring steppe
#

Does anyone have an idea why data from my template sensor does not end up in InfluxDB? The entity does, but no data. The sensor works fine in hass...

- sensor:
    - name: "Medeltemperatur Nedervning"
      unique_id: medel_downstairs
      unit_of_measurement: "°C"
      state: >
        {% set toalett = states('sensor.toalett_sensor_temperature') | float %}
        {% set lekrum = states('sensor.lekrum_temperature') | float %}
        {% set hall = states('sensor.hall_temperature') | float %}
        {% set tvattstuga = states('sensor.tvattstuga_temperature') | float %}
        {% set vrum = states('sensor.vrum_temperature') | float %}
        {% set kok = states('sensor.kok_temperature') | float %}

        {{ ((toalett + lekrum + hall + tvattstuga + vrum + kok) / 6) | round(1, default=0) }}```
mighty ledge
umbral pond
#

hey guys - if I could have your advice on this... I have created a script that takes a capture using the camera.snapshot service from a camera entity passed as a parameter to the script and then sends this capture via telegram to a user.
So there is a second service call for telegram_bot.send_photo. I am using now().strftime to produce the filename for the capture and I would like to ensure that the same filename can be passsed (somehow) as the file and caption for the telegram service call.

Because seconds are also used in strftime I am worried that if I reuse the same line of code , if he time between service calls has passed by 1 second then the telegram service won't be able to locate the file.

Here is my code: https://paste.debian.net/hidden/b1d5a472/

#

Suggestions are highly appreciated.

#

The obvious workaround would be to lose the "seconds" and leave it at %H%M

mighty ledge
#
take_screenshot:
  ...
  variables:
    thetime: "{{ now().isoformat() }}"
  ...
  sequence:
      ....
      data:
        filename: /config/www/camera_captures/{{ camera_entity }}_{{ thetime }}.jpg
slow vine
#

Is there a way to filter out an entity not available? I tried filtering out entities with a state of unavailable but some entitities are orphaned and the entity itself is unavailable how do I filter out those entities in a template.

marble jackal
sinful mica
#

hello , my philips hue sensor also shows temperature. But it has an offset of 2C less than the actual temperature. How can i make it show the measured temperature +2 C ?

#

Or how do i add a new entity with the philips sensor temperature + 2 as value ?

#

(oh i scrolled up and saw an example ... nvm)

fierce turret
#

Can anyone shed some light on how I remove the date from a sensor? The following code outputs: 2021-12-06 13:35:00. I would like to get just the time, 13:35. Also, what is the preferred method, top or bottom code?
{{ states.calendar.family.attributes.start_time }}
{{ state_attr('calendar.family', 'start_time') }}

marble jackal
#

bottom is preferred, as is also mentioned quite clear in the docs:
https://www.home-assistant.io/docs/configuration/templating/
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).

edgy umbra
#

Hi, want to count my tv's that are playing but the template below gives an UndefinedError: 'media_player' is undefined error?

sensor:
  - platform: template
    sensors:
      televisions_playing:
          value_template: >
            {% set media_players = [
              media_player.samsung_tv_remote,
              media_player.samsung_tv_slaapkamer,
              ] %}
            {{ media_players | selectattr('state','eq','playing') | list | count }}```
mighty ledge
#

hint, if you want entity_id's they need to be in quotes. Then you need to supply the list to the expand method to get them into state objects

pastel moon
#

Hi, I am trying to feed a light group data in configurations.yaml. I have this https://pastebin.com/nH5BvmXE, where the first one works and was hoping the second should work, but can't seem to get the syntax correct. Can someone point me in the right direction please?

slim holly
#

I have a problem with my one of my ESPHOME sensors. HA is recognising the sensor as string and not as numeric, so my numeric state trigger will not work.
If i use {{ states('sensor.gosund4_temperatur') > 0 }} in the developer tools i get TypeError: '>' not supported between instances of 'str' and 'int'
but with {{ states('sensor.gosund4_temperatur')|float > 0 }} the result is true.

edgy umbra
mighty ledge
edgy umbra
#

It works perfectly fine for my speakers like this.

#
    sensors:
      speakers_playing:
          value_template: >
            {% set media_players = [
              states.media_player.sonos_keuken,
              states.media_player.badkamer,
              states.media_player.living,
              ] %}
            {{ media_players | selectattr('state','eq','playing') | list | count }}```
#

It now says 1 speaker playing which is correct...

mighty ledge
#

I hope you see your error

#

look at your other list

#

and look at the one you posted

#

they are not the same

inner mesa
#

it both starts and ends with "s"

mighty ledge
#

shh rob

#

lol

edgy umbra
#

Oh cr*p. 😄

mighty ledge
mighty ledge
pastel moon
inner mesa
#

It would be a feature request

pastel moon
inner mesa
#

You could simulate that with a template light

slim holly
# mighty ledge That doesn't make sense. All states across home assistant treat states as strin...

I knew that the value must cross the threshold. I had tested yesterday very long time with the automation and the developer tools and never the trigger was triggered, although the threshold was crossed. Now I have just deleted the automation completely and created new and then restarted the HA. What should I say, now everything works, no idea what the problem was. Now I feel pretty stupid. Sorry for the stupid question. 😩

haughty pond
#

Hi! I'm using following line to display a sensor in a markdown card -> {{states('sensor.nasta_buss_mot_lyckeby_0')} , this works fine giving me a time in HH:MM:SS. But is there an easy way to display it directly in the markdown card without the seconds part? Thanks beforehand.

haughty pond
#

Okay, I've tried like 10 different ways now. Including <code>{{ strptime(states('sensor.nasta_buss_mot_lyckeby_1'), "%H%M") }}</code> but it still shows HH:MM:SS

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://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

inner mesa
#

probably because the state is a string and not a datetime, so it's just passing it through

haughty pond
#

@inner mesa , problably, but I tried using strptime now with the same result, shouldn't that fix it?

inner mesa
#

like you just posted? like I said, it's a string, not a datetime

#

states('sensor.nasta_buss_mot_lyckeby_1') is a string, like every state

#

oh, nevermind

#

I'm an idiot

haughty pond
#

🙂

#

I was think I was the idiot

floral shuttle
#

having this trigger template:```
template:

  • trigger:

    • platform: event
      event_type: hue_event
      event_data:
      id: auditorium_tap_switch_button
      sensor:
    • name: Hue tap switch last event
      state: >
      {{trigger.event.data.subtype}}
inner mesa
haughty pond
#

The state is a time displayed in this format HH:MM:SS

floral shuttle
#

works just fine, except when one taps the same button multiple times. (and the trigger doesnt fire) can I somehow add the event.time_fired to the trigger?

haughty pond
#

It also has attributes for time, date or tiemdate.

inner mesa
#

then you need to provide that string to strptime(). you need to provide the format of that string so that it can parse it, not what you eventually want to output

#

you're doing two things at once

#

strptime(string, format) parses a string based on a format and returns a datetime object. If that fails, returns the default value, or if omitted the unprocessed input value.

haughty pond
#

Hm.. But if I have to it another way, is there an easy way to get minutes until that time occurs instead? That would actually be more convinient.

#

Like "The next bus leaves in x minutes"

#

Because I'm doing it in a markdown card

inner mesa
#

{{ ("15:30:01"|regex_findall(".*:(.*):.*"))[0] }}

#

-> 30

#

is that what you want?

#

{{ "15:30:01".split(':')[1] }}

#

-> 30

#

oh, I see. you also need to do some math

#

I'm not doing a very good job of helping here 🙂

haughty pond
#

Hm.. Sorry if I'm confusing you by changing the question in the middle of the discussion. Anyway, TLDR: Sensor outputs time in a string like eg. "21:16:00". I want to get the number of minutes outputted until that time occours in a markdown card mid sentence.

#

No problem, @inner mesa , glad you're trying!

#

I tried this now but with no luck, just getting an int number instead:

'''

#

{{ ((((states.sensor.nasta_buss_mot_lyckeby_0, "%H:%M:%S") | int)) - ((as_timestamp (now()) | int ))) }}

#

Oh.. See what I did there, let me try something

inner mesa
#

you can start with today_at(states('sensor.nasta_buss_mot_lyckeby_0'))

haughty pond
#

That dindn't get me anything

#

Same thing. No output.

inner mesa
#

{{ today_at("13:05:01") }} -> 2021-12-06 13:05:01-08:00

haughty pond
#

UndefinedError: 'today_at' is undefined

inner mesa
#

you're using an old HA version

haughty pond
#

Version
core-2021.9.7
Senaste version
core-2021.11.5

inner mesa
#

that's almost 3 months old

haughty pond
#

Aight, maybe time for an update then. 🙂

inner mesa
#

once you do, this might work for you:

#
{% set parts = ((today_at("13:05:01") - now())|string).split(':') %}
{{ "%s hours, %s minutes" % (parts[0], parts[1]) }}
#

-> 0 hours, 59 minutes

haughty pond
#

Just wrapping up startup now after update. Will try!

#

@inner mesa : Got this now: ValueError: could not convert datetime to datetime: '1900-01-01 21:36:00'

When using the following

{{ "%s hours, %s minutes" % (parts[0], parts[1]) }}```

That makes it seem like it actually is a datetime and not a string or?
inner mesa
#

you still have strptime() in there. see mine

#

you just want the state

haughty pond
#

I tried yours as well, didn't work

inner mesa
#

🤷

#

it does

haughty pond
#

OH

#

Now it did.

#

Weird. I must be a dumbass.

#

And if I just want it in minutes?

#

Because usually the bus leaves like every 20 min or something. Of course not in the night, but then it ca say like 240 min, doesn't matter.

#

Got it: {{ ((today_at(states('sensor.nasta_buss_mot_lyckeby_0')) - now()).seconds / 60) |int }}

#

Thanks, @inner mesa !

thick ivy
#

Hi, I am trying to create image cards in lovelace, is it possible to create a folder where the images are named the same as the entities' friendly_name and in the image field do something similar to / local / images / {{friendly_name}}. png?

Thanks in advance

silent barnBOT
floral shuttle
#

darn. sorry. do we need to repeat the - trigger for all sensors per trigger (and have the sensor: at the same indent?

#

somehow it seems more logical to only state trigger: once and then align the trigger platform and sensor to the same indent..

rare panther
#

Does the local file accept template for the file_path? https://www.home-assistant.io/integrations/local_file/ I was trying the below, which works fine in the Dev tools -> Template but reports errors in config validation when I provide the same for the file_path
{{ state_attr('sensor.cam_storage', 'file_list') | reject('search','^\/\w*\/\w*\/\w*\-\w*.mp4$')| sort(reverse=true) | list| first }}

inner mesa
#

It says ‘string’, so no

#

It would say ‘template’

rare panther
#

okay. So I would have to do that extraction of the exact filename via this template in automation and pass the exact string.

inner mesa
#

yes, presumably via local_file.update_file_path

sweet atlas
#

I dont know if this is the correct channel for this, but I want to write a template for a lot of sensors. they will all be the same (only difference is their index). so example: door_code_user_1, door_code_user_2, etc. but it will be very messy writing this 25 times. Is it possible to do a for-loop and write it out like that? Or does anyone know how I would go about making something that will auto-generate a yaml file?

fossil venture
sweet atlas
floral shuttle
#

also have a look at decluttering card, which is a last resort before entering the realm of lovelace_gen. throw all repeating stuff in a template and only list a variable name or 2 in the config. very nice. (comp with yaml anchor, but global) https://github.com/custom-cards/decluttering-card

thorny snow
#

Hi all, I have a small question regarding the new entity categories. Is it possible to find the entity_category of a specific entity from within a template? And/or is it possible to find all entities in a category from a specific device? I searched the docs, but it quite limited on this topic. This feature seems to be purely for the configuration page from home assistant, and not really made for custom UI's.

thorny snow
#

oh 😦 is there any reason to hide this property from the end user? Or is this something that could still come in future updates?

#

Thx for the information anyway 🙂

mighty ledge
silent barnBOT
mighty ledge
#

@mighty roost check the pins 📌

mighty roost
mighty ledge
#

yep

north steppe
#

hi there! I have a question

#

I have an entity that is a sensor from mqtt. how is it that I can have history on the sensor, but no current value on the sensor?

#

if I place the entity in lovelace as a gauge for example, it reports 0 [units] but when I click on the gauge entity it shows the historic values as they should be (non-zero)

north steppe
sonic nimbus
#

Hello, I have an automatioon which I monitor 2 switches, and if they are switched in seconds both of them, then I turn on wled

#

however, I want now, instead of the second switch to implement last_changed date of my binary_sensor.hallway_ledstrip_button

#

basically something like this : {{states.binary_sensor.hallway_ledstrip_button.last_changed}}

#

When I put it in my template editor, I see some datetime value, but its not correct time..so my question is is there an attribute for binary_sensor when it was pressed?

thorny snow
#

Hi guys

#

I'm trying to build a light template and im getting a strange error

#

the error is:

#

Invalid config for [light.template]: [effect_list_template] is an invalid option for [light.template]. Check: light.template->lights->ambivision->effect_list_template. (See ?, line ?).

mighty ledge
#

@thorny snow I replied to you on the forums

heady gulch
#

Greetings, so I have a vesync smart switch that comes with energy monitoring. Since this is not directly supported in the HA energy dashboard, I followed a guide to create a sensor template to have the appropriate data. However it doesn't show if I try to add it to the energy configuration. Any guidance would be greatly appreciated

fossil venture
heady gulch
#

I can't seem to use state_class in my sensor template

#

Invalid config for [sensor.template]: [state_class] is an invalid option for [sensor.template]. Check: sensor.template->sensors->heatingwire_today_energy->state_class. (See ?, line ?).

fossil venture
#

Use customize to add it then

heady gulch
#

so disregard this part of the pinned message: Keep in mind however it's best to incorporate these attributes in the integration itself and not as customisations! ? 🙂

#

if it works .. trying

fossil venture
#

You can't follow that if the integration you are using does not support it. Use customize to get up and running then raise an issue for the integration on github

heady gulch
#

ok now I can add it .. need to fix this .. statistics_not_defined
sensor.heatingwire_today_energy

#

nevermind .. I guess it just needed some time to generate some stats for it .. message is gone now

#

thank you !

fossil venture
#

Dont forget to raise the issue.

heady gulch
#

checking for an existing one

#

weird .. existing closed issue .. someone saying: integration sets the state_class on it's own...

#

issue opened

mighty ledge
#

It's not supported in the legacy format

#

so use the new format

#

That issue will be closed if you write it against legacy, as it's legacy

heady gulch
#

struggling to convert to the new format with a sensors.yaml outside configuration.yaml file .. trying ...

#

if anyone feels like helping with syntax that would be appreciate .. always struggling with the proper intendation: ```- platform: template

  • sensor:
    • name: "chicken_heatingwire_today_energy"
      state: '{{state_attr("switch.chicken_heatwire", "today_energy_kwh")}}'
      unit_of_measurement: kWh
      state_class: total_increasing
      device_class: energy
#

can't find working example of external yaml file using the new template syntax

inner mesa
#

That’s a mix of the two formats

heady gulch
#

hence my confusion I guess lol

inner mesa
heady gulch
#

but that example is within the configuration.yaml file ..

#

instead of in a included yaml

inner mesa
#

Do you have template: in configuration.yaml?

heady gulch
#

I'm putting this in sensors.yaml .. does the new format need me to do this in a template.yaml instead ?

inner mesa
#

That’s wrong

#

If you don’t already have template:, then just follow the example

heady gulch
#

I dont want to overburden my configuration.yaml file if I can help it

inner mesa
#

First get it working

#

It’s no different from any other example of including files

mighty ledge
#

template: !include_merge_dir_list templates -> in configuration.yaml
Then put the template in any yaml file inside a folder you create named templates. The file contents will be:

- sensor:
    - name: "chicken_heatingwire_today_energy"
      state: '{{state_attr("switch.chicken_heatwire", "today_energy_kwh")}}'
      unit_of_measurement: kWh
      state_class: total_increasing
      device_class: energy
heady gulch
#
  - sensor:
      - name: "chicken_heatingwire_today_energy"
        state: '{{state_attr("switch.chicken_heatwire", "today_energy_kwh")}}'
        unit_of_measurement: kWh
        state_class: total_increasing
        device_class: energy``` works in my configuration.yaml file
#

@mighty ledge Error loading /config/configuration.yaml: could not determine a constructor for the tag '!include_merge_dir_list'

heady gulch
mighty ledge
#

its !include_dir_merge_list

#

was going off my head, that's pulled from the docs

heady gulch
#

ok it validates now

#

thanks guys .. just confirming that all is good now .. I believe it is

neon barn
#

is there a way to make a subtraction with the templates that only returns positive values?

mortal shard
#

Is it possible to use templating when creating a sensor using the Integration platform?

inner mesa
#

like what?

slow vine
inner mesa
#

I don't think they are directly

#

name is, but I don't think the others are

slow vine
#

:( I was hoping I can separate config switches from other switches in auto entities card.

marble jackal
#

Is there a way to combine dicitionaries into one?
examle

{% set dict1 = {'a': 1, 'b': 2} %}
{% set dict2 = {'d': 3, 'b': 4} %}

Should be combined into: { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
I found the | combine filter online, but that doesn't seem to work in the template editor

#

dict2 doesn not have a fixed number of keys, so it could be 1, or 2 or whatever number of keys and items

hexed wing
#

We don't have the ability to do dictionary/list modifications in our Template engine

#

combine I believe/remember is a specific Ansible feature, not natively to Jinja2 (but is has been a while since I've used Ansible, so things might have changed)

fossil venture
hexed wing
#

hehe you can't 😄

marble jackal
#

okay, good to know 🙂

hexed wing
#

Although we should be able to make such things possible nowadays, I does need to be done with a lot of testing and care. As in, we don't want to create abilities to modify internals

marble jackal
thin vine
#

I seem to recall that you can use templates as well to create conditional attributes in data, but I can't seem to find where I found that. ```

#
  attribute: 1
  {% if something %} attribute: 2 {% endif %}```
#

like that

hexed wing
#

{% if something %} {"attribute": 2} {% endif %}

marble jackal
#

and should this work then?

- variables:
    extra_data:
      language: nl
      voice: thefes   
- service: tts.google_cloud_say
  data:
    entity_id: media_player.whatever
    message: test
    {% if extra_data is defined %} {{ extra_data }} {% endif %}
#

Hassbot and VSCode do not like it 😉

hexed wing
#

no that won't work

#

you could do that, but you'd have to fully template the data part and return a single dictionary string

#

but honestly, that is stuff that will bite you at some point 🙂

#

So, maybe not...

marble jackal
#

okay, I'll just stop with this futile attempt then 🙂

mighty ledge
mighty ledge
#

Unless you're in an automation, then you can use yaml.

#

but you have to use python's dictionary built-in functions like update, which has it's own caveats

hexed wing
mighty ledge
#

I've been using it for sometime

hexed wing
#

Well in that case, we have to report a security issue with Jinja :S

mighty ledge
#

or maybe I did it differently

#

hold up, lemme check

#

I've done dict merging somehow. I assumed it was update

mighty ledge
hexed wing
#

Aah that will do 👍

#

Nice trick

thin vine
#

yeah, it passes ' ha core check' so should be fine

mighty ledge
#

I doubt vscode understands that data can be a template

mighty ledge
thin vine
#

well yeah I worked it out in the template editor. should be testing it later

marble jackal
#

Ah nice petro, will give it a try!

frank gale
#

I have multiple trigger-based binary_sensors in a template.yaml
Trying to template the icons based on state in example:

binary_sensor:
- name: Schlaf
icon: >
{{ 'mdi:sleep-off' if is_state('binary_sensor.schlaf','off') else 'mdi:sleep' }}
state: >
{{ trigger.id == "sleep" }}
unique_id: binaryschlaf
After a restart none of the icons show up in Lovelace. After some time, some of them show up and the rest stay on the default binary sensor icon. Am I missing something?

With all my non-trigger-based binary sensors this template works as it should...

mighty ledge
frank gale
inner mesa
mighty ledge
#

But you can get around that...

#

in automations

#
variables:
  my_fake_dict:
    key: value
#

then

service: xyz.ijk
data: "{{ my_fake_dict }}"
#

I use that quite a bit

marble jackal
#

This is what I did now using your template:

  variables:
    tts_service: tts.google_translate_say
    service_data:
      language: nl
#

then

    - alias: "Send TTS message"
      service: "{{ tts_service }}"
      target:
        entity_id: "{{ tts_target_list }}"
      data: >
        {% if service_data is defined and service_data != None %}
          {{ dict( message = tts_message, **service_data ) }}
        {% else %}
          {{ dict( message = tts_message ) }}
        {% endif %}
mortal shard
# inner mesa like what?

Like if I want the source to be a combination of several sensors, but now I have to first create a template sensor with my calculation and then feed the new sensor to the Integration platform as a source.

inner mesa
#

that's your only option

mortal shard
#

Alright good to know 😊

austere zenith
#

Hi there. a dumb question. I want to make a template for my heat pump though and IR blaster.

#

My IR remote only has a toggle on/off button.

#

I currently have no way of knowing whether the heat pump is on/off

#

how do i create an entity that allows me to toggle the on/off

#

I currently don't mind if home assistant doesn't know the state of the heat pump

#

Am i correct in saying that I should just write a script?

fossil venture
#

You can create a template switch. The turn_on and turn_off actions will both be to call the remote command. The state feedback (value_template) is optional so you can leave that out as you dont have any way to determine this.

#

A good way to add state feedback if you want this in future would be with a power monitoring smart plug. Power > X = ON.

austere zenith
#

Thanks.

#

thats awesome.

#

There's no power plug for my heat pump unfortunately.

#

its directly hooked up to my house's AC.

fossil venture
#

Ah ok.

#

There are other options for controlling heatpumps, like sensibo (cloud 🤮 ) or ESPHome or even a wifi card addon for your particular heatpump (best option). These will create Climate devices. What type of heatpump is it?

austere zenith
#

its a daikin heat pump

fossil venture
#

Are you in Australia?

austere zenith
#

the wifi card isn't available in my country

#

for some reason

#

im in new zealand.

#

how did you guess?

fossil venture
#

I have a spare wifi card you can have for postage.

#

DM me.

austere zenith
#

Your message could not be delivered. This is usually because you don't share a server with the recipient or the recipient is only accepting direct messages from friends. You can see the full list of reasons here:

#

But you're too kind. You don't need to send one to me.

fossil venture
#

I wont ever use it. I offered it on the forum too. Hang on...

#

(I got new heatpumps with the card fitted and saved the card from the old one).

austere zenith
#

oh

#

do all daikin use the same wifi card?

#

just in case different models use different cards.

fossil venture
#

All support the older card I'm looking up the part#

austere zenith
#

ok, thanks.

fossil venture
#

BRP072A42. Pretty sure all Daikin heatpumps have the S21 connector needed for this. The 2.0kW – 7.1kW Cora & Alira systems just require a differnt connecting cable.

austere zenith
#

FTXV25UVMA

#

i believe that's the model number.

fossil venture
#

That's a 2.5kW Cora. It is compatible.

austere zenith
#

oh

#

thats great.

fossil venture
#

You will need the extra cable though.

#

Not sure where to get that.

austere zenith
#

oh, let me sort that out first before you send me anything.

#

i don't want the part to goto waste because i can't find the cable.

#

Sidetracking a little, you mentioned using ESPHome. I have ESP32 boards. But how would you hook that up to the heat pump?

#

That sounds interesting.

fossil venture
austere zenith
#

Oh

fossil venture
#

Rod at Peninsula Air (link I posted earlier) is very helpful and can sort you out re: cable. Send them an email.

austere zenith
#

So its controlling it through the remote.

#

Will do

fossil venture
#

Yeah. Let's move this to DIY as it is no longer about templates.

silent barnBOT
ivory pawn
#

Hello, Can someone tell me what is wrong in my template?

This works:

  command: curl -X https://api.com/test/?period_from={{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:30', True)}}```
#

This works in developer tools > templates:

{{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:30', True) }}
{%- else -%}
{{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:00', True) }}
{%- endif %}```
#

BUT this combination doesn't work:

  command: curl -X https://api.com/test/?period_from={{
    {% if (now().minute) > 30 %}
    {{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:30:00Z', True)}}
    {%- else -%}
    {{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:00:00Z', True)}}
    {%- endif %}}}```
#

I'm trying to round down to the nearest half hour and pass this into the curl command. Think its formatting issue but maybe command line template cannot handle conditions.
Any ideas?

inner mesa
#

you're nesting templates

#

you've surrounded the whole template with {{ }} with some other template stuff inside

#

you'll need to play with it, but I would start with something like this:

#
- platform: command_line
  command: >-
    curl -X https://api.com/test/?period_from=
    {%- set format='%Y-%m-%dT%H:30:00Z' if now().minute > 30 else '%Y-%m-%dT%H:00:00Z' -%}
    {{ as_timestamp(now()) | timestamp_custom(format, True) }}
#

you also had a multiline template, but didn't add the >- to introduce one

#

that results in

- platform: command_line
  command: >-
    curl -X https://api.com/test/?period_from=2021-12-09T16:30:00Z

for me

ivory pawn
#

@inner mesa thanks, did realize the nesting issues but didnt try the >- . ill try it all now 🙂

#

@inner mesa your code works great and neater too. I had simplified what i wanted to make it easier to help, but I also wanted to subtract 24 hours from the result . I had used this in my example period_from={{(as_timestamp(now()) - (24*3600)) | timestamp_custom('%Y-%m-%dT%H:30:00Z', True)}} but not sure how to add that to your code?

inner mesa
#

Edit: something like this: {{ (now() - timedelta(days=1)).strftime("%H:%M:%S") }}

ivory pawn
#

thanks @inner mesa ill give it a go

bitter spindle
#

Hey, could anybody help me in here? Why am I seeing this message when I try to render the template?

Template:

Test: {{input_datetime.time_bedroom_left_window_opened}}

Error I get:

UndefinedError: 'input_datetime' is undefined

However, I can nicely see that the value is actually populated:

input_datetime.time_bedroom_left_window_opened
time_bedroom_left_window_opened
01:45:24    has_date: false
has_time: true
editable: true
hour: 1
minute: 45
second: 24
timestamp: 6324
friendly_name: time_bedroom_left_window_opened
inner mesa
#

@ivory pawn I edited it a bit after testing. You can convert to timestamp and use timestamp_custom, or just use strftime() like that

silent barnBOT
inner mesa
#

because that's not valid template syntax

bitter spindle
#

Ooo, thank you very much! Works like a charm now:

Test: {{states.input_datetime.time_bedroom_left_window_opened.state}}

Test: 01:45:24
inner mesa
#

better to use {{ states('input_datetime.time_bedroom_left_window_opened') }}. See the warning on that page

thorny snow
#

is it possible in yaml to evaluate whether the 'abcde' string contains the 'bc' substring?

hexed wing
#

Not in YAML

#

But it is possible if the option support templating with Jinja

#

{% if "bc" in "abcde" %}

thorny snow
#

sorry, I meant Jinja 🙂

#

instead of 'in', does 'includes' work in some way?

#

nevermind... I guess it's just the same

hexed wing
#

Yes it is 🙂

soft bough
#

why are you useing input datetime?

#

wouldn't a template sensor make more sens?

nimble copper
#

I have implemented a few single line template if statements. Is it possible to create an else if in the same manner?

{{ 'arrived' if trigger.to_state.state == 'home' else 'left' }}

nimble copper
#

Basically it'll only allow one statement that evaluates as true or false, and the returns either of the two text variables at the end of the {{ }} template? Thanks for clarifying!

hexed wing
#

I'm not sure if I follow that question

nimble copper
#

I think I kind of answered my own question 🤦‍♂️

hexed wing
#

even better 🤣

austere relic
nimble copper
#

Yeah that's right, trying to keep the code condensed and short. But it sounds like it's not possible with the condensed format I've used as it only allows for a boolean test.

hexed wing
#

trying to keep the code condensed and short.
I would advise against that btw...

#

Single line stuff may look condensed, but always harms readability

#

But... its taste 😄

#

I wish we had some ternary support in Jinja though

#

Especially if/else is happening a lot I guess

#
{{ is_state("device_tracker.frenck", "home") | ternary("yes", "no") }}
#

Would something like that be useful?

#

can also be used in expressions

#

e.g.

#

{{ (something == "unavailable") | ternary("yes", "no") }}

nimble copper
#

Yeah that would be handy.

austere relic
#

i like that too

nimble copper
#

A separate question, but is there a way to use jinja to create a grammatically correct list? I.e. I have a jinja list and I want to convert it to:

Item 1, item 2 and item 3.

#

I don't always know the length of the list, so if it's more than one item the and connector should be used on the final item.

austere relic
hexed wing
#

yes that works

#

Bam 🤘

nimble copper
#

🔥🔥🔥

hexed wing
stuck remnant
#

hello, I have a wake on lan template set up so that it hibernates a windows pc and also wakes it up

#

but I've recently noticed the switch isn't working anymore

#

the turn_off action triggers a service that ssh

#

I've tried the command in the terminal on the HA server and it works

#

but then tried the same service in HA gui and it doesn't trigger

#

the bare ssh command works from the terminal meaning it can't be the keys fault

#

anyone know why the service in HA would act up?

marble jackal
#

or.. 2022.2? I seem to recall 2022.1 will be skipped

silent barnBOT
tranquil eagle
#

Hi Guys! Sorry for this noob question.

I've tried this on the template demo and this works:

#

sensor:

  • platform: template
    sensors:
    livingroomtemperature:
    friendly_name: 'Living Room Temperature'
    unit_of_measurement: '?C'
    value_template: "{{ states('sensor.living_room_thermometer') | float / 10}}"
#

However I don't know where I could put in on my configuration.yaml

I would like to seek your assistance in helping me on where I should put it.

I have a LocalTuya Integration.

Thanks!

thorny snow
#

Hi guys

#

when doing a dict

#

is it possible to reduce this:

#

{"a": "ok", "b": "ok"}

#

a or b then ok

marble jackal
marble jackal
thorny snow
#

{"a or b": "ok"}

#

the right syntax for doing that

hexed wing
buoyant pine
#

What's the actual objective here?

thorny snow
#

I found another way of doing that

#

I was curious whether it was possible the do that

hexed wing
#

You are asking for a solution without the problem

thorny snow
#

like {"a/b": "ok"}

buoyant pine
#

Yes, but why

#

What are you trying to accomplish?

thorny snow
#

I like to learn ...

#

{% if states('input_select.ambivision_modes') in ['Intelligent (Capture)', 'Manual (Mood)', 'Level (Music)']%}
AmbiVision31
{% elif states('input_select.ambivision_modes') in ['Smooth (Capture)', 'Fireplace (Mood)', 'Mixed (Music)']%}
AmbiVision32
{% elif states('input_select.ambivision_modes') in ['Fast (Capture)', 'Rainbow (Mood)', 'Lamp (Music)']%}
AmbiVision33
{% elif states('input_select.ambivision_modes') in ['Average (Capture)', 'Nature (Mood)', 'Flash (Music)']%}
AmbiVision34
{% elif states('input_select.ambivision_modes') in ['User (Capture)', 'Relax (Mood)', 'Frequency (Music)']%}
AmbiVision35
{% endif %}

#

I was trying to achieve that with a dict

#

and some values repeat

buoyant pine
#

Got it. That's why we're asking why: the context is important

mighty ledge
#

that doesn't lend well towards a dictionary

thorny snow
#

I have a custom component that in its configuration has something like

#

wait

#

'{"Spotify": "3201606009684/rJeHak5zRg.Spotify", "Netflix": "RN1MCdNq8t.Netflix", "Rakuten": "vbUQClczfR.Wuakitv", "YouTube":"111299001912/9Ur5IzDKqV.TizenYouTube", "Prime Video": "3201512006785/evKhCgZelL.AmazonIgnitionLauncher2", "Mitele": "BTqpJutesE.Mitele", "Grabaciones": "My Content Browser", "Video USB": "mycontent-video-player", "Navegador": "org.tizen.browser", "Menu": "org.tizen.menu", "Reproduciendo Grabación": "Recoreded TV Player", "TV3 app": "PzkKxRdFT6.TV3", "HBO": "cj37Ni3qXM.HBONow"}'

#

this: "Spotify": "3201606009684/rJeHak5zRg.Spotify"

#

it allows one entry or several separated by a "/"

#

I was wondering whether it was possible to do it the other way around

#

if it were possible it would look clean in a dict

mighty ledge
#

it's not going to look clean with what you're trying to do

thorny snow
#

I think it would

#

if it were possible

#

something like {'Intelligent (Capture)/Manual (Mood)/Level (Music)': 'AmbiVision31'}

mighty ledge
#

juice is not worth the squeeze

#

somewhere, you'd have to map AmbiVision31 to each value of ['Intelligent (Capture)', 'Manual (Mood)', 'Level (Music)'] to make a dict work. So it defeats the purpose

#

either way, you have to write it out somewhere

thorny snow
#

nope

#

and index at the end

#

oh ok

#

I just realized ^^

#

the problem

#

I understand

mighty ledge
#
{% set items = {
  "AmbiVision31": ['Intelligent (Capture)', 'Manual (Mood)', 'Level (Music)']
  ...
  } %}
{% set ns = namespace(found=None) %}
{% for k, v in items.items() %}
  {% if states('input_select.ambivision_modes') in v %}
    {% set ns.found = k %}
  {% endif %}
{% endfor %}
{{ ns.found }}
#

any better? Not really.

#

mapping the other way...

{% set items = {
  'Intelligent (Capture)': "AmbiVision31"
  ...
  } %}
{{ items.get(states('input_select.ambivision_modes')) }}

However you'll run into issues if the modes share a name.

thorny snow
#

I understand

#

I mean, I don't understand you last posts but I do understand the issue

#

it is ok the way it is

mighty ledge
#

how do you not understand the last post? i'ts a one to one

#
{% set items = {
  'Intelligent (Capture)': "AmbiVision31",
  'Manual (Mood)': "AmbiVision31",
  'Level (Music)': "AmbiVision31",
  ...
  } %}
{{ items.get(states('input_select.ambivision_modes')) }}
#

it's probably the easiest thing to understand

thorny snow
#

one more thing

#

how can I convert hs to rgb?

#

the formula I mean

#

I want to do it whithin a template

#

is it already done somewhere in the forums or whatever?

mighty ledge
#

why don't you search

thorny snow
#

hoping to find a faster answer

#

on my way then

plush willow
#

I have a question about UTC times. I'm trying to format the UTC time for some goal:

  • platform: time_date
    display_options:
    • 'date_time_utc'

This:

{{ (as_timestamp(states('sensor.date_time_utc')) | timestamp_custom("%Y-%m-%d", true) ) | string }}

results in None. What do I wrong?

mighty ledge
#

here, I reformatted it to work outside my code. The hue goes from 0 to 255:

              {%- set hue = 255 %}
              {%- 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] %}
              {{ [ r, g, b ] }}
thorny snow
#

thanks a lot!

mighty ledge
#

maybe it's just 0 to 1

#

probably is

#

confirmed, it is zero to 1

#

soi f your hue value is 255 based...
{% set hue = value /255 %}
or if its 360 based
{% set hue = value /360 %}

mighty ledge
silent barnBOT
mighty ledge
# silent barn

Just make a trigger template with the sunset...

template:
- trigger:
  - platform: time
    at: "00:00:00"
  sensor:
  - name: Today Sunset
    device_class: timestamp
    state: "{{ state_attr('sun.sun','next_setting') }}"
#

the value of the sensor will be utc

plush willow
#

okay that looks much easier 🙂

mighty ledge
#

it goes in template, not sensor.

plush willow
#

thanks I will try it right now

mighty ledge
#

it triggers only at midnight

#

if you want it to trigger at restart, you can add a restart trigger and a tempalte reload trigger. However realize that if you restarti t after the next_setting, it will be tomorrows time

plush willow
#

indeed that was my next question....what about when the system is not running at 00:00:00

mighty ledge
#

it won't trigger

#

you can trigger it whenever you want

#

midnight makes the most sense.

#

either way, your other template wouldn't persist during restart anyways

plush willow
#

yes, but that piece of code of somebody else is dummy proof It will always work. I think that it is updated every second?

mighty ledge
#

no, it's updated once every ~3ish minutes

#

actually, no it would update once a minute

plush willow
#

okay, but back to my original question....Do you know why I cant format a utc time?

mighty ledge
#

Are you after midnight?

#

er sunset

plush willow
#

I'm living in the Netherlands...it is here now before midnight 16:09

#

and before sunset

mighty ledge
#

ok, so your template on restart will be unavailable until you hit midnight

#

wait, before sunset

#

ok, then your template should work

#

meaning this should work " {{ (as_timestamp(states('sensor.date_time_utc')) | timestamp_custom("%Y-%m-%d", true) ) | string }}"

#

however it's not really optimized

#
 {{ as_timestamp(states('sensor.date_time_utc')) | timestamp_custom("%Y-%m-%d", true)}}

is all you need

#

assuming you have sensor.date_time_utc as a sensor in your system

#

but you could always just not use that sensor

#
{{ as_timestamp(utcnow()) | timestamp_custom("%Y-%m-%d", true)}}
#

you don't even need to use utcnow

#

you could just use now

#

there's about 389472398473289 ways to solvethat

plush willow
#

🙂

#

okay your last statement works

mighty ledge
#

if the other doesn't that means sensor.date_time_utc doesn't exist

#

or you miss-spelled the name

#

or you didn't restart after adding that sensor

#

or the format is not a useable for as_timestamp

#

fyi, you can also use this

#
{{ utcnow().date() }}
plush willow
#

This results in None

{{ as_timestamp(states('sensor.date_time_utc')) | timestamp_custom("%Y-%m-%d", true)}}

mighty ledge
#

yes, read my reasons above

#

the syntax is correct

#

your sensor is not

plush willow
#

when I print the sensor value in the developer tools I see this

2021-12-10, 15:17

mighty ledge
#

that's not valid for as_timestamp

plush willow
#

it is something native from Home assistanokay

#

okay

mighty ledge
#

it needs to be an iso format timestring

plush willow
#

okay

#

maybe it should be coverted toutc as final step

mighty ledge
#

why do you need utc

#

a fully formatted timestamp is understood by all software usually

#

regardless of tz

plush willow
#

okay good question.. I thought that everything is done with UTC time. My final goal is in Node-RED in a function node compare the current date time with sunset_today datetime

#

there I use

new Date(Date.now());

according to me that is in UTC time

mighty ledge
#

that according is wrong

#

JS dates accept isoformats

plush willow
#

okay, then I will have to look there to use the ISO dates for comparison

thorny snow
mighty ledge
#

so all you need is...

template:
- trigger:
  - platform: time
    at: "00:00:00"
  sensor:
  - name: Today Sunset
    device_class: timestamp
    state: "{{ state_attr('sun.sun','next_setting') }}"
plush willow
#

yes that is a very clean option

mighty ledge
#

and if you want the restarts...

#
template:
- trigger:
  - platform: time
    at: "00:00:00"
  - platform: homeassistant
    event: start
  - platform: event
    event_type: call_service
    event_data:
      domain: template
      service: reload
  sensor:
  - name: Today Sunset
    device_class: timestamp
    state: "{{ state_attr('sun.sun','next_setting') }}"
plush willow
#

okay the only problem I see with this version is that (sunset is here at 16:29) so when I reboot after that time.. there is a wrong datetime in the sensor (the sunset of tomorrow so 2021-12-11)

mighty ledge
#

yep

plush willow
#

okay clear

#

okay I will choose something 🙂 But I don't understand why Home Assistant doesn't have both attributes (current_setting and next_setting). Maybe I have to create a feature request to built this native in the framework

anyway thanks for your help!

mighty ledge
#
template:
- trigger:
  - platform: time
    at: "00:00:00"
  - platform: homeassistant
    event: start
  - platform: event
    event_type: call_service
    event_data:
      domain: template
      service: reload
  sensor:
  - name: Today Sunset
    device_class: timestamp
    state: >
      {%- if is_state('sun.sun', 'above_horizon') %}
        {%- set t = (state_attr('sun.sun','next_setting') | as_datetime).time() | string %}
        {{ today_at(t.split('.')[0]) }}
      {%- else %}
        {{ state_attr('sun.sun','next_setting') }}
      {%- endif %}
#

but you'll still be off by 3 minutes.

mighty ledge
#

Why aren't you just using below_horizon and above_horizon anyways

#

that's the whole point of the sun.sun sensor

plush willow
#

okay strange that the team of HA not is willing to build it in......they have both values when they calculate it

#

what do you mean by "off by 3 minutes"?

mighty ledge
#

they do not have the previous when it's calculated

plush willow
#

okay

mighty ledge
#

the sunset changes by about 3 minutes every day

#

well, maybe it's half of 3 minutes

#

either way, it's not going to be correct with your timestamp

#

can you explain why you want todays sunset after it already occured?

plush willow
#

My project is:

I have an illumance sensor outside, it meassures ofcourse the lux. when the value is above 40K lux for 5 minutes my covers go down.. when below 40K lux for 25 minutes they go up.

This is the import part: it is allowed to operate for example 08:00-21:00 but when it is dark then that is the maximum operation time

But I think you are completely right.....the time is not import but below_horizon is all I need

mighty ledge
#

yep

#

that's why it exists

plush willow
#

okay 🙂

#

next_setting is only import when you will work with offsets I think. But for my project it is not necessary.

Thanks.

thorny snow
#

@mighty ledge , regarding the hs to rgb conversion template.. Is it possible to achieve whites with that template? (255,255,255)

mighty ledge
#

Hue doesn’t have a white conversion

buoyant pine
#

A/S/L

bright plaza
#

I keep getting a template sensor flipping from a valid number to "Unavailable" in my entity card. I have an availability template but clearly it's not working as it should

#

state in the states database is showing some rows with "Unavailable" as the state. What I want is those to not be accepted as state changes

#

Trying modifying my availability template to catch is undefined

inner mesa
#

There’s an issue in the current releases where the availability template will still evaluate the state even if false on startup. It’s fixed in 2021.12

bright plaza
#

I seem to be having weird issues. Is there any way to really monitor/log the result of a rest api call?

#

url works fine every time I try manually and get json back. But it seems very temperamental when HA calls it

thin vine
mighty ledge
thin vine
#

huraah!

marble jackal
mighty ledge
ivory pawn
#

Hello all, I have a Command line sensor and wanted to get some nested json values as attributes

    - dict1
    - dict1[0].value```
in the example, the first attribute (key dict1) works but the second fails. Is my syntax wrong or is this is not supported? Any ideas thanks
fossil venture
#

Try this:```
json_attributes:
- dict1
- dict1[0][value]

#

value has a special meaning in the template so you have to use square brackets.

#

Though I'm not sure if you can put a path in the attributes list.

ivory pawn
#

@fossil venture thanks , i gave it a try but it doesn't work. I also thought it might be that only top level keys can be used

fossil venture
#

The new Rest sensor format allows you to create multiple sensors from the one resource.

ivory pawn
#

thanks again, I had looked at json_attributes_path but for some reason cannot get my rest sensor to authenticate (maybe because it doesnt need a password but only a username.

#

which is why i moved to curl via command line

tranquil eagle
#

Hi @marble jackal ! Thank you for your response. I will ask this to #integrations-archived instead. Sorry for wrong posting. Will use the new template format. Have a great day!

red zinc
mighty ledge
sonic nimbus
#

how to check if my variable in the script contains multiple entities or just one?

#
  avr_media_player:
    description: "gets the correct zone player for avr"
    example: media_player.avr_zone1, media_player.avr_zone2
  volume:
    description: "sets the volume on the avr"
    example: "0.4"
  source:
    description: 'Correct source for playing audio - amplifier sources - AUX1,AUX2,Blu-ray,Bluetooth,SBB BOX,CD,DVD,Game,HEOS Music,Media Player,TV Audio,Tuner'
    example:  HEOS Music

sequence:
  - choose:
    - conditions: "{{not is_state(avr_media_player,'on')}}"
      sequence:
#

avr_media_player as you can see in example: can be for example like this: media_player.avr_zone1, media_player.avr_zone2 or just media_player.avr_zone2

#

so I want to wait for both entities to turn on, and then to continue with a script

dim eagle
#

Is there a way to have a template sensor not update its value if a condition isn't met?

{% if states('sensor.roborock_s7_last_clean_area')|int > 10 %}
  {{ ((as_timestamp(now()) - as_timestamp(states('sensor.roborock_s7_last_clean_end'))) / 86400)|round }}
{% endif %}

This works except when the template is updated and the if statement criteria isn't met, it's returning no value (None) but I want it to use the previous value it had.

dim eagle
#

Hm, looks like trigger-based template sensors might be what I need...

dim eagle
#

Ha, went full circle... ended up creating a input_datetime helper, then made an automation to update that based on a specific trigger, and finally created a template sensor to format it into a single digit days value. I bet there's an easier way but this is the only solution I could figure out 😆

austere relic
#

`template:

  • sensor:
    • name: test
      device_class: timestamp
      state: '{{ states("input_datetime.testtest") }}'`

now after the update I get a sensor.test rendered timestamp without timezone warning in the logs, and the sensor is not updated.
I can't figure out how it is supposed to look now.

austere relic
#

yeah can't make it work anymore, giving up for today

inner mesa
#

I think that's an issue that oughta be reported. If you pass a datetime into an input_datetime with timezone info, it's retained within the entity, but I don't think there's a way to get it back out again. The format used for the datetime state omits the TZ info, rather than presenting it in a proper ISO format that can be parsed back out again

#

there was a breaking change in 2021.12 regarding formatting timestamp_local and timestamp_utc in ISO format with tz info, and I think there are more places that it needs to be done

inner mesa
dim eagle
#

Is it possible to update an entity state through templating?

inner mesa
#

Not without using a python script. But why?

#

You’re just fighting the integration that provides the entity

dim eagle
#

I created a template sensor and an input_datetime helper entity. The input_datetime helper is just my way to persist a date/time stamp between HA restarts and it's being updated through an automation. I was wondering if I could just use a template trigger to update the input_datetime state instead of the automation (it would be doing the same thing, just eliminates needing to create a dedicated automation for this).

inner mesa
#

You can

dim eagle
#

It doesn't seem like there's a way to persist a template sensor state through an HA reboot without using a custom integration variable... or a helper

inner mesa
#

The template will be evaluated on startup

#

Are you saying that you would have a trigger-based sensor with the state being derived from the trigger variable and you want the state to persist between triggers, even across a restart?

#

That would make sense

dim eagle
#

This is the template trigger I'd like to use:

template:
  - trigger:
      - platform: numeric_state
        entity_id: sensor.roborock_s7_last_clean_area
        above: 100
    sensor:
      - name: Last Complete Vacuum
        unit_of_measurement: "day(s)"
        icon: "mdi:calendar-star"
        state: "{{ ((as_timestamp(now()) - as_timestamp(states('sensor.roborock_s7_last_clean_end'))) / 86400)|round }}"
#

It will only update when that trigger hits, which is what I want, but when I restart HA, it sets it back to Unknown. I basically want to persist the state before a restart.

#

Couldn't figure out a way except for creating a separate helper entity and storing the value there.

inner mesa
#

I see

dim eagle
#

The state is a datetime state

inner mesa
#

Might want to report that

#

It doesn’t look like it derives from RestoreEntity

dim eagle
#

Ah, so no way to retain the state other than store it in another entity (like input_datetime helper). Not a huge deal, how I have it set up now works... although I do wonder if I could just update the helper entity from the sensor template (to get rid of the automation).

inner mesa
#

I don’t think so. It’s not a script

icy thistle
#

Is there a template button integration

#

like template switch to create custom entities

fossil venture
edgy umbra
#

Anyone know whats wrong with this? 🙂

#

return (entity.attributes.source) + ' • ' + (Math.round(entity.attributes.volume_level / 0.01) + '%' ;

pastel moon
edgy umbra
#

Fixed

#
    [[[
      return (entity.attributes.source) + ' • ' +  ( Math.round(entity.attributes.volume_level / 0.01)) + '%' ;
    ]]]```
proud lark
#

for solar automation: how to assign a teoretical power number based on sun elevation?

icy thistle
inner mesa
#

Where do you plan to use this button?

silent barnBOT
austere relic
plush willow
#

Okay

austere relic
#

maybe @inner mesa knows more, I'm just a noob 🙂

inner mesa
#

please don't

austere relic
#

sorry

mortal monolith
#

I have this {{ state_attr('sensor.github_zwavejs','latest_release_tag') != states('sensor.zwavejs2mqtt_version') }}

#

problem is I need to add a "v" to states('sensor.zwavejs2mqtt_version')

inner mesa
#

‘v’ ~

mortal monolith
#

thanks!

fossil venture
icy thistle
inner mesa
#

you could just write a tiny script

icy thistle
#

wdym?

inner mesa
#

i only need the button to generate a custom event that's all

#

you can do that with a tiny script

icy thistle
#

it's just one command but how do i put it into entities card

inner mesa
#
    - event: pump_timer
#

put the script in an entity card

#

or, as recommended, just use a button card and call the event directly

#

or whatever

icy thistle
#

oh that, but is there a service for running shell scripts?

inner mesa
#

your requirements keep changing

icy thistle
#

i just need to run a single command to ssh into my machine and do stuff

inner mesa
#

what exactly are you trying to do?

#

ok, that's quite a bit more than

#

i only need the button to generate a custom event that's all

icy thistle
#

i'm unused to the jargon i suppose, sorry

#

and i did the worst mistake you can do on support channels - asking something without telling the whole story 😦

inner mesa
#

it sounds like you want shell_command

#

and there are several comprehensive threads on the forum about how to ssh to another machine and run stuff

icy thistle
#

yeah i figured that out a while ago but i think most threads discuss the ssh-ing part and now how to integrate it in the best way

#

i think most people make a template switch but i don't want that

inner mesa
#

I don't have any shell_command entities right now, but I'm sure they can be added to an entities card as well

icy thistle
#

yeah i think shell_command will work, thank you for your help

#

although an integration to add custom buttons would still be better for these usecases i feel

inner mesa
#

I think it comes down to what you would actually do with them, and I suspect that there are usually better options

#

like, use the shell_command by itself, rather than further encapsulating it in a button entity which serves no additional purpose

#

if you can come up with a compelling case for a manual button entity, I'm sure the devs would appreciate a post in the feature request forum

icy thistle
# inner mesa like, use the shell_command by itself, rather than further encapsulating it in a...

well, right now, I have this in my configuration.yaml

switch:
  - platform: command_line
    switches:
      pc_power_off:
        command_off: "ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no user@ip sudo poweroff"
  - platform: wake_on_lan
    mac: mymac
    name: "pc-power-on"

this creates 2 switches with no state checking which only work partially because each can only do one thing. for these i will need to create scripts, to replicate the functionality of buttons. to me it seems more logical to skip the step with making scripts and just create button entities directly.

#

and yeah i will make a forum post about it

#

thanks for the suggestion

#

and i figured since i have these i don't really need shell command

inner mesa
#

well, the switch with just a "turn_off" part is a little weird, and a shell_command would be more fitting if you always only want to send one command to turn it off

#

I think you'll find that it's pretty much the same as any theoretical button entity

median ridge
#

I have a rest sensor which gets the serial number of a device in my network. The serial number is 16 digit number. In the entities card it is treated as a rather large number and given thousands separators (e.g. 1,234,567,890,123,456 instead of 1234567890123456). Is there any way to stop this from happening? Can my value template be altered to treat the serial number as a string?

icy thistle
inner mesa
#

It could expose a button entity, but the docs explain why it’s a switch. I guess you could use a manual button entity for that

cinder lotus
#

Configuration question. What's wrong with this configuration.yaml code:

  - sensor:
      - name: "power_distri"
        device_class: "energy"
        unit_of_measurement: "W"
        state_class: "measurement"
        state: >
          {% set delivered = states('sensor.power_delivered') | float)  %}
          {% set returned = states('sensor.power_returned') | float)  %}
          {{ (delivered - returned) }}```
#

It seems I screwed up my configuation.yaml
The configuration check passed with below (shorted) configuration:

    - platform: time_date
      display_options:
        - 'time'
        - 'date'

    - platform: template
      sensors:

        date_templated:
          value_template: "{{ now().strftime('%d %B %Y') }}"
          friendly_name: ''```
#

This config passes without any problem but I believe I mixed up 2 things. Anyway, I'm not sure. May I use
- platform: template in the sensor section?

#

I don't understand all the differences...

#

When I copy/paste the first code I've posted, I get errors when I check my configuration:

Source: config.py:464
First occurred: December 12, 2021, 2:59:50 PM (10 occurrences)
Last logged: 10:17:23 AM

Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['power_grid']['value_template']. Got "{% set delivered = states('sensor.power_delivered') | float) %} {% set returned = states('sensor.power_returned') | float) %} {{ (delivered - returned) }}". (See /config/configuration.yaml, line 122). Please check the docs at https://www.home-assistant.io/integrations/template
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][0]['state']. Got "{% set delivered = states('sensor.power_delivered') | float) %} {% set returned = states('sensor.power_returned') | float) %} {{ (delivered - returned) }}\n". (See /config/configuration.yaml, line 278).
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][0]['state']. Got "{% set delivered = states('sensor.power_delivered') | float) %} {% set returned = states('sensor.power_returned') | float) %} {{ delivered - returned }}\n". (See /config/configuration.yaml, line 278).
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][0]['state']. Got "{% set delivered = states('sensor.power_delivered') | float) %} {% set returned = states('sensor.power_returned') | float) %} {{ delivered- returned }}\n". (See /config/configuration.yaml, line 278).
Invalid config for [template]: [date_templated] is an invalid option for [template]. Check: template->sensor->0->date_templated. (See /config/configuration.yaml, line 123).```
silent barnBOT
#

@cinder lotus 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://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

sonic oracle
#

@cinder lotus I already responded to your github issue with the solution but just for completion:
There are some opening brackets missing in line 7 and 8.
A slimmer solution would be

template:
  - sensor:
      - name: 'power_distri'
        unit_of_measurement: "W"
        state: "{{ (states('sensor.power_delivered') |float) - (states('sensor.power_returned') |float) }}"
cinder lotus
silent barnBOT
cinder lotus
#

I had to remove some text but it was send before I was aware of it

#

Who can clarify for me sections and 'sub-sections', I know this is not the correct word for it but I'm very confused now

#

@sonic oracle , I've copy/paste your code in the 'root' of configuration.yaml and it worked. But... I've got 0,20 Watt indication, this should be 200 Watt. The value is in kW and should be in Watt so X 1000.
I changed state: "{{ (states('sensor.power_delivered') |float) - (states('sensor.power_returned') |float)
to
state: "{{ (states('sensor.power_delivered') * 1000 |float) - (states('sensor.power_returned') * 1000 |float)
but the sensor doesn't give any data now...

#

Why is anything so difficult...

#

I've checked sensor.power_delivered and this sensor gives the value in Watt. Strange that it becomes kW in the template

bright plaza
#

Struggling to find correct selector for json_attributes on a rest sensor. The JSON that is returned is effectively:

#
{
   "device":{
      "State":"running",
      "Status":"Up 18 hours"
   }
}
#

so I'd have thought :

#
json_attributes:
  - device.Status
#

But it doesn't seem to work

#

I've also tried - status: '{{ value_json.device.Status }}'

marble jackal
#

@cinder lotus your code should not be placed under sensor: or in sensor.yaml because it is not part of the sensor integration, but the template integration. But as your template itself is correct, this is more a topic for #integrations-archived

bright plaza
#

yeah, I've figured that you can't do anything but top level attributes with json_attributes. I've moved it to template sensor and just about got that working now

cinder lotus
#

But it seems the way you make the code is different

marble jackal
#

Yes, that will work, but what you posted earlier is the new template sensor format, which is part of the template integration and not of the sensor integration

cinder lotus
#

Will read and try to understand...

soft bough
#

ok so i got this automation: https://pastebin.com/p0fB0TTc
but i get error : Template variable error: 'context' is undefined when rendering '{{ 'CONFIRM_' ~ context.id }}'

#

its based on the actionable notification automation for the companion app

buoyant pine
bright plaza
#

are all states stored as strings?

inner mesa
#

Yes

bright plaza
#

that explains why | int on a value template to store a state into a sensor still means it comes out as a string later then

#

so - if I history graph a sensor like that and it gives me coloured horizontal bars for every different number - how do I get that to graph properly? For some other sensors I have used unit_of_measurement. But there doesn't appear to be a unit_of_measurement for "just a number"

inner mesa
#

unit_of_measurement is the answer. It doesn’t matter what you give it

#

Could be a space, I think

bright plaza
#

I'll try

#

yup that seems to work. Thanks 🙂

pallid ibex
#

good evening, anyone know how to change it to float?

#

{{ states('sensor.pv_ac_l3_voltage') }}

#

i received state like "117.4"

#

from mqtt sensor.

inner mesa
#

{{ states('sensor.pv_ac_l3_voltage')|float }}, but I have a feeling that there's more to your question...

silent barnBOT
brazen stone
#

Hi, I'm struggling with the statistic changes that have come with 2021.12. I've had a sensor monitoring Internet bandwidth working for ages using the change_rate sensor attribute provided through the old statistics module but I can't get it to work under 2021.12

I've added state_characteristics to the sensor (sensor still works providing raw data) but then whenever I try to use it in a template, I get an error of invalid input 'None' when rendering template and when using Developer Tools I don't get any attribute of the sensor for change_second.

extract from my sensor.yaml

https://hastebin.com/refofiveku

plusnet_rx is fine and has the raw data but plusnet_rx_mbps is giving me the error (hence is always 0)

Any thoughts?

mighty ledge
brazen stone
mighty ledge
mighty ledge
brazen stone
brazen stone
brazen stone
cinder basin
#

Hi guys. im getting this error: The 'value_template' option is deprecated, please replace it with 'state_value_template'. i have one light on mqtt

#

how do i fix it