#templates-archived

1 messages Β· Page 119 of 1

mighty ledge
#

email contents that is

copper seal
#

Here you have the returned xml file from GET request to the camera

#

And my template

#

If it helps, the error:
Logger: homeassistant.helpers.entity
Source: helpers/template.py:1214
Update for switch.cam_piscina_mail fails

mighty ledge
#

@copper seal expand the error by clicking on it to reveal the full error.

copper seal
#

Can I add a pic of full error?

mighty ledge
#

You can just copy / paste the error?

silent barnBOT
mighty ledge
#

You have to add a check to validate that you actually have information in value

#

it's erroring out because the regex is failing on an empty string

#
{% if value %}
{% set status = value | regex_findall_index('(?<=id>).*?(?=<\/id>)') %}

{% if status == "email" -%}
true
{%- else -%}
false
{%- endif %}
{% else %}
false
{% endif %}
#

It also helps if you properly indent so you can see your logic

#
{% if value %}
  {% set status = value | regex_findall_index('(?<=id>).*?(?=<\/id>)') %}
  {% if status == "email" -%}
    true
  {%- else -%}
    false
  {%- endif %}
{% else %}
  false
{% endif %}
copper seal
#

Still got the error

#

😩

mighty ledge
#

Then the contents contain other information and regex is not finding a result

copper seal
#

Is there a way to check the content on HA? On win cmd using curl I get that xml code

novel crystal
#

Hi all. Unsure if this is the right channel but here goes. On my current system I have some logic to "record" today max / min values (for a temperature sensor), 7 days history rainfall, and so on. I use this, e.g. to decide whether I need to turn on the sprinklers. E.g. if today temperature was above > say 28 then water the grass no mater what. I also know each m2 of grass needs Xm3 of water per Y days so based on rainfall history I can decide if the grass needs to be watered or not...anyway was trying to understand what's the best way to store this data. I was thinking about custom attributes but for what I could gather I'd need to manually create these attributes on every device I'd want to monitor plus would also need to create an automation per device to update the attributes accordingly. Is there anyway to just create a "template" for every temperature sensor for example that would automagically do this?

mighty ledge
#

then your template would just be:

{{ value | regex_search('(?<=id>)email(?=<\/id>)') }}
#

that returns true/false if <id>email</id> exists or not.

copper seal
#

It solved!!!!

#

Many thanks petro

robust ermine
#

hey I'm trying to figure out how to get the datetime units here converted to int so i can do <= & >=. Any hints?: {% set start = (now().timestamp() * 1000) | int %}
{% set end = start + 86400000 %}
{{ state_attr('weather.openweathermap', 'forecast') | selectattr('datetime', '>=', start) | selectattr('datetime','<=', end) | map(attribute='temperature') | list | max }}

#

i know there's an as_timestamp function, but not sure how it would fit in here

mighty ledge
strong idol
#

Hi everyone, how can I check if a timestamt (attribute of an entity) is two days older than now() ?

robust ermine
mighty ledge
#

seems like 'datetime' would be a string

robust ermine
#

yeah doesn't work in the template tester, says: TypeError: '>=' not supported between instances of 'datetime.datetime' and 'float'

dreamy sinew
#

just make start now() and call it a day

#

then you'd be comparing 2 datetimes

#

set end to now() + timedelta(days=5) or whatever

strong idol
#

That is a good hint, I need something like

strptime(state_attr('sensor.some_sensor','timestamp'), "%d-%m-%Y").timedelta(days=2)

But this returns: UndefinedError: 'str object' has no attribute 'timedelta'

dreamy sinew
#

you'd need to know the actual value of that attribute

strong idol
#

The value is set by the integration, it is e.g. "2021-02-09 09:07:37.356957"

dreamy sinew
#

it might already be a datetime

#

do state_attr().day

#

if that returns something you can skip the strptime stuff and just use it directly

strong idol
#

It returns UndefinedError: 'str object' has no attribute 'timedelta'

dreamy sinew
#

that's not what i asked you to do

strong idol
#

Oh sorry

#

This is not returning any error, but an empty string (or nothing)

dreamy sinew
#

oh, try .date()

#

you're using the template tester right?

strong idol
#

correct

dreamy sinew
#

all of this works

strong idol
#

It doesn't work for my sensor: UndefinedError: 'str object' has no attribute 'date'

dreamy sinew
#

then you need to do a proper strptime() then

robust ermine
#

aha thanks @dreamy sinew

dreamy sinew
#

@strong idol '%Y-%m-%d %H:%M:%S.%f'

#

you have the parse the entire thing even if you don't need all of it. otherwise it doesn't know what you are doing

strong idol
#

This time it works: {{ strptime(state_attr('sensor.some_sensor','timestamp'), '%Y-%m-%d %H:%M:%S.%f').date() }}
This is returning the date correctly

dreamy sinew
#

yep because now you have a proper datetime object

#

without the .date() you can do timedelta now as i showed in my example

sonic nimbus
#

how to put it right: - conditions: - '{{ event == 1002 }}' - '{{ is_state('media_player.spotify_stefan', "playing") }}'

strong idol
#

Ok, let me try

sonic nimbus
#

when I remove single quotes from media_player.spotify_stefan I have an erorr in my logs

dreamy sinew
#

you're mixing quotes

sonic nimbus
#

Error during template condition: UndefinedError: 'media_player' is undefined

dreamy sinew
#

convention says to use " outside your template and ' inside

#

fix that

strong idol
dreamy sinew
#

because that's not how i used it in my example

sonic nimbus
#

Still the same

#

I changed single and double quotes

#

here is the script

strong idol
#

Almost there ... can I somehow only get y-m-d from now()?

dreamy sinew
#

same idea. .date()

#

but you should do the comparisons with the full objects

#

they have actual numerical handling if you compare them directly. If you convert to the strings you're at the mercy of string math

sonic nimbus
#

it works πŸ™‚

#

thanks @dreamy sinew

strong idol
#

Still not there πŸ˜‚ Feels like this is impossible to solve.

#

I am using: {{ (strptime(state_attr('sensor.some_sensor','timestamp'), '%Y-%m-%d %H:%M:%S.%f')) < (now() + timedelta(days=-2)) }}
to check, if the first timestamp is older than now() minus two days.
This returns: TypeError: can't compare offset-naive and offset-aware datetimes

dreamy sinew
#

oh, use utcnow() instead

#

we're missing a timezone so its getting cranky

strong idol
#

Still getting the same error, also with utcnow()

dreamy sinew
#

this works

#
{{ sensor < (utcnow().replace(tzinfo=None) + timedelta(days=-2)) }}```
#

should probably still use utcnow() though

#

depending on what the sensor actually uses

#

@strong idol

strong idol
#

This works! πŸ₯³ Thank you so much!!

#

Is it a bad idea to put everytthing in one line, like:
{{ (strptime(state_attr('sensor.some_sensor','timestamp'), '%Y-%m-%d %H:%M:%S.%f')) < (utcnow().replace(tzinfo=None) + timedelta(days=-2)) }}

dreamy sinew
#

not really. just makes it harder to read

strong idol
#

Ok, sounds good. Thanks a lot - I am gonna put this to use now. πŸ™‚

silent barnBOT
novel crystal
#

that "template" is being treated as text and not rendered so clearly I'm missing the point

mighty ledge
#

No, you have to create a template sensor

#

there's no way to change states of things without creating new entities

novel crystal
#

thank you @mighty ledge. so much to learn!

#

trying to figure out what's the best way to, for example, keep track of daily max / min temperature readings for all temperature sensors

ivory pawn
#

Hello all, is there a way to apply wildcard to the entity_id in a service data template? Ie. apply the service to all entities in the light domain that include the number 1 in their id. I have tried using a light group but some of the special light attributes do not pass through a group.

#

OR , can I use a condition to choose which entities are applied?

dreamy sinew
#

{{ states.light|map(attribute='entity_id') }}

night imp
#

Anybody got a good video on templates they would recommend

silent barnBOT
#

Videos are great to watch but are usually out of date QUICK.... Best to read the DOCS

dreamy sinew
#

in this case

silent barnBOT
dreamy sinew
#

but also check the HA docs for templates

#

there are a few HA specific extensions that are exposed

atomic dust
#

In a template sensor, is there a way to keep the existing value of the sensor on a if/else branch?

#

I'm using a unifi controller to do some room presence detection, and when a phone isn't connected to an AP, I'd like the ap sensor to just retain the last AP

#

value_template: >-
{% if state_attr('device_tracker.pixel4a', 'ap_mac') == '74:ac:b8:82:05:e9' %}
living
{% elif state_attr('device_tracker.pixel4a', 'ap_mac') == '74:ac:b8:82:04:40' %}
studio
{% elif state_attr('device_tracker.pixel4a', 'ap_mac') == '74:ac:b8:82:06:c2' %}
garage
{% else %}
none
{% endif %}

#

When I remove the "{% else %} none", it blanks the template sensor, instead of keeping the last living/studio/garage value

dreamy sinew
#
{% set map = {'74:ac:b8:82:05:e9': 'living', '74:ac:b8:82:04:40': 'studio', '74:ac:b8:82:06:c2': 'garage'} %}
{{ map.get(state_attr('device_tracker.pixel4a', 'ap_mac'), 'none') }}
#

probably not though. this will update whenever that attribute updates

#

you'd need to enable an automation to set an input bool to store previous values

atomic dust
#

OK, i see a solution with two entities

dreamy sinew
#

and then you can replace the 'none' with states('input_bool.ap_store')

#

sub in that entity id for whatever it actually is

atomic dust
#

Thanks for the dictionary idea, much cleaner.

dreamy sinew
#

yeah, i'm a fan of those

#

and you only have to pull the value of the attribute once

#

though you could set it to a var and run your checks that way if you wanted

#

fun little tricks where the python pokes through the jinja

atomic dust
#

Yep, I was struggling a lot with jinja until I found the dev tools template editor, helps a lot with wrapping python

#

I wonder if a self reference will work, can't try it until later, but:

#

{{ map.get(state_attr('device_tracker.pixel4a', 'ap_mac'), states('sensor.pixel4a_ap')) }}

#

where sensor.pixe4a_ap is the template sensor itself

dreamy sinew
#

Circular reference will not work

atomic dust
#

Right. Maybe I just drop the template sensor entirely for this. Automation triggering on attribute change, updating an input_text instead.

dreamy sinew
#

Probably for the best

atomic dust
#

Cool, thanks for your help!

peak juniper
#

Can anyone help me create a template sensor to parse data from a CSV file?

#

can't seem to find any helpful docs

#

data looks like this

deft timber
#

If you use a File sensor, you will only have access to the last line of the file (that you can parse afterward with a template sensor). I don't think you will be able to store the entire file in an entity. If you want some specific value in the files, you can use a command line sensor, and in the command you can get what you want with tools like cut, tail, head, ...

peak juniper
#

ah so what you're saying is if there are 18 records in there I'll only be able to look at that last line with a record with a file sensor?

deft timber
#

Only the last line of the file is used

#

btw the state of an entity is limited to 255 characters

mint viper
#

for an event that has one of the data entries is an array how do i traverse the array after this trigger.event.data.args?

thin vine
#

that's kinda a broad question, what do you want to do with the data, use it as a condition, send it to a notification, something else?

mint viper
#

ok here is the data component of the event:

"data": {
        "device_ieee": "",
        "unique_id": "",
        "device_id": "",
        "endpoint_id": 1,
        "cluster_id": 8,
        "command": "move",
        "args": [
            0,
            84
        ]
    }

the first arg specifies the button pressed. so to use it as a trigger or condition i need to filter for that value. how would i do that?

dry silo
#

Hello all, I have a template sensor that calculates a number out of two sensors. It works great, but as it has to do with solar power production i want it to behave different then it does atm. Now it reports the same number from when the inverter goes offline, till it goes online again. Is there a option to add a comparison and a reset at midnight inside the template ?

ivory delta
#

Templates don't 'reset'. They are evaluated whenever any of the entities they reference change.

ashen agate
#

Hello, I try to display my router upload/download per day in "GB" my router display it in bytes, my template sensor value_template: "{{ (states.sensor.fritz_netmonitor.attributes.bytes_sent|float / 1073741824 | round (2)) }}" It displays me 1,1402727728709600 GB

#

Can you tell me whats wrong here? I only want to see "1,14 GB"

mint viper
#

how would i go about mapping a 0-100% range to a 255 brightness value?

ashen agate
dry silo
glossy viper
#

if this helps,,,u can set a sensor to keep your template....and have an automation running just before your 24h expire and to store that data

white owl
#

What's the secret to getting zwavejs2mqtt updates to a light entity created via light (platform: mqtt)? The topic (both state, command and availability) comes through ok if I subscribe to them in hass, but my light entity just doesn't update..

  name: 'Hallway-Lamp2'
  state_topic: 'zwave/Hallway/Lamp/37/0/currentValue'
  command_topic: 'zwave/Hallway/Lamp/37/0/targetValue/set'
  availability_topic: 'zwave/Hallway/Lamp/status'
  #availability: 
  #  payload_available: 'true'
  #  payload_not_available: 'false'
  #  topic: 'zwave/Hallway/Lamp/status'
  payload_on: 'true'
  payload_off: 'false'
  #optimistic: false
  #qos: 0
  retain: true```
dry silo
glossy viper
#

well...i try to write something meaningfull in text then send to you

dry silo
#

cool, thanks! I can send you the two calculation templates in pvt if that is helpfull ?

glossy viper
#

tried to order them

dry silo
#

I think i can follow all the sections so that is a good start ! πŸ˜„

ivory pawn
dry silo
#

@glossy viper That doesn't change anything. I think i have to change my calculation all together.

#

The problem i have is that one of the two sensors keeps the last known number. So even when the other sensor resets at midnight (which it does, it comes out of our smartmeter) it starts calculating with the old number πŸ˜…

austere relic
#

I want to replace the "1" in "background: rgba(0, 165, 0, 1)" with the **size **of a state array.

ivory delta
#

Uh... why? The alpha channel is a percentage. It goes from 0-1. What's your goal?

austere relic
#

it could also check if array site is at least 1 and print 1, but everything above 1 is equal to 1 anyway πŸ™‚

#

but that seems more complicated, so I tried to do the easiest solution (for now). just can't get to work to replace that little number

silent barnBOT
austere relic
#

I'm desperate trying to figure out how to count the size of an array.

fossil hearth
# silent barn
    Single
{% elif  '0006!01' in my_test_json.SW1 or  'Double' in my_test_json.SW1 %}
    Double
{% elif  '0006!00' in my_test_json.SW1 or  'Long' in my_test_json.SW1 %}
    Long
{% endif %}

Solved

ivory delta
#

So almost what Tinkerer suggested:
{{ state_attr('sensor.seventeentrack_packages_delivered','packages') | length }}

austere relic
#

they both seem to work

#

to access the previous state, I have to combine this with trigger.from_state and trigger.to_state somehow (and thus can't test it with templates anymore, is that correct?).

#

I think it's something for another day, brain is sad I keep feeding him

ivory delta
#

Of course you can use templates. That's why I suggested them.

#

The page I linked in the other channel was about templates in automations... they explicitly show uses of trigger.

austere relic
#

{{ states.sensor.seventeentrack_packages_delivered.attributes.packages | length }}
also works. isn't this like the new way?

ivory delta
#

No...

#

Use the helper functions wherever possible.

austere relic
#

ok πŸ™‚

ivory delta
#

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).

austere relic
#

it just looks cleaner πŸ˜„

ivory delta
#

That's... debatable...

dreamy sinew
#

yeah, debatable

#

use the helpers

#

stability > looks

#

despite what apple thinks

austere relic
#

{{ ((state_attr('trigger.from_state','packages') | length) - (state_attr('trigger.to_state','packages') | length)) > 0 }}
should it look something like this (if sensor.seventeentrack_packages_delivered is the trigger) ? can't test that anymore in the template tab

dreamy sinew
#

you're mixing things

austere relic
#

I completely agree πŸ˜„

dreamy sinew
#

in this case you do need to use the hard access

#

it protects against the main concern by having to actually exist to do the trigger

#

trigger.to_state.attributes.packages

austere relic
#

is there a state missing after to_state? (my example from docs shows that)
if I got it right (won't be the case I guess), I can use it even as value template in the trigger itself.
value_template: "{{ trigger.from_state.state.attributes.packages | length) - (trigger.to_state.state.attributes.packages | length) }}" above: 0

#

it's my last try for today, new day brings new hope I guess

ivory delta
#

No. trigger.to_state already represents a state object.

#

You want the attributes of that state object, you acces trigger.to_state.attributes

austere relic
#

value_template: "{{ (trigger.from_state.attributes.packages | length) - (trigger.to_state.attributes.packages | length) }}" above: 0
that could work? hard to test, I don't even know how often seventeentrack sensors updates

austere relic
#

it doesn't. thanks for your help so far! have to give up for today

austere relic
#

damn I could not give up yet. I'm afraid I will never finish it if not now. I guess I just wanted to force it into a value_template but trigger.from_sate and to_state are probably not available in the trigger section. As I was told before to do that in the condition section and fixed my math this works now:
{{ (trigger.to_state.attributes.packages | length) - (trigger.from_state.attributes.packages | length) > 0 }}

hot coral
#

is there a way to assign a template sensor to an area?

#

maybe by adding an attribute via 'entity customizations'?

#

assigning unique_id lets me assign area

thin vine
mint viper
#

thanks

glossy viper
#

to have sensors from entity states i must have template for every state, isn't it ?

ivory delta
#

States are already easy to access. Do you mean attributes?

glossy viper
#

always right πŸ™‚

#

attributes

ivory delta
#

It depends what you're trying to do with them and where you want to use them.

glossy viper
#

in a card to have direct view

ivory delta
#

Some custom cards might let you access attributes. Otherwise, make a template sensor.

glossy viper
#

dev tools aren't returning anything

thin vine
#

'BMI' != 'bmi'

glossy viper
#

oh..case sensitive...still not returning {{ state_attr("bodyscale.adrian","BMI") }}

#

sorry...i'm....guilty

thin vine
#

and this is output op devtools -> states?

glossy viper
#

yes

#

so dumb that wasn't paying attention to entity called bodymiscale

#

now returned the attribute

#

i can name the same template sensor ? because i will have 2 sets of same attributes, for different entities

thorny snow
#

Could somebody help me out with a shell_command template please. I'd like to delete some camera image files older then X days. The X is stored in an input_number. Here is the code copied and modified from a working command_line switch: 'find /config/www/camera_images/ -maxdepth 2 -type f -mtime +{{ states("input_number.kamera_fenykepek_lejarati_ido") }} -exec rm {} -f ;'
This one gives an error: Error running command: ..... return code: 1 NoneType: None

thin vine
#

if you put {{ states("input_number.kamera_fenykepek_lejarati_ido") }} in devtools -> template, what output do you get

thin vine
glossy viper
#

then i have to use customize to have the same name for different entities attributes

thorny snow
#

The entity state returns 1 I've verified that. That is OK.

thin vine
#
shell_command:
  somecommand: "find /config/www/camera_images/ -maxdepth 2 -type f -mtime +{{ states('input_number.kamera_fenykepek_lejarati_ido') }} -exec rm {} -f ;"
#

that's how it looks in your config?

thorny snow
#
{% set value_json=
{"step":"10",
"light":"light.test",
}
%}


{{(state_attr([value_json.light],'brightness')|int(0)/255|int(0)*100)|round(0)-[value_json.step]}}```AttributeError: 'list' object has no attribute 'lower'
glad geode
#

Hi all, how do I access device data in a device trigger automation?
I want to fire an event with some data about the device

thorny snow
thin vine
mighty ledge
#

That can be simplified without all the int casts and using int division.

{{ state_attr(value_json.light,'brightness') | int // 255 * 100 - value_json.step }}
thin vine
#

true, just fixed the error(s)

humble beacon
#

Hello. Is there a way to get "trigger.to_state.state != trigger.from_state.state" for two entities?

#

I have the following trigger in an automation:

    - platform: state
      entity_id: 
        - device_tracker.aaa
        - device_tracker.bbb
#

If the state from one of this device_tracker changes, the automation fires. Can I add a condition, that the automation only fires if the state is different?

thin vine
#

different how? if the two device trackers are different, or if the previous state of one tracker is different from the new state?

humble beacon
#

Yes. The automation should only fire if the previous state of one tracker is different from the new state.

thin vine
#

Not sure if this is needed, I believe they should always be different to begin with

condition:
  condition: template
  value_template: "{{ trigger.from_state.state != trigger.to_state.state }}"
humble beacon
#

This is not working.

#

I tried this already.
The automation fires every time, one of this device.tracker is changing his state.

#

If device_tracker.aaa is home and device_tracker.bbb change his state from home to not_home, the automation should fire. If device_tracker.aaa change his state also to not_home, the automation should not fire.

thin vine
#

ah! so only if device aaa is different from device bbb

#
condition:
  condition: template
  value_template: "{{ states('device_tracker.aaa') != states('device_tracker.bbb') }}"
humble beacon
#

If I use {{ states('device_tracke.aaa') and states('device_tracker.bbb') }} in the template editor I have the behavior what I want. For this I am trying to get "trigger.to_state.state != trigger.from_state.state"

#

I think the easiest way is to create a group from this two device_trackers. But I am searching for a the without to create a group.

dreamy sinew
#

the to state will never match the from state otherwise it wouldn't even trigger with your trigger def

#

your trigger def says "when either of these change"

#

Magie's solution will work. Group would be easier to manage

thorny snow
#

how do i get a lights color using a template

jagged dune
#

Hello.How can the weather sensor convert km / h to m / s and pressure hPa to mm Hg?

ivory delta
#

Just make a new template sensor to do the math. Let's say a is your speed in km/h, your template for m/s would just be this:
{{ a * 1000 / 3600 }}

#

And I don't know the conversion for hPa to mm Hg but it's going to be a similar solution with different numbers.

glossy viper
#

hpa to mm hg is 0.7....wait for my ha to start

fossil totem
#

@thorny snow {{state_attr("light.some_color_light_you_have_deployed", "rgb_color")}}

glossy viper
#

hpa *0.75006156130264 = mmHg

fossil totem
#

that might be a few sig digits past your sensor resolution πŸ˜›

glossy viper
#

sure...my formula includes a parse int

dreamy sinew
#

should |round instead

glossy viper
#

where?

dreamy sinew
#

if you're casting to int you should round instead

#

otherwise you're just chopping of the decimals

glossy viper
#

well..no

#

${parseInt(stateObj.attributes.pressure*0.75006156130264)}
<span class="unit">
mmHg

dreamy sinew
#

oh, if you're in js land who knows

#

they do all sorts of dumb shit over there

glossy viper
#

:)))))))

#

well...is a customa animated card made by a green guy

#

but hpa doesn't mean anything for me

#

and he helped to covert that

young jacinth
#

why is a delay option not a thing for template sensors yet?

ivory delta
#

Huh? What would you delay inside a template?

young jacinth
#

the state of a template sensor

#

like delay on/off for template binary sensors

ivory delta
#

But why? What are you trying to do?

young jacinth
#

i have a dryer connected to a power monitoring plug
i want to be sure in which state the dryer is so a delay is neccesary
this works great with binary sensors but i want to monitor a standby state
this would work with an automation, but i want to keep everything inside the sensor

ivory delta
#

i want to be sure in which state the dryer is so a delay is neccesary
Why?

#

It takes some time so you know it's on standby instead of a short pause in a cycle?

young jacinth
#

announcement if dryer is finished
if the dryer is in the standby state it is not emptied and i want to be announced again

ivory delta
#

Well that's just automations...

#

You need to use an automation to send the notification anyway.

#

Templates won't do what you want. Templates are moment-in-time things. They have no history.

young jacinth
#

yea but i want to use this in other scenarios aswell

ivory delta
#

Any scenario where you want to do something based on a sensor is an automation. Automations are the tool that handle delays or checking how long something's been in a particular state.

#

Templates can't do what you're asking, nor am I sure there's actually any point.

young jacinth
ivory delta
#

No

#

Questions about automations belong there. You can't do what you're asking with a template sensor alone. Templates don't have history.

young jacinth
#

they dont need to monitor history

ivory delta
#

For a template to have an internal delay, it would need a history...

young jacinth
#

template binary sensor work in a smiliar way

#

they have delay on/off options

ivory delta
#

Well if you think other types of template sensors should... either log a feature request on the forum or create a pull request on GitHub.

young jacinth
#

mhhh i might do that, as is dont see the reason why this should not exist

golden beacon
#

Hi does someone know how I can have the friendly name change based on the value of a sensor? I am trying to use it in Bitfocus Companion but it doesn't support states (yet) and it currently uses the (friendly) name so I need to change that to the value of a sensor
So basically value_template but for friendly name
Oh... I'm a bit blind, apparently ' friendly_name_template' is a thing

ivory pawn
#

Hello, this will need some skills ! Can someone tell me how to create a filtered list of all entities that are present in 2 groups. I see some codes as below but would appreciate some help joining the dots to make it happen.
This for example gives me a list of the entities in a group_3.

{{- entity_id }}
{% endfor %}```
I then tried this but think I need an iteration within an iteration to make it actually work?
```{% set group_entities = expand('light.group_3.attributes.entity_id') %}
{% set wled_entities = expand('light.group_wled.attributes.entity_id') %}
{% for entity_name in group_entities if entity_name == wled_entities %}
  {%- if not loop.first %}, {% endif -%}
  {{- entity_name -}}
{% endfor %}```
I hope someone understands and can give me a the best solution here. Thanks!
.... im now seeing intersect() as a better way?
ivory delta
#

I don't think you can use set.intersection() in the sandbox that templates run in.

mighty ledge
#

expand('group.x') | selectattr('entity_id', 'in', expand('group.y') | map(attribute='entity_id') | list)

ivory delta
#

One day we'll have to schedule a competitive templating event between petro and phnx.

#

I love that template. Taking it a bit further (and making it a little uglier)... this actually returns the entity ID's:
{{ expand('group.x') | selectattr('entity_id', 'in', expand('group.y') | map(attribute='entity_id')) | list | map(attribute='entity_id') | list }}

#

The nesting there almost sent me cross-eyed πŸ˜„

mighty ledge
#

Yeah I’m texting this from my phone so i didn’t feel like adding that extra crap πŸ˜‚

ivory delta
#

I figured from your mispost πŸ˜„

#

Not trying to take the credit, your solution is brilliant.

mighty ledge
#

I’m sure there’s a better way and simpler

#

This might work

#

expand('group.x') | select('in', expand('group.y'))

ivory delta
#

Nah. I don't think it likes comparing the state objects.

mighty ledge
#

Depends on generators

ivory delta
#

That was my first guess before you came in with selectattr.

#

Returns an empty list for me when I compare a group against itself:
{{ expand('group.everyone') | select('in', expand('group.everyone')) | list }}

ivory pawn
ivory delta
#

Works here πŸ€·β€β™‚οΈ

#

Use the same group in both places for now, you should get everything in that group:
{{ expand('light.group_wled') | selectattr('entity_id', 'in', expand('light.group_wled') | map(attribute='entity_id')) | list | map(attribute='entity_id') | list }}

ivory pawn
ivory delta
#

Aha... light.group isn't a group πŸ˜‰

#

It's a grouping of lights but it's not actually a group.

#

It just looks like a single light.

ivory pawn
#

oh i see ... nicely spotted

ivory delta
#

I guess if you want to do that, you'll have to switch for a regular group.

#

I've caught the Jinja bug now. Remembered macros... who said we don't have intersection? 🀣

{{ expand(list1) | selectattr('entity_id', 'in', expand(list2) | map(attribute='entity_id')) | list | map(attribute='entity_id') | list }}
{%- endmacro %}
{{ intersection('group.x', 'group.y') }}```
#

Is there a way to share macros around to have them accessible throughout HA?

#

Never mind. Found petro answering the same question on the forums 🀣 #

ivory pawn
#

nice , but so i don't waste your times guys, if we can take a step or three back,
.. im basically trying to have a service data template apply to multiple entities, and wonder if the list will even be accepted this way by HA.?
(If I just write the entities with a comma seperation it does work)

data_template:
   entity_id: {{ the list we are trying to create comparing 2 groups for matching entities}}```
ivory delta
#

Sure, it'll work.

ivory pawn
#

cheers....

ivory delta
#

Just pass in lists instead of expanding groups.

ivory pawn
#

got it it think ... {{ states.light.group_3.attributes.entity_id | list }}

rain cove
#

How do I make a sensor that shows whether a device is on or off based on a state of a sensor? (Humidifier plugged into smart plug that can measure power draw)

#

I have the states('sensor.sonoff01_watts')|int > 20 part

#

But I am unsure how to set state on/off and for the icon and what not

#

I think i figured it out, i should be using binary sensor, not sensor

misty pasture
#

what's the idiom for testing whether a value (state) is defined/truthy in a template?

thin vine
#

you can test an entity with {{states('light.unknown') == 'unknown'}}

#

or rather != as you want to know it is defined πŸ˜‰

misty pasture
#

thanks that works (though I compared with None)

wicked gazelle
#

hi is there a template that can get text from a file? i want to send the learned broadlink code as a notification. can i use some sort of template to get the code and display it in the notification?

#

/config/.storage/broadlink_remote_780f775acae6_codes the code is in this file

#

the part i want is the b64 part

#
    "version": 1,
    "key": "broadlink_remote_780f775acae6_codes",
    "data": {
        "Learn": {
            "Code": "JgBQAAABJ5URFBMSEzYUERQRFBETEhMSETgUNhEUETgRORE5ETgRORQRExITNhQRFBEUERM2EhMUNhE5ExEUNhQ2ETgRFBE5EQAFKQABKUkRAA0FAAAAAAAAAAA="
        }
    }
}```
#

the broadlink learn command used to do what i want to achieve, but when it was updated it no longer shows you the leared code. i am just looking for an easy way to display the learned code

#

i want to use the persistance_notification service to display the learned code

next haven
#

Good day,

I have a thermostat called climate.thermostat and it supports preset_modes (I can set these via a service call).
I'm trying to make a binary_sensor for each of the preset modes (climate.thermostat.preset_mode).

I have the following, but they always show off even though in Developer Tools I can see the correct preset_mode as an attribute.

# Create binary sensors for thermostat programs
binary_sensor:
  - platform: template
    sensors:
      thermostat_program_away:
        value_template: "{{ is_state('climate.thermostat.preset_mode', 'away') }}"
      thermostat_program_home:
        value_template: "{{ is_state('climate.thermostat.preset_mode', 'home')}}"
      thermostat_program_comfort:
        value_template: "{{ is_state('climate.thermostat.preset_mode', 'comfort') }}"
      thermostat_program_sleep:
        value_template: "{{ is_state('climate.thermostat.preset_mode', 'sleep') }}"

This is not working though, any help will be appreciated

Edit : I installed Attributes Extractor in HACS, made a sensor for climate.thermostat.preset_mode and then made my binary_sensors based on the new sensor.thermostat_preset_mode entity's state (which is now equals to the preset_mode) and this works like a charm.

If there is another way to do this (without the HACS Integration), I really would like to know.

wicked gazelle
#

i have tried using a file sensor but the state is showing state "unknown"

#
  - platform: file
    name: test sensor
    file_path: /config/.storage/broadlink_remote_780f775acae6_codes
    value_template: '{{ value_json.data.Learn.Code }}'```
deft timber
#

@wicked gazelle , you file sensor can't work. The file sensor only retrieve the last line of the file. [edit]maybe the last line is good for you, but reading from a storage file is not really pretty πŸ™‚

#

for your binary sensor, you are doing it wrong. The preset mode is an attribute, not a state

#

so you should use : is_state_attr('climate.thermostat', 'preset_mode', 'away')

#

the command would be cat $pathToStorage/broadlink_remote_780f775acae6_codes | jq -r '.data.Learn.Code'

#

and if you don't have jq, cat $pathToStorage/broadlink_remote_780f775acae6_codes | sed -E '/"Code"/ s/^.*: "(.*)".*$/\1/ p'

wicked gazelle
#

@deft timber the sensor.command works perfectly. Thank you. the first command worked

#

@deft timber fyi it was @next haven that was asking about the climate

deft timber
#

Oups πŸ˜„

deft timber
next haven
silver flare
#

Hello, is there a way to define a template macro in a "global" way, to be used by every template sensor?

silver flare
#

I'm finding myself repeating alot of code and would be nice to centralize some common pieces in macros

deft timber
#

Nop

ivory pawn
#

hey , got some help with comparing entities in groups but wanted to know is it possible to compare just lists (not the array created by using expand).

Simply put, can I create a List C which is composed of all matched items between List A and List B ?

#

List A and B are generated as follows:

{{ states.light.group_B.attributes.entity_id }}```
#

[note. because its a LIGHT group, the group is treated in HA as an entity itself so expand wont work, so instead we can get a list of entities as shown above.

dreamy sinew
#
{% set l2 = [3,4,5] %}
{{ l1 |select('in', l2)|list }}```
mighty ledge
#

@dreamy sinew that doesn't work with state objects

#

have to use selectattr

#

& entity_id

dreamy sinew
#

just showing an example

#

i don't have any groups so this is as close as i can get without spending extra effort

royal vortex
#

I have the "Meteorologisk institutt (Met.no)" integration set to give me weather data for the area near my house. I'm trying to figure out how to pull the templow value out of the first forecast day, but i can't figure out how to dig down that far as it were... how do I get data out of a collection with a template?

dreamy sinew
#

in the template tester start with pulling the attribute and work your way down from there

#

@mighty ledge isn; the output of .entity_id on a light.group a list of entity_ids? or are they state objects themselves?

mighty ledge
#

yes it is, but they'd want to use expand

#

even though he incorrectly states that expand will not work on a light group. Unless they changed expand

#

I think there was a change to expand because it no longer breaks out properly on a circular referenced group

#

I have to look at the source

royal vortex
glossy viper
#
  • platform: template
    sensors:
    templowhere:
    value_template: >
    {{ state_attr("weather.home","templow") }}
dreamy sinew
#

{{ state_attr('weather.thermostat', 'forecast')[0].templow}}

#

i do have one of those

glossy viper
#

oh..didn't see branch

dreamy sinew
#

another option

#

state_attr('weather.thermostat', 'forecast')|map(attribute='templow')|first

ivory pawn
mighty ledge
#

Yes, its a list of state objects

royal vortex
#

{{ states.weather.home.attributes["forecast"][0].templow }} worked! Thank you!

mighty ledge
ivory pawn
#

@mighty ledge thanks for showing some interest and helping.
I have different capability/brand lights with different extra attributes that the light group cannot forward or customise onward to the groups entities. So I have made automations to cope with those. The below is just and example but there are many more choose options dealing with wled_services , mqtt_services , presets , night modes .. etc.

data_template:
   entity_id: {{ the list i am trying to create by comparing 2 light.groups for matching entities}}```
mighty ledge
#

if you just want the list then do what @dreamy sinew suggested

#

you don't need to use expand

#

unless you want to only turn whats on, off.

#

or vice versa

ivory pawn
#

cheers... is this on the right track?

{% set B = {{ states.light.group_B.attributes.entity_id }} |list %}
{{ A |select('in', B)|list }}```
mighty ledge
#

nope

#

Templates do not go inside templates

#

the entire line is a template

#

you do not need {{ }} to extract info inside a template

dreamy sinew
#

and you can drop the |list on the first 2

ivory pawn
#
{% set B = states.light.group_B.attributes.entity_id %}
{{ A |select('in', B)|list }}```
mighty ledge
#

yep

dreamy sinew
#

{{ }} print/output statements
{% %} logic statements

ivory pawn
#

thanks @dreamy sinew and @mighty ledge ... its so much easier with help πŸ‘

hybrid merlin
#

I'm having some trouble with a template fan.
https://paste.ubuntu.com/p/XdfDbMc9dp/

It'll turn on and off fine, and it'll display the speed (mostly just '3' if the fan is at full blast) but when I select other speeds, it isn't adjusting the fan level at all.

#

The fan controller is a Z-Wave Leviton VRF01. I can adjust the speed just fine through light.turn_on in Developer Tools>Services

bleak dragon
# royal vortex `{{ states.weather.home.attributes["forecast"][0].templow }}` worked! Thank you!

The following attributes seems to work ok:

{{ states.weather.home.attributes["forecast"][0].templow }} {{ states.weather.home.attributes["forecast"][0].wind_speed }} {{ states.weather.home.attributes["forecast"][0].wind_bearing }} {{ states.weather.home.attributes["forecast"][0].temperature }} {{ states.weather.home.attributes["forecast"][0].condition }} {{ states.weather.home.attributes["forecast"][0].precipitation_probability }} {{ states.weather.home.attributes["forecast"][0].datetime }}

#

But for some reason temperature and humidity does not produce a result.

#

The number [0] is the number of days into the future the forecast is done - up to 4 days maximum.

mighty ledge
mighty ledge
hybrid merlin
mighty ledge
#

aer you getting errors?

bleak dragon
mighty ledge
#

I know that

#

I'm asking what it looks like.

bleak dragon
#

-10.0
7.9
204.0
-2.2
cloudy
29.4
2021-02-13T11:00:00+00:00

mighty ledge
#

that's missing the keys

bleak dragon
#

Fromtop down the list

hybrid merlin
# mighty ledge aer you getting errors?

Actually, now that I'm looking, it seems that it's not that it's not changing, but instead it's always changing the speed value to '3' whenever I make a change. Let me change it to low/med/high and see if it's still doing that.

mighty ledge
#

That will happen when because your speed template is based on your light's setting

#

if the light isn't changing, the speed won't update

#

You need to look in the logs and see if there is errors

hybrid merlin
#

Logger: homeassistant.components.template.fan
Source: components/template/fan.py:377
Integration: template (documentation, issues)
First occurred: 2:10:19 PM (3 occurrences)
Last logged: 2:13:02 PM

Received invalid speed: . Expected: ['1', '2', '3']

mighty ledge
#

Alright, well there you go, it needs to be strings. So revert back to what you had but with the entity_id inside the data template

#

also, it appears as if your turn_on might need to select the speed

hybrid merlin
#

I have an almost identical fan template working for a different kind of Z-Wave fan controller

mighty ledge
#

right but this is not the same because it's not working

hybrid merlin
#

clearly πŸ™‚

mighty ledge
#

Received invalid speed: . Expected: ['1', '2', '3']

#

that tells us that it receive an empty string when trying to set the speed

#

Received invalid speed: . would normally read Received invalid speed: "something".

hybrid merlin
#

I actually get the same error on the other fan's template, but only upon starting HA

#

which, I didn't look to see if this was the case here

mighty ledge
#

Then that's not the error that we should be loooking at

hybrid merlin
#

I've restarted it so much troubleshooting this

#

But it's the only error for the template in the logs

#

OK, confirmed, it does trigger that error when changing the level. I switched everything back to 'low', 'medium', 'high'

#

and the error is
Received invalid speed: . Expected: ['low', 'medium', 'high']

#

Which fits that it is receiving an empty string for the fan speed

#

The entity details show speeds of low, medium, and high

#

When setting any of them, it changes the fan to brightness: 255

#

actually, now that it's low medium and high, it seems to be defaulting to 'medium', which would be the last item alphabetically...?

lime grove
#

How can I clamp the upper value to avoid erraneous numbers on this line?

#

value_template: "{{ (states('sensor.dehumidifier_volts') | float / 230) | round(3) }}"

#

voltage should never be over 250, but i think the smart plug freaks out occasionally

#

which im reading it from

mighty ledge
mighty ledge
ivory delta
#

What's this? πŸ˜‚
{% set v = v if v <= 250 else 250 %}

#

Why not min? πŸ˜„

#

{% [v, 250] | min %}

mighty ledge
#

same shit, different way of writing it

ivory delta
#

It's not like you to do things the long way πŸ˜›

mighty ledge
#

iterating over a list is slower than an if statement πŸ˜‰

ivory delta
#

Maybe

mighty ledge
#

oh it is, 2 computations vs 1 worse case

#

best case 1 vs 1

#

why not have 1 always

ivory delta
#

Reminds me of every time I try to optimise code at work... only for another dev to remind me that we wouldn't be using JavaScript if we wanted it to be fast 🀣

mighty ledge
#

always try to keep collection iteration to a minimum tho, thats 101

#

min definitely has to iterate across the whole list

ivory delta
#

Indeed. I reduced something from O(n2) to O(n) once at work. The other dev was wondering why a script was taking 15min+ to run. I got it to 10 seconds.

#

Meanwhile, my manager had no idea how much time I'd saved everyone 😦

hybrid merlin
# mighty ledge Sorry, was driving. What's y our current brightness when you turn on the light?

thanks for your help so far isolating the issue, unfortunately going to have to come back around to it later. I was trying different brightnesses on the light entity, and it would stay at that level until I tried to change it from the fan template entity, at which point it would go to medium. I was listening to the event bus, and was seeing that if changing the fan speed turned on the fan, I'd get a change event for light., fan., and zwave. entities. (It would always say the old state is null and the new state is 'medium', no matter what I had set it to. It would also set the fan to the medium level.) If I tried changing the speed while the fan was already on, I only got a change event for the zwave. entity, not the fan or light entities.

mighty ledge
ivory pawn
#

Hi again, trying to finish off something you guys helped with earlier but stuck. Can you take a look my entity_id entry in my data template ?
this works:

    speed: "{{[(state_attr('light.light_'+trigger.topic.split('/')[4], 'speed') + 28), 255] | min }}"
    entity_id: "{{'light.light_'+trigger.topic.split('/')[1]}}"```
and this works:
```    entity_id:
      "{% set A = states.light.group_1.attributes.entity_id %}
      {% set B = states.light.group_2.attributes.entity_id %}
      {{ A |select('in', B)|list }}"```
but trying to combine both doesn't.
```    entity_id:
      "{% set A = states.light.group_1.attributes.entity_id %}
      {% set B = 'states.light.group'+trigger.topic.split('/')[1]+'.attributes.entity_id' %}
      {{ A |select('in', B)|list }}"```
I've tried various combinations for set B but think it may be an issue of nested variable , rather than syntax. 
Either way any ideas would be nice. Cheers
ivory delta
#

What does trigger.topic.split('/') give you?

#

Also, use ~ to join things so you don't have to worry about casting.

mighty ledge
#
    entity_id: >
      {% set A = state_attr('light.group_1', 'entity_id') | default([]) %}
      {% set B = expand('light.group'+trigger.topic.split('/')[1]) | map(attribute='entity_id') | list %}
      {{ A |select('in', B)|list }}
ivory pawn
#

too fast πŸ™‚ @ivory delta... was just about to edit that bit in .. Its gives a number from an mqtt topic (i think its a string of a number an not an actual integer)

ivory delta
#

What error do you get?

ivory pawn
mighty ledge
#

it's not possible to concatenate a states object and a string, so you have to pass the entity_id to a function

#

it could also be done like this

ivory delta
#

And I think I'd still do it like this (even if I don't know exactly what the difference is):
expand('light.group'~trigger.topic.split('/')[1])

mighty ledge
#
    entity_id: >
      {% set A = state_attr('light.group_1', 'entity_id') | default([]) %}
      {% set B = state_attr('light.group' + trigger.topic.split('/')[1], 'entity_id') | default([]) %}
      {{ A |select('in', B)|list }}
#

the ~ vs the + just makes sure they are both strings, it is safer

ivory pawn
tender isle
#

I can't seem to get templates to work with a rest_command... Docs suggest it should work, but the data is not being passed into the parameters.

Edit, nevermind, I think I got it now, yay!

sonic nimbus
#

hello I have an error which says that Error during template condition: UndefinedError: 'tts' is undefined

#

so I have a choose statement and then two separate conditions if my variable platform is tts.google_translate_say do that branch of the automation, else if tts.cloud_say do other branch..

#

I checked in my templates tab {% set platform = 'tts.cloud_say' %} {{ platform == 'tts.cloud_say'}} and it returns true

#

do you see something that I missed maybe?

ivory delta
#

You missed telling us how you're calling the script.

sonic nimbus
#
    entity_id: script.play_notification
    data:
      variables:
        speaker: "media_player.bathroom_ceiling_speaker"
        source: "Primary Chromecast"
        volume: "0.4"
        custom_message: "Dobro doΕ‘li u kupatilo."
        platform: "tts.cloud_say"```
#

this is the call

#

but I think its working now..

#

im still testing..

lusty yacht
#

Got a question I'm hoping someone knows the answer to. I can get today's date using "now()" but how can I create a date using the known month, day, and year integers? Is there something like "date(2,13,2021)"? Ultimately, I'd like to create a custom date value and get the weekday() value of it to know the day of the week of a custom date.

ivory delta
lusty yacht
#

Thank you!

#

This returns the correct result but fails on with .weekday() -- strptime('{2}-{0}-{1}'.format(dateinfo.month,dateinfo.day,dateinfo.year),"%y-%m-%d") -- result: UndefinedError: 'str object' has no attribute 'weekday'

ivory delta
#

Try this instead (substituting in your own values):
{{ now().replace(day=21).replace(month=2).replace(year=2020).weekday() }}

#

That doesn't zero out hours or below.

#

This works too, so it must be something to do with your .format:
{{ strptime('20-02-21', '%y-%m-%d').weekday() }}

lusty yacht
#

Any way around the .format?

ivory delta
#

You can use it, you're just making a mistake somewhere. Check that the values make sense in the positions you're inserting them.

#

This works too:
{{ strptime('{0}-{1}-{2}'.format(20,2,21), '%y-%m-%d').weekday() }}

#

It'll be human error.

lusty yacht
#

story of my life lol

#

Thanks ill work on it

#

This ended up working for me: {{now().replace(day=dateinfo.day).replace(month=dateinfo.month).replace(year=dateinfo.year).weekday() }}

#

It doesnt like passing a variable into strptime

#

This fails:

{% set dateinfo={
"day": now().day ,
"month": now().month,
"year": now().year,
"dow": now().weekday(),
}
%}
{{ strptime('{0}-{1}-{2}'.format(dateinfo.year,2,21), '%y-%m-%d').weekday() }}

ivory delta
#

Variables work fine:

{{  strptime('{0}-{1}-{2}'.format(year,2,21), '%y-%m-%d').weekday() }}```
#

Check what now().year gives you πŸ˜‰

lusty yacht
#

I think its the JSON

#

Oh wait I see

ivory delta
#

What does it give you? You're telling strptime to expect a 2 digit year...

lusty yacht
#

Yea brain fartssss

ivory delta
#

Always build things up in steps, or you'll miss details like that.

lusty yacht
#

Its been a hot second since I used python, ive been missing a lot of details lately lol

ivory delta
#

Yeah, I'm not familiar with Python either. What little I know, I've picked up from watching this channel.

lusty yacht
#

Appreciate the help!

lime grove
#

How can I add another if statement which ignores power_w if the value is over 20000, can i nest them?

#

value_template: > {% if value_json.id == 51600 %} {{ value_json.power_W }} {% else %} {{ states('sensor.owl_watts') }} {% endif %}

lime grove
#

also could i just replace that if statement with value_template: "{{ value_json.power_W | is_defined }}"

lime grove
#

Is this valid?

#

value_template: > {% if value_json.id == 51600 %} {% if value_json.power_W <= 12500 %} {{ value_json.power_W }} {% else %} {{ states('sensor.owl_watts') }} {% endif %}

lusty yacht
#

I think you need another {% endif%} to close out the 2nd if statement for that one

lime grove
#

I did add that and it broke

lusty yacht
#

but you could do this value_template: > {% if value_json.id == 51600 and value_json.power_W <= 12500 %} {{ value_json.power_W }} {% else %} {{ states('sensor.owl_watts') }} {% endif %}

lime grove
#

I did think about that, I'll do that if this way causes any oddities

#

ah you're quite right the endif was needed, last time I tried and it failed I must not have saved my config

sonic nimbus
#

how to get last_changed attribute from a switch

#

Im trying this: {{ state_attr('switch.bathroom_light', 'last_changed') }}

austere relic
# sonic nimbus how to get last_changed attribute from a switch

I'm not the expert here, but since it's not listed under "attributes" under developer tools, I think you can only access it with the hardcoded: {{ states.switch.bathroom_light.last_changed }} . if you need it only for front end, you can access it directly there with secondary info.

sturdy fiber
#

Hello again. Im working on an integration via MQTT Auto Discovery, which is working so far.
The only issue i have left is converting a string value to float. I know this can be done by | float. But my key : value pair is not a json. so i tried {{ value | float }}, but this doesnt seem to work.
My state topic is basically the key entry. Trying to convert the value to float.
The config entry includes ["value_template"] = "{{ value | float }}. And the value is shown in the gui, but it seems to be a string instead of the float.

sonic nimbus
#

tnx @austere relic

#

I managed to retrieve last_changed attribute

#

but now I have an error

#

here is the script

#

Invalid config for [automation]: invalid template (TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.) for dictionary value @

austere relic
#

dunno if it's the space missing after {%

ivory delta
#

Whitespace doesn't matter inside the templates.

#

Probably doesn't help that the if block isn't actually doing anything.

sonic nimbus
#

yup, just old habit.. to have else part

austere relic
#

no you also dont have an action after the if πŸ™‚

sonic nimbus
#

oh I found it entity_id is misspelled πŸ™‚

sonic nimbus
#

so if the condition met, it should jump into sequence

ivory delta
#
                {%else%}
                  #DoNothing
                {%endif%}```
#

The if does nothing...

#

It returns nothing.

#

You should also simplify it all...

{{ 3 > time_diff > 0 }}```
sonic nimbus
ivory delta
#

If you're using a condition as a template, the template needs to return True for you to proceed.

#

Currently, you return nothing when it passes (so it will stop your sequence) and you return something when it fails (so it will continue).

#

I've edited my last post... that's what you need to return.

#

The important thing is that {{ 3 > time_diff > 0 }} returns a boolean.

sonic nimbus
#

I get it..my if statement does not returns boolean always

ivory delta
#

It might be considered a boolean but it'll be backwards.

#

An empty string is 'False', a non-empty string is 'True'.

sonic nimbus
#

it works πŸ™‚ thanks mono

ivory delta
#

States are always strings. Templates always return strings. If an integration needs a different data type, it will attempt to convert it.

gray loom
#

Hi i need some help,
Im trying to create a template for my temp sensor and im writing this to pull its state

Im getting a

invalid key: "OrderedDict([('states.sensor.151_temperature', None)])" in "/config/configuration.yaml", line 46, column 0

error
But if i plug the same thing in dev tools>template editor it works and i get the temperature

ivory delta
#

It sounds like the problem is the way you're configuring your integration, not the template itself.

gray loom
#

i just came from thereπŸ˜…

ivory delta
#

Share the whole thing...

gray loom
#
  - platform: template
    sensors:
      sensor.151_temperature:
        friendly_name: "TempSensor"
        unique_id: "z2f3035e0e8d4bd098c03ffb1b1e0926"
        unit_of_measurement: "Β°C"
        value_template: '{{states("sensor.151_temperature")}}'
#

This is a temperature sensor that works with tellstick add-on. It does not have unique_id so im trying to make one with a template

#

Because i need to add my entities into areas and i cant do that now...

ivory delta
#
      sensor.151_temperature:```
πŸ€”
thin vine
#

I don't think you can pull data in a template from the same device

ivory delta
#

First, you don't put sensor. in front, it does that for you.

#

Second, never start an entity name with a number.

#

Third... what Magie said. Circular references are stupid.

#

And... your problem is the integration, not the template.

thin vine
#

if the original is calles 151_temperature, call this something else

gray loom
#

I didnt call it 151_temperature, when i integrated it first it was called like that

ivory delta
#

You just showed us where you typed that name...

#

Line 3.

thin vine
#

a template sensor is it's own entity, you';re not changing the original one

gray loom
#

I can change name and do a bunch of stuff to all of my entities that are pulled from my phone, because they have a unique_id right, but this temp sensor that works with a tellstick doesnt have one

This entity ("sensor.151_temperature") does not have a unique ID, therefore its settings cannot be managed from the UI. See the documentation for more detail.

in my yaml i only have

sensor:
  - platform: tesllstick

thats it. How can i add my temp sensor to a area for example the same way i can with my phone entities?

ivory delta
sturdy fiber
#

Quick feedback to my issue with the wrong data format. It was actually not related to the value_template, but to the unit_of_measurement key. Setting a unit_of_measurement made the data be displayed as floats.

hollow cloud
deft timber
#

You have errors in level_template and value_template. "{{states('light.zb_office_ceiling1.brightness') | int }}" is not correct. If you want to access an attribute, use "{{state_attr('light.zb_office_ceiling1', 'brightness') }}" (it is already a number so no need to cast)

#

when you call set_level, you set a parameter value, instead of brightness

#

BTW, use data: and not data_template:, which is deprecated

#

@hollow cloud πŸ‘†

fossil hearth
#

how to configure a template sensor to survive restarts without effecting the last changed time stamp πŸ™‚ ?

lethal sparrow
#

is there any way to apply an icon template to a helper variable created via UI? I want the helper icon to change based on state (on/off)

whole marsh
wet latch
#

Hello there. I'm not sure if this question needs to be under templates or automations...

I'm trying to set up an automation based off an event from my Camera system. The event triggers on motion and includes detail about which camera, which object detected as well as a direct link to what I suspect is a gif of the motion recorded....
I've used a data_template to pick up the specific camera '{{ trigger.event.data.desc }}' and further down in the automation I'm trying to do a push notification to my iPhone with the category "camera" and then I try to do the same thing to define the camera: entity_id: 'camera.{{ trigger.event.data.desc }}_camera'

Whenever I include the stuff about the camera, I get an error which my talents are not adequate in troubleshooting: voluptuous.error.MultipleInvalid: extra keys not allowed @ data['attachment']

Anyone able to help me understand this? πŸ™‚

thin vine
silk smelt
#

I'd like to split out my Utility Meters in a separate folder but how can I know if I should use !include_dir_merge_named or !include_dir_merge_list ?

ivory delta
silk smelt
#

hehe... I always post in the wrong channel!!

fading bear
#

I'm trying to pull some data from API endpoints which require bearer authorization, and the issue i have is that my token keeps changing. I can't store it and update it in secrets.yaml because it takes a restart to affect the change, is this something i could somehow achieve with a template and some sort of variable somewhere?

#

I havn't yet worked out -how- i'm going to keep getting the new token, but it's kinda academic if I can't -use- the new token without restarting HA

wet latch
#

@thin vine I've tried and tried, here is my code: https://paste.ubuntu.com/p/sSF5F73gHf/ - It fails with: NEW Notify Motion: Error executing script. Invalid data for call_service at pos 2: extra keys not allowed @ data['attachment']
NEW Notify Motion: Error executing script. Invalid data for call_service at pos 2: extra keys not allowed @ data['push']
NEW Notify Motion: Error executing script. Invalid data for call_service at pos 2: extra keys not allowed @ data['data_template']

I'm not sure what I'm doing wrong :/

First part of the script works fine, it starts going to shit when I add on the 2nd part with the attachment, push stuff

fading bear
wet latch
#

Hmmm, it may be @fading bear - I picked it up in a YouTube tutorial at some point...I have something set up in a different way where it works like this...I don't think it's data_template tho, but only data:

fading bear
#

edit: it's "attachment" on iOS, not image

#

it's worth noting that if the goal is to send a snapshot of the camera with the notification, the way i do it is to have 2 actions - the first saves a snapshot and the second creates the notification with the attachment

wet latch
#

In the same automation I have an action that snapshots the camera that triggered an event, this works fine. I then have another action that is to notify my mobile phone...it works fine just sending me a message with some content from the event, but if I try to include the image then it messes up

#

trying to make it so it includes a snapshot and then a long press = live stream...but first things first, snapshot :p

fading bear
#

the order of things is a bit messed up because it's created by the editor

wet latch
#

ok...I do need data_template to use {{ data tho right?

fading bear
#

forgive me, but if that works, what doesn't? πŸ˜›

wet latch
#

no problem...it's another thing I'm trying to achieve. I'm trying to get the info from the event and then via that "select" which camera to show me...
The last one I posted is from another way of doing it where I have something called DOODS do the analysis of the image to detect humans and the new thing I'm trying to do is to use what's called a Camect to do that detection

fading bear
#

ah i see

wet latch
#

The Camect device is better at detecting objects but I've had a hard time figuring out to integrate it into HA

#

So I just went another way at some point...but now I'm a bit stubborn :p

fading bear
#

probably going a bit beyond me in that case. You might be able to do something weird with actionable notifications, where each action pings you back with a different stream

#

?

#

seems clunky in my head but i'm a bad coder πŸ˜›

wet latch
#

hehe, likewise...I cut, paste and modify quite a bit...can't quite understand this one tho...

#

and the error code I'm not able to troubleshoot on my own

fading bear
#

Seems to be that it has a problem with you using "push" inside data, so maybe try it as its own group, but we're well into "just try moving the yaml about" now

wet latch
#

I think the issue is in some way this data_template inside another data_template, but I don't know

#

Yeah...hope someone has the magic touch to help me on my way

#

thanks for giving it a try tho πŸ™‚

fading bear
#

here with my own problems, just trying to give back πŸ˜›

ivory delta
#

There are already several integrations that do exactly that. If you want to go down that path, ask in #devs_core-archived

fading bear
#

Your sunny optimism at my skill is as uplifting as a dog in a costume, but i fear it may be misplaced πŸ˜›

mighty ledge
#

all sections of data can be templates

thin vine
#

If I had a guess, replacing data_template with data should work, as long as 'camera.{{ trigger.event.data.cam_name }}_camect_jpg' is a valid camera entity

#

I would first try to make it work without the template, then insert the template part

wet latch
#

@thin vine Thanks! I'll give that a shot at once

#

@thin vine It's better...another obstacle but something I think I can manage now. Thanks a bunch! πŸ˜„

fossil hearth
#

how to configure a template sensor to survive restarts without effecting the last changed time stamp πŸ™‚ ?

coarse tiger
#

is the tempalte result a number?

clever sedge
#

how do I do this, template derives it's value from another entity

#

I just want a place to store a set point

coarse tiger
#

then you maybe satisfied when you put a statistics sensor on top of the template result

clever sedge
#

I want to use node red to call a service that sets a value that is read only from GUI

#

there is no service to set values of a template sensor

coarse tiger
#

as long as you don't touch it in gui/automations/scripts it doesn't matter if it's r/o or r/w

clever sedge
#

sure, but that's janky

#

i wish HA had a generic variable service

#

or ability to make inputs read only

#

maybe there is a custom lovelace card to do what I want...

coarse tiger
#

janky? ok 🀷

clever sedge
#

i'm surprised that such a basic feature is missing

#

there is a switch services that does exactly this for booleans, why don't we have an analog_service

#

i'll just use the input_number for now and hope my wife doesn't touch it...

coarse tiger
#

now we get to the point, yes ACL is missing in HA

clever sedge
#

I come from factory and industrial automation, so making internal and user variables is common place

coarse tiger
#

do you have industrial grade switches and sensors at home?

clever sedge
#

i don't see how that relates to being able to create program variables in node red

#

and displaying them on the UI

coarse tiger
hollow cloud
fossil totem
#

@clever sedge the input_x "helpers" are in fact intended to use like you suggest. if you have a number to stash, input_number is a place you can stash it.

hollow cloud
#

@deft timber thanks! It's looking like it works!! I might run into some edge cases but this is looking great!

fossil totem
#

blueprints cannot (yet) create helper objects, but they can publish MQTT messages, so if you're sure the users of your blueprint have MQTT available, you can do things like publish a discovery message to create something like an MQTT sensor, push changes to it via MQTT messages, and read those settings back via templates.

clever sedge
#

there is no way to disable that

dreamy sinew
#

just don't show that entity in your ui

coarse tiger
#

or feed the number to a sensor with the api

mighty ledge
clever sedge
#

i need to show these targets on the UI because the climate UI isn't very smart/has problems

dreamy sinew
#

make a template sensor to display

clever sedge
#

yes, that is the only other solution, but it's a bit ridiculous to make a template sensor just to make a "read only" variable in the UI

coarse tiger
#

it is a solution, though

clever sedge
#

I will try it

#

making templates is a bit confusing, so I was trying to avoid it

dreamy sinew
#

sensors are the only things that are read only in HA. Input_x aren't read only because something is writing to them

clever sedge
#

I agree, that's all fine

#

but sometimes that thing isn't the UI

dreamy sinew
#

Β―_(ツ)_/Β―

#

you get history graphs and unit types on sensors and not on input_X

fossil totem
#

template sensors are really handy, they provide a kinda-read-only way to stash structured data

dreamy sinew
#

as long as you can get it from somewhere that already has it πŸ˜›

fossil totem
#

and again, if you have MQTT, you can write to it via MQTT without giving the user any way to make those same sorts of cahnges

clever sedge
#

I'm not using MQTT, HA is complicated enough as it is lol

#

is there a way to refresh config and get my new template sensors without reboot?

dreamy sinew
#

you never need to reboot, just restart the HA service

mighty ledge
#

template.reload service

#

developer tools -> services tab -> template.reload without any args

clever sedge
#

does this look correct

#

- platform: template sensors: climate_sys_heating_target: value_template: '{{ state_attr("input_number.climate_sys_heating_target") }}' #unit_of_measurement: 'F' friendly_name: Heat Target device_class: temperature

mighty ledge
#

states() not state_attr()

#

Also, if you want it to show up in the correct history graph, include the degree symbol

clever sedge
#

in unit of measure ?

#

I think device_class will sort it correctly won't it?

mighty ledge
#

nope, because it doesn't know if it's C or F

fossil totem
#

Sets the class of the device, changing the device state and icon that is displayed on the UI (see below). It does not set the unit_of_measurement

mighty ledge
#

device_class only sets the icon btw

#

it also does some fancy shit for timestamps

#

but we don't need to talk about that

clever sedge
#

so do I need the degree symbol

#

or can I just put F

dreamy sinew
#

you need the symbol

fossil totem
#

Β°F

#

no idea why i have committed this to memory, but it's alt-248

#

too much time writing templates πŸ˜„

clever sedge
#

ok looks good now

#

and is read only

#

thanks for helping

ivory delta
#

Alt+0186 for the better one πŸ˜‰

#

ΒΊC

mighty ledge
#

I have alt241 memorized

#

and 248, but it's not always the correct degree symbol

silent barnBOT
iron peak
#

Hi everyone. I have some smart blinds, that are integrated with HA via rest_commands.
I'm using the covers template, but I'd like to avoid repeating the same code 14 times.
Is it possible to use Jinja2 template somehow in the configuration.yaml, something like this:

#

?

ivory delta
#

Try it and see

iron peak
#

this is just pseudo code, to explain what I'm trying to do

#

the jinja2 template throws an error, if I try it like this

#

I was trying to use "customize" and "customize_glob" but that does not help much, as the open_cover and close_cover sections have to be repeated

#

unless there is a way to reference the attributes of the entity without defining the entity name

#

something like .friendly_name or self.friendly_name would help, but it looks like there is no such thing

dreamy sinew
#

you'll have to copy-paste

mighty ledge
#

Add the code to your yaml and comment it out so you don't need to reinvent the wheel everytime you need to add one.

iron peak
#

Thanks @mighty ledge , this is what I've been doing. (I took it a step further, and wrote a simple python script to generate a yaml file, by rendering the Jinja2 template, and I only need to run that if the template part changes. I was just thinking that there has to be a standard solution for this πŸ™‚

mighty ledge
#

Nope, jinja is only applied on fields

iron peak
#

is it possible to reference a parent key in the yaml config somehow?

#

something like this:

#

friendly_name: blind_name
open_cover:
service: rest_command.blind_setpos
data:
position: 0
name: ../../friendly_name

#

?

#

that would allow me to define it once and use the customize module to simplify my code

#

but I have not seen any examples, where there is a reference to a parent key, so I suspect it's not possible

#

πŸ™‚

glacial matrix
#

Afternoon all, i have a tracker on my motorcycle that is connected through traccar to Home Assistant, one of the data fields it reports is power (ie. the voltage of the bike battery, how do i ctreate a template sensor that pull that into it's own sensor? the device is called device_tracker.thundercat and the attribute is power.

fossil venture
#

value_template: "{{ state_attr('device_tracker.thundercat', 'power') }}"

fossil totem
#

@iron peak to the best of my knowledge your suspicions are correct

glacial matrix
#

Thank tom, I assume that goes into sensors, is that correct?

glacial matrix
#

Got it! Cheers tom!

fading bear
#

I have CLI sensor, "esi-rika-online" which I have working pulling json attributes into its attributes successfully.

#

name: esi_rika_online
json_attributes:
- last_login
- last_logout
- logins
- online
value_template: "{{ value_json.esi_rika_online }}"

#

What do i need to change to properly set one of these attributes as the "state" of the sensor? Currently it just says "unknown"

#

I copypastad the bulk of this, so I figure i need to change the value_template bit but not sure what i'm doing at this point

stark pilot
#

Hi guys. Can I disable unavailable state for one sensor?

dreamy sinew
#

no

#

@fading bear need to set your value template correctly. to do that, you need to know what data you're actually working with

fading bear
#

the attribute i'd like to become the main state of the sensor is "online"

#

which is either true or false

glad geode
#

Hi all. I want to set attribute templates based on the new state of a sensor. Is that possible?

dreamy sinew
#

@glad geode need more details

#

Neo: then adjust your value template to pull that value

#

if you want the state to be something other than true/false you'll need to do some more template magic to convert it

glad geode
dreamy sinew
#

don't do circular references

glad geode
#

I wouldn't call it circular as such. The value_template doesn't reference the attributes

fading bear
#

i suck at templating, it never seems to sink in

dreamy sinew
#

that would work

glad geode
#

But with attribute_templates rather than icon_template

fading bear
#

any ideas?

dreamy sinew
#

did you restart/reload your templates after making the change?

fading bear
#

yep

#

restarted all of HA

dreamy sinew
#

anything in the logs?

fading bear
#

nothing i can see

dreamy sinew
#

.share the full then and a example of the payload

silent barnBOT
#

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

fading bear
#

one mo

dreamy sinew
#

try:
{{ 'Online' if value_json.online else 'Offline' }}

fading bear
#

restarting now to test

#

that seems to have done it, won't know until the account goes offline to see if it changes, but it's reading "Online" now int he state. - cheers @dreamy sinew

#

I suppose this should be a binary sensor, but can they contain attributes too?

dreamy sinew
#

they should, if there is a binary version of this platform

fading bear
#

alright, future me problem

#

cheers

#

using home automation to spot game disconnects.. what a world

dreamy sinew
#

lol

tardy patio
#

Hello everyone! Is there any way to get the value of a mqtt topic into dev tools/template editor without making a sensor out of it?

#

I want to see exactly how payload_json works and the output of a certain attribute

dreamy sinew
#

if its not in a sensor its not in HA's state machine

#

or rather, if its not in an entity

tardy patio
#

I am trying to do just that,

#

So I am not sure how to find out the value

#

I made many sensors and binary sensors manually configured

dreamy sinew
#

probably through some sort of mqtt explorer tool

tardy patio
#

but I am having issues with one in particular.

#

If value_json is something like ("value"=heat,) I can make a sensor with "{{ value_json.value }}"

#

BUT, if value_json is ("value"="heat",) it will not work. I have tried with something like ```
value_template: >-
{{ value_json.value | replace('"','') }}

#

And of ocourese it will not wirk with a simple "{{ value_json.value }}"

dreamy sinew
#

is that a direct copy-paste of the response?

#

because that isn't valid json if so

tardy patio
#

no, just the part I am interested in πŸ™‚

#

Let me see

#
{
    "anti_scaling": "ON",
    "away_mode": "OFF",
    "battery_low": false,
    "child_lock": "LOCKED",
    "current_heating_setpoint": "30.0",
    "frost_detection": "ON",
    "linkquality": 18,
    "local_temperature": "24.7",
    "local_temperature_calibration": 0,
    "preset_mode": "none",
    "system_mode": "heat",
    "window_detection": "OFF"
}```
#

system_mode is what I am interested in

#

This is what I see in mqtt explorer and also in zigbee2mqtt state page of the device

dreamy sinew
#

value_json.system_mode would be what you want then

tardy patio
#

It does not work,

#

I have the exact same thing done for my other clkimate component and it is working

dreamy sinew
#

make sure you're pulling the correct topic then

#

if it works on another it would work here

glossy viper
#

i want to see only specific mails

tardy patio
#

Looks like there is a problem with my mqtt sensors. The ones from windows do work, but the ones from mqtt climate entities do not work. Neither does. One just stays on all the time.

glossy viper
glacial matrix
#

would this round to two decimal places? value_template : "{{ state_attr('device_tracker.thundercat', 'power')|round(2) }}"

EDIT. Just found the template in config tools to test, and it works. Thanks.

glad geode
#

Hi all. How can I merge two sensor values that are json strings?

glad geode
#

Right, a slightly different tack. Is there a filter to merge 2 dicts?

ivory delta
#

There's a link in the pins to the available filters.

glossy viper
glad geode
#

Ok, I'm drawing a blank on ways to do what I want to do. I have a json defined set of light profiles for rooms which I'm reading in from a command_line sensor that sets json_attributes. I want to merge the room profile over the default profile. Obviously in any standard language this would be trivial, but in jinja2 I'm struggling:

{% set profile = 'night' %}
{% set room = 'lounge' %}
{% set defaults = state_attr('sensor.settings', 'profiles').default[profile] %}
{% set data = state_attr('sensor.settings', 'profiles')[rm][profile] %}

What next?

#

I suppose I could use an sql sensor and COALESCE...

dusky heron
#

SelectorSyntaxError(
soupsieve.util.SelectorSyntaxError: Expected a selector at position 0

#

But this site has no selector like .div or <a> or something, just plain text

thin vine
#

it seems to be embedded in a <pre> tag:

<pre style="word-wrap: break-word; white-space: pre-wrap;">2021/02/17 12:50
EDDM 171250Z 27011KT 240V300 9999 FEW030 10/03 Q1021 NOSIG
</pre>
#

So I would say select: "pre"

dusky heron
#

Let me try ...

glad geode
dusky heron
#

Shows 'unkown' ... so how do I get just this line:
EDDM 171250Z 27011KT 240V300 9999 FEW030 10/03 Q1021 NOSIG
?

glossy viper
#

"body > pre"

dusky heron
#

Good idea ... I'll try

#

Nope ... sensor still returns 'unkown' ... grrr

charred dagger
#

The link seems down to me.

thin vine
#

weird, link works for me.

#

unkown is also weird, I would think it to be unknown... I wonder where that typo is πŸ™‚

#

anyway, at the moment however, it doesn't seem to be template issue, so I would move the discussion to #integrations-archived and see if someone has experience with the scraper

dusky heron
#

Okay, so should I post the problem there?

dusky heron
#

That is what I ended up with:
- platform: rest name: MUCWX scan_interval: 300 resource: https://tgftp.nws.noaa.gov/data/observations/metar/stations/EDDM.TXT value_template: '{{ value.split("\n")[1] }}'

The desired output is: EDDM 171220Z 26010KT 9999 FEW025 09/03 Q1021 NOSIG
Thanks for your help. πŸ™‚

fading bear
#

My next issue, I'm trying to create a command line sensor which is essentially the sum total of lots of json objects returned by an API call, and frankly im not even sure where to start... https://paste.ubuntu.com/p/rfZsQy5cCR/ is an example of the data to be returned, but the number of objects and length of the response is variable

#

I want my eventual sensor to simply be the sum total of all of the "quantity" values

ivory delta
#

Did you check the pins?

fading bear
#

discord tells me this channel has no pins 😦

ivory delta
#

No, it doesn't.

fading bear
#

I mean, let's not be one of those people that tells other people what they can see

glad geode
#

If not....install jq

ivory delta
#

Or... just use the existing Jinja filters πŸ€·β€β™‚οΈ

glad geode
#

Well as with my issue earlier jinja doesn't always have the answer you're looking for

ivory delta
#

When they do, use it.

fading bear
#

if it has this answer though, i'll take it over installing something else

ivory delta
#

Look at the built-in filters. It has a perfect solution for what you're asking.

fading bear
#

i'll take a look, might need help making it work though - is there a way of giving the template editor some sample output to work with for testing stuff like this?

fading bear
ivory delta
#

The template editor has an example.

fading bear
#

this bit?

ivory delta
#

Yes

fading bear
#

excellent

fading bear
#

finally got this working, cheers @ivory delta

glossy viper
#

where u are master of templates? :)))

bronze prawn
#

Can someone help? I've got a window sensor that's having some problems. It keeps reporting open/closed suddenly. I think it may be weather related. I'm wanting to have it only turn on if it has been on for at least two seconds. I've tried adding this:

    master_window:
      friendly_name: 'Master Windows'
      value_template: >-
        {{ 'open' if is_state('binary_sensor.master_windows', 'on') else 'closed' }} 
        delay_on:
          seconds: 2
      icon_template: >-
        {% if is_state('binary_sensor.master_windows', 'on') %}
          mdi:window-open
        {% else %}
          mdi:window-closed
        {% endif %}
#

I think I may be missing the whole boat on this though, right?

#

I want to check that binary_sensor.master_windows is on for two seconds

#

Okay so this works in the gui at dev->template:

{{ 'open' if is_state('binary_sensor.master_windows', 'on') and (states.binary_sensor.master_windows.last_changed < (now() - timedelta(seconds=2))) else 'closed' }}

but I'm getting an error when I add it to my config above like this:

#

ha.. Talking to myself. Solved. Would not have happened if I had not come here and posted. Thanks for listening. πŸ˜‰

strong idol
charred dagger
#

Seems like your {% set sensor part isn't working. It sets it to None.

#

If it works in /developer-tools/template it may be a " vs ' issue.

strong idol
#

It does not work in /developer-tools/template (anymore). But it used to work there ten days ago.

keen sky
#

hello , i have one zigbee button, which have not entities and when i do automations I use event and describe event data. Is it possible to do some template to have somehow friendly named entity for that ?

spiral flax
#

hello is there a shortcut to get the current sensor's state in the value_template?

ivory delta
#

What 'current sensor'? πŸ€”

spiral flax
#

current sensor = the current that's value is currently processing while the template is running

#

in OOP it would be something like this.state

ivory delta
#

I think you're confused...

spiral flax
#

where the this referes to the current object and the state is the value of the state

ivory delta
#

Templates aren't a general thing that exist everywhere. Templates are used in scripts/sensors/etc.

#

Depending on where you use them, they'll look different.

spiral flax
#

yes, but I don't want to write always the entity id out to get the current state value if the mqtt message doesn't contain it

ivory delta
#

If there was a magical this.state, you'd be asking for the state of the script/automation/whatever.

#

Explain what you're trying to do.

#

Not how you're trying to do it.

spiral flax
#

I have a device that sends mqtt messages, I've wrote a custom template to extract one value from the message

#

however, sometimes this value is not there, in that case I want to keep the current, instead of update it to undefined/none

#

and for that I need to refer for the current state (value) of the sensor

ivory delta
#

Well, no, you don't. Use an automation instead to update something.

#

Only update it when you know the value.

spiral flax
#

o_O

ivory delta
#

The template won't know what entity it should give you the state of if you don't give it an entity ID. So either type the whole template out properly or find another way.

spiral flax
#

then I guess I will write out the full id of the entity, coz writing that amount of automation to update entity states will be too much to do

#

just it would be better if the template knows the context

ivory delta
#

Forget what you know about other programming languages. this requires you having a reference to the current object in scope. You don't have that.

spiral flax
#

now I would have easier job

ivory delta
#

If you think there's a better way to do it, submit a pull request with the improved functionality.

spiral flax
#

yeah, first I need to take care about phyton

dreamy sinew
#

the context is the entire state machine

#

automation get additional context of trigger

ivory delta
#

Hence the need to specify which part of the state machine you want.

#

Or use scripts to avoid updating something when the value is unknown.

mighty ledge
dreamy sinew
#

beware circular references though

#

i think there was some protection added recently but that could definitely behave in unexpected ways

mighty ledge
#

it doesn't, never really did. They just have a warning

dreamy sinew
#

heh ok

mighty ledge
#

I think the warning is there if you're trying to average all sensors or something

#

like, you don't want to include yourself in your calculation

dreamy sinew
#

i thought i saw something for recursion

mighty ledge
#

well, there is an issue with recursion & groups

#

like group a contains items from group b and group b includes a, there is protection for that

#

with expand

#

its like a 3 second timeout

dreamy sinew
#

oops

#

my general view on sensors is "they deal with what is not what was." and that holds true for template sensors

mighty ledge
#

Yeah, I don't disagree. Just offering up work arounds if your saucy enough

glossy viper
ivory delta
#

Then you need to explain:

  • what you're trying to do
  • what the problem is
glossy viper
#

i'm trying to extract and view the body of a certain e-mail .

#

i tested imap connection and works, but i am not sure how to filter with template only certain mail

#

because the energy guys are sending more mails from same address

#

and i want to be retained only the mail containing 'Emitere factura' in subject

#

after this is retained, the i should get energy consumed and total value of invoice

#

problem: 1. not sure if value template for subject is ok

#
  1. search oeprators from and subject are not ok according to docs it should be
ivory delta
glossy viper
#

holly molly....need translator for those

ivory delta
#

It's a bash script. They look crazy but they're powerful.

glossy viper
#

so ...i should set some python reader in ha ?

ivory delta
#

Maybe it's not the option you want but it's an option.

#

No, it's not Python. bash is used by Linux.

#

It's a shell script.

glossy viper
#

oh..out-of-scope linux

#

maybe if the ram that arrived today help me have 8gb and make another vm with 2 gb...way to complicated

sturdy solar
#

Oh i cant send picture

#

Normaly the config file make a lot of switch named tv_voo , tv_appletv, tv_switch, ... but not really

#

He make a switch named tv_voo_2 for the tv voo, and switch tv_voo for tv apple tv ...

#

Its strange reaction

mighty ledge
#

Harmony now creates switches

sturdy solar
#

I have disabled the integration for manualy configure

#

But my configuration have strange reaction :/ i dont understand why

#

The first declaration of switch tv_voo are remplaced by tv_voo_2... realy#ly strange

#

And tv_appletv is remplaced by tv_voo... second switch dΓ©clarationπŸ€”

fleet wyvern
#

can i define target_sensor: value based on another entity attributes?

#

something like this: target_sensor: {{state_attr('climate.mco', 'current_temperature')}}

#

or do i have to create a sensor out of climate.mco attributes and then use that sensor as the value for target_sensor ?

dreamy sinew
#

That should work

fleet wyvern
#

if i use target_sensor: {{state_attr('climate.mco', 'current_temperature')}} when i press check configuration in settings >server controls i get the following error message

#

Error loading /config/configuration.yaml: while parsing a flow mapping
in "/config/configuration.yaml", line 451, column 22
expected ',' or '}', but got '<scalar>'
in "/config/configuration.yaml", line 451, column 84

#

ok, i added double quotes

#

now i get another error

#

Invalid config for [climate.generic_thermostat]: Entity ID {{state_attr('climate.mco_sonia_climate', 'current_temperature')}} is an invalid entity id for dictionary value @ data['target_sensor']. Got "{{state_attr('climate.mco_sonia_climate', 'current_temperature')}}". (See ?, line ?).

narrow glacier
#

Sounds like target_sensor doesn't want to take a template, so yeah; make a template sensor to give the value you want

celest tinsel
#

Writing my first template (well, copying). Does it go into config.yaml?

dreamy sinew
#

typically

celest tinsel
#

the templates docs don't really say

dreamy sinew
#

they can go in automation.yaml or scripts.yaml if you have them

celest tinsel
#

cool.

#

thanks

dreamy sinew
#

but it depends on what you're trying to do

versed idol
shell ferry
#

Can someone help me with templating? I'm trying to set value as float and use the value in numeric_state trigger, but the value is string instead of float. what am I doing wrong?
https://paste.ubuntu.com/p/2SKH4jqpgx/

fossil venture
shell ferry
#

okay, thanks! :)

fossil venture
#

I left one too many )

#

After the round()

shell ferry
#

so I should do automations like this instead?

  trigger:
    - platform: template
      value_template: "{{ states('sensor.xiaomi_airhumidifier_depth')|float <= 25 }}"
fossil venture
#

If it is an integer or you don't care about the fractional part. Otherwise use |float

shell ferry
#

yeah, just noticed that I want it to be float instead

#

thanks!

fossil venture
#

The main issues were in your sensor. Make sure to fix that too.

shell ferry
#

yeah, I did :)

fossil venture
ivory delta
#

If you want to visualise that it's hours, do the math...
somenumber + (2 * 60 * 60)

#

With simple multiples like 3600, it's easy to remember that's an hour... but when you want 12.5 hours?

versed idol
#

Thanks Tom. Thanks mono i will try it. Looks beautiful than +7200. Prayer time always change time to time, this is to turn on water pump 1 hour before and 2 hrs afterπŸ™

gray loom
#

Hi guys i have a motion sensor that i have integrated trough tellstick but its a switch and is not reacting in HA when i for example wave my hand. So i was thinking about making a binary sensor with template this is my code:

binary_sensor:
  - platform: template
    switches:
      switch.motion_sensor_10981222:
        movement:
          device_class: motion
          value_template: "{{ states('switch.motion_sensor_10981222') }}"

But im getting a error on

Invalid config for [binary_sensor.template]: [switches] is an invalid option for [binary_sensor.template]. Check: binary_sensor.template->switches. (See /config/configuration.yaml, line 42)

Can anyone guide me in the right direction?

fossil totem
gray loom
#

why does it expect "sensors:" argument when the point is to make a sensor FROM a switch?

fossil totem
#

the switches: line isn't applicable here, the example linked above i think does the exact thing you're trying to accomplish (turn a switch device into a binary_sensor)

#

because that's how it works my man πŸ˜„ you are creating a sensor. that line isn't talking about the source device.

narrow glacier
#
binary_sensor:
  - platform: template
    sensors:
      motion_sensor:
        friendly_name: "Motion Sensor"
        device_class: motion
        value: template: "{{ states('switch.motion_sensor') }}```
fossil totem
#

^^^

narrow glacier
#

replace motion_sensor and "Motion Sensor" with whatever entity id and name you want to use.

fossil totem
#

yaml is tweaky in general @gray loom , it can be counter-intuitive at some times. best solution is to follow the docs precisely. i've been using hass for a couple years and still have to refer back to examples like this.

#

just part of the fun πŸ˜„ let us know how it works out for you!

gray loom
#
binary_sensor:
  - platform: template
    sensors:
      switch.motion_sensor_10981222:
        friendly_name: "Motion Sensor1"
        device_class: motion
        value_template: "{{ states('switch.motion_sensor_10981222') }}"

changed to this and still no luck

#

are you sure about value:template:?

fossil totem
#

yes

#

switch.motion_sensor_10981222: is your problem

#

change that to motion_sensor.

#

that line is declaring the name of the new binary sensor you are creating

#

so, you tell it the name of the new device, down below you are telling it the name of your existing device in the template

gray loom
#

alright, its restarting now at least πŸ˜„

fossil totem
#

you got this my man πŸ˜„

narrow glacier