#templates-archived

1 messages · Page 84 of 1

stone skiff
#

but i'm not able to do that, because i'm very new to HA

mighty ledge
stone skiff
#

The Moes TV01-ZB doesnt provide a Sensor for the current Temperatur. I want to use it in a Sensor Diagramm and Better Thermostate as external Temperature Sensor

mighty ledge
#

right, but you said that your Moes TV01-ZB shows current_temperature: 19.9, but for some reason you can't use

Create a template sensor
{{ states('climate.whale_heater','current_temperature') }}
#

so, I'm asking "why can't you do that?"

stone skiff
#

because i'm very new and i dont know what to do

plain magnetBOT
#

Open your Home Assistant instance and show your helper entities

marble jackal
#

follow that link, and create a template helper

stone skiff
#

It is not the problem to find where to create them, but much more what to do there

marble jackal
#

choose, sensor and then enter that template in the field asking you for a template

#

replace the entity_id with your actual entity

mighty ledge
stone skiff
#

you mean this: {{ states('climate.whale_heater','current_temperature') }} ?

marble jackal
#

yes

#

that's a jinja template

stone skiff
#

whale heater is nothing of my Hardware

mighty ledge
#

well you need to find the entity_id of your climate device and replace it

marble jackal
#

looks like someting @arctic sorrel wrote

mighty ledge
#

while keeping the single quotes

stone skiff
#

climate.heizung_sz is the entity

mighty ledge
#

ok so what portion of that template would you replace?

marble jackal
#

then use that instead of climate.whale_heater

#

ah damn, too soon

stone skiff
#

and the Atribute is current_temperature

mighty ledge
#

right, so you don't change that

#

you just change climate.whate_heater to your entity_id

#

while keeping the quotes

stone skiff
#

So it should look like that? {{ states('climate.heizung_sz','current_temperature') }}

mighty ledge
#

Yes, if you paste that into the template, it will show you the preview

#

you can work in that window

stone skiff
#

ok. I will do so. Thank you very much

#

creating a new helper doesnt offer me "Sensor". Sorry my HA isGerman

marble jackal
#

first {} Template, then Template a sensor

#

don't know what that would be in German

stone skiff
#

Can i change the HA Language easily to english?

stone skiff
marsh cairn
#

Looks like the value of an attribute is meant

stone skiff
#

Sensor None has device class 'temperature', state class 'measurement' unit '°C' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'off' (<class 'str'>)

stone skiff
#

Thank you!

marble jackal
#

Hehe, totally overlooked that

frail dagger
mighty ledge
#

never assume!

compact pond
#

Hi all,

Is it possible to get the entity names from the members of a binary sensor group?

I know it is possible in normal sensor groups, but a binary sensor only returns on or off. Ive tried to map on entity ID and friendly name but both are undefined

inner mesa
#

aren't they in the entity_id attribute?

#

they are

compact pond
#

Dont think so.

{{ states('binary_sensor.group_always_available_apps')|map(attribute='entity_id')|list }} this results in undefined undefined, while map('entity_id') results in a filter error

inner mesa
#

you needed map(attribute='attributes.entity_id')

#

you can see them in devtools -> States

compact pond
#

I cant find any group in the developer tools

inner mesa
#

not sure what to tell you

#

you claimed that this is a binary_sensor group: binary_sensor.group_always_available_apps

#

is it?

compact pond
#

Yes, it is a binary sensor group

inner mesa
#

that wholle template is broken

compact pond
#

Oh wait

#

I had to refresh my browser apparantly

inner mesa
#

if you want the list of entities in that group, you just need:
{{ state_attr('binary_sensor.group_always_available_apps', 'entity_id') }}

compact pond
#

Now i have the group into the states tab

compact pond
#

I really have no clue what to use when,,,

inner mesa
#

your attempt was taking the state of the entity and then trying to find state object properties in the string

compact pond
#

Yea, true. So actually i did everything in the wrong order innit

robust star
#

Still fiddling with that derivative sensor, it seems to be reporting okay now so im working on a template sensor to catch the trends, so far i got this:

  - sensor:
      - name: "Bathroom Humidity Trend"
        unique_id: bathroom_humidity_trend
        state: >
          {% set rate = states('sensor.bathroom_humidity_rate_of_change')|float %}
          {% if rate > 0.3 %}
            Rising
          {% elif rate < -0.15 %}
            Falling
          {% else %}
            Constant
          {% endif %}

My question here is, for the falling rate, obviously the humidity is dropping before it reaches minus - rates, what would be a better approach for this?

mighty ledge
#

not necessarily

robust star
#

As in, there is no better approach? :D

mighty ledge
#

well, there's a ton of different ways to approach this

#

I'm currently using something similar to you and it works OK

#

it really depends on your sensor update frequency and how wildly your humidity swings

#

e.g. last night at 4:30 am, my automation fired because my master suite decided to jump 3% in humidity

#

I should look into that

robust star
#

Hope the fan didn't wake you :o

mighty ledge
#

I was awake already

#

saw the sameish blip in the basement

robust star
#

Thats odd

mighty ledge
#

blue on top is master bathroom, tall peaks are showers

#

no clue what the blip was, but it was seen across the house

#

and of course, I can't see what's happening outside cause the battery is dead in that device

robust star
#

ghost in the machine 🫨

inner mesa
#

a moist ghost

robust star
#

were there any other type of ghosts 🫠

robust star
#

exactly my train of thought 😂

mighty ledge
#

pretty sure that was the ghost sex scene in GB1

#

Yep

#

anyways, I've been trying out random humidity crap for like 3 years

robust star
#

I put a condition in my bathroom fan automation, the bathroom has no windows so the light must be on for it to trigger the fan to the on state

mighty ledge
#

and what you have will probably work fine, but have hiccups

mighty ledge
#

I might have to steal that idea

robust star
#

Sure! Happy to help as well 👌

robust star
#

(Had to go to doggy school 😜)

mighty ledge
#

You'll just have to try it and see

#

if you're using it to turn on a fan, you'll know what I mean after some time

robust star
#

Hm okay

#

Everything needs a tuneup once in a while, gotten used to it

fallow gulch
#

I’ve got an MQTT sensor from EVCC showing the currently connected vehicle, which is updated to a null value when the car is unplugged.

I’m trying to use a trigger template to derive a sensor that will retain the state of the MQTT sensor post-disconnect, to show the last connected vehicle.

I’m having trouble with this, because the MQTT sensor state is empty (not unknown or unavailable) when the car is disconnected. How would I configure a trigger template to ignore the blank state?

#

Or am I better off configuring the MQTT sensor to report unavailable when there’s no vehicle connected? (This feels like a work-around solution to me)

lofty mason
fallow gulch
#

Yeah it literally shows nothing. I’ll give that a try.

willow wing
#

Hey, im searching here for an soloution to give out only the first word after each comma, someone has an idea?
the current output is "Marc Test, Xaver Test2" the output should be "Marc, Xaver" it should not stopped after two Names, because its a calendar and maybe three or more Birthdays can be 🙂

{{ summaries }}```
stone skiff
#

Yesterday i made this helper with a lot of help from here. It includes this:
{{ state_attr('climate.heizung_sz','current_temperature') }}
But i need to substract number.heizung_sz_local_temperature_calibration from this state_attr because the measured temp of the TVR is very incorrect and needs calibration.
Can this be done in this helper?

marble jackal
#

yes

#

you first need to get the state of that entity, using the states() function

#

but... all states are strings, so you need to convert that to a numer, using the float filter

#

to avoid errors when the entity is unavailable, it's best to provide a default value for the float value float(default=0) or simply float(0)

#

in total it will be:
{{ state_attr('climate.heizung_sz','current_temperature') - states('number.heizung_sz_local_temperature_calibration') | float(0) }}

stone skiff
#

thank you very much

plain magnetBOT
#

@stone skiff I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

you can't create sensors with attributes and availabilitiy in the helpers section

stone skiff
#

the attribute is not relevant as i guess

marble jackal
#

This must have been a very old tutorial though

stone skiff
#

yes, it may be. To mee it looks like i can do the same in the Helper. Correct?

#

i dont know whats the availabilty is for, but i could do it like in your example, if there is no value the default is "float(0)"

willow wing
#

@marble jackal do you have an idea for my problem a little bit higher too? 🙂

stone skiff
#

hmmm.... This
{{ states('sensor.shellyem3_C8C9A33C64F5_channel_a_energy') + states('sensor.shellyem3_C8C9A33C64F5_channel_b_energy') + states('sensor.shellyem3_C8C9A33C64F5_channel_c_energy') | float(0) }}
gives an error
required key not provided @ data['set_value']. Got None
What am i doing wrong?

marble jackal
#

you are only converting the last one to float, you need to convert all of them to float

#

and if you want to use this on your Energy dahboard, it will become a mess

blissful anvil
#

Is there a way to trigger an automation from calendars based on the event name atm i have to have a separate calendar for each event…

marble jackal
stone skiff
#

and {{ states('sensor.shellyem3_C8C9A33C64F5_channel_a_energy' | float(0) }} doesnt work

marble jackal
#

can you upload a screenshot (using imgur or similar) how you are now creating this helper?

stone skiff
#

sure.

marble jackal
#

the last one is missing the closing parenthesis for the states() function

stone skiff
#

yes, true. But even with closing paranthesis its noch working. Is it a Number Template i have to use?

marble jackal
#

no, a sensor template

stone skiff
#

thats the Problem 🤦‍♂️

#

i found it

#

damn.... thats complicated

marble jackal
#

What is/

#

?

stone skiff
stone skiff
marble jackal
stone skiff
#

ok. no i dont use it there.

plain magnetBOT
#

@stone skiff I converted your message into a file since it's above 15 lines :+1:

stone skiff
#

i cant even delete this helper now

scenic verge
#

how can i make the following a "higher then" value?

#

{{ 'light-green' if states('sensor.basement_car_charger_power') == 'on' else 'dark-grey' }}

#

perhaps this? {{ 'light-green' if states('sensor.basement_car_charger_power') == '>50' else 'dark-grey' }}

marsh cairn
#

You would have to convert the state to an integer or float. And is is either equal (==) or higher/higher-equal/lower/lower-equal (> >= < <=) - not both at the same time

stone skiff
marble jackal
#

that's a string comparison

#

you need to convert the state to a number

#

otherwise something like '6' >= '50' will retern true and will give you the wrong color

plain magnetBOT
#

@delicate dagger I converted your message into a file since it's above 15 lines :+1:

delicate dagger
#

Hello together, i got 5 sensors, and only want to output the one witch "Falcon 9" in the vehicle attributes fields, see code above.
My question is, the output shows that it correctly finds falcon 9 in sensor one, but it cant find it in the starship_launch object

stone skiff
#

but somehow i miss the "then" part in front of the "else" part

marsh cairn
#

This would translate to something like:
"If car charger power is bigger or equal to 50 then value is 'light-green', else value is 'dark-gray'"
It is just another way of writing

{% if states('sensor.basement_car_charger_power') | float(0) >= 50 %}
  'light-green'
{% else %}
  'dark-gray'
{% endif %}
stone skiff
#

Understand. Thnx

trail ginkgo
#

I have a few template sensors, that spit out something like "2024-09-08 17:15:06.232492+07:00" ... I would like this to look a little bit nicer.

Do I do this by changing the output of the template to what i want it to look like? Or is it possible I have this delivered to the frontend, and the frontend then 'makes it look nice'?

marble jackal
#

A sensor with a state like that, and device_class: timestamp will show as eg 12 hours ago or in 3 minutes on the frontend

trail ginkgo
#

I use the relative strings in some cases where accuracy is not all that important, because they quickly devolve to quite broad statements.

#

like "Last week" 🙂

marble jackal
#

you can use strftime on the template result to convert it to something easier to read, see https://strftime.org for possible options

#

eg {{ utcnow().strftime('%H:%M') }} will return 11:16

trail ginkgo
#

Ok, I'm familiar with that. So in the template then.

marble jackal
#

yes

cursive ice
#

is it possible to create a % sensor from 4 entities (its tides I have low tide and low tide 2 and high tide and hight tide 2 min is 1 max is 6 (so one could show 5.38 etc) as I have 2 tides (live near a estery)

marble jackal
#

possibly, but I have no idea what you want to achieve based on that description

trail ginkgo
#

Perfect. Thanks very much for your help!

cursive ice
#

so I have 2 tides a day, I have the heights in meters for low and high twice, I wanted to know if its possible to combine them all and have a percentage level (base on min 1 to max 6 meters), probably wont work as have to calculate the drop or rise over the gaps between times.

mighty ledge
#

You want a percentage of the height?

#

Still not following

cursive ice
#

yes, I want them turned into a % from the hieght which has a min of 1 and max of 6 meters

trail ginkgo
#

Is it possible to contain a url as the state of a template sensor, and for that link to then be clickable in the frontend? I guess this is more a #frontend-archived question.

mighty ledge
mighty ledge
#

You're better off using a markdown card in the frontend

#

which you can use markdown to format your link

cursive ice
#

sensor.high_tide_height and sensor.high_tide_height_2 for high

#

sensor.low_tide_height and sensor.low_tide_height_2

mighty ledge
#

{{ (states('sensor.high_tide_height') | float(0) / 6) * 100 }}

#

if you want to remove the lower bound...

#
{{ ((states('sensor.high_tide_height') | float(0) - 1) / 5) * 100 }}
trail ginkgo
mighty ledge
trail ginkgo
#

ah ok

mighty ledge
#

or you can just use an iframe

trail ginkgo
#

Did not even know there was such a thing as a markdown card! Excellent.

#

Thanks very much for your help!

#

Hm so the idea is I write a template that spits out markdown, and thats what i put into a markdown card?

mighty ledge
#

That's 1 use

#

you can also use html

#

because markdown allows that

#

you can also just write text

trail ginkgo
#

this is promising.

#

And themes too, i see. much to explore!

#

i could use this to build clickable lists of entities, even ... i think?!

mighty ledge
#

probably not because you'd need tokens for logging in

#

there are tap actions for that, but I'm not sure if the html elements are usable in markdown

trail ginkgo
#

ok ... well, thats future rob talking. first things first ... i want a clickable map link based on gps coordinates.

cursive ice
#

thanks pedro helped a lot thank you

trail ginkgo
#

WHOAH ... so easy! LOVE IT!

#

Thanks again!

#

I use a webhook to accept a bunch of data from a shortcut on my iPhone. Right now, the webhook automation stores those in helpers. This shows in the frontend like editable fields, but they're not intended as such.

Is there a template sensor possible that gets filled directly from such a webhook?

mighty ledge
#

Yes, template sensors

#

yaml only

#
template:
- trigger:
  - .. webhook ..
  sensor:
  - name: ...
    state: ...
trail ginkgo
#

from the state: {{ xxx }} ... how do i then reference the webhook json? the same way as i do it in the automation?

mighty ledge
#

yep

trail ginkgo
#

huh

#

sometimes life is simple, eh!

mighty ledge
#

I suggest you put the content in an attribute so that you don't have to worry about the 254 character limit

#

e.g.

trail ginkgo
#

oh they're just some floats and integers

#

so in THIS case its not a big deal

#

but ... please explain 🙂

mighty ledge
#
template:
- trigger:
  - .. webhook ..
  sensor:
  - name: ...
    device_class: timestamp
    state: "{{ now() }}"
    attributes:
      content: "{{ ... }}"
trail ginkgo
#

got it!

mighty ledge
#

which will give you a sensor that tells you when it recieved the webhook, with an attribute that has your content

#

You can even build automations off the sensor's time

trail ginkgo
#

could be an elegant solution in some cases.

#

k ... going to work on that tomorrow.

dinner time 🙂

#

Thanks for taking the time to help field my several questions!

#

to field or to help with ...

#

anyway, much appreciated!

compact pond
#

Hi friends,

Can someone explain me please why this doesnt work as expected?

{{ states('sensor.truenas_system_cpu_usage')|float(0) }}%

The thing what does not work is the |float(0) filter. I expect to get a rounded number without a number behind the dot, but i still get it

mighty ledge
#

round does that

#

int chops the decimals without rounding

#

float keeps it a "floating point decimal"

compact pond
#

Ah i see! Many thanks for the clear explaination! 😄

#

I didnt know you could convert something to int when it contained a dot or something

robust star
#

@mighty ledge After yesterdays discussion i gave "claude.ai" some humidity data, some context on the available sensors and the climate here and it came up with a bunch of sensors "for the most accurate result". haven't checked it for errors yet but at least it looks interesting 😂
https://pastebin.com/hUq2TbLK

mighty ledge
#

but you can make those sensors pretty easily with the statistics integration

#

definitely worth a shot

#

The principle makes sense, the HA bullshit is.... bullshit

#

You def don't need all those template entities

#

TBH, I'll probably try that out

robust star
#

The statistics you mean?

mighty ledge
#

no, statistics integration

#

it allows you to create all the things the AI is assuming exists.

#

i.e. sensor.house_average_humidity

robust star
#

Ah that, yeah the helpers page right

#

Already created some average helpers for the house before

robust star
#

It gets worse when you ask it to factor in the temperature

#
template:
  - sensor:
      - name: "Bathroom Absolute Humidity"
        unique_id: bathroom_absolute_humidity
        state: >
          {% set temp = states('sensor.bathroom_temperature')|float %}
          {% set rel_humidity = states('sensor.bathroom_th_humidity')|float %}
          {% set abs_humidity = 6.112 * 2.1674 * (rel_humidity / 100) * 
                                 exp((17.67 * temp) / (temp + 243.5)) / (273.15 + temp) %}
          {{ abs_humidity|round(2) }}
        unit_of_measurement: "g/m³"
#

not sure where those numbers came from (edit: Its based on the august-roche-magnus approxmiation for calculating the saturation vapor pressure of water in air)

fair gull
#

Hey I am trying to wrap up my automation code and I want to put multiple test in one condition. How do I test if friendly name of entity contains any of strings because this clearly does not work.

  {{ True }}
{% else %}
  {{ False }}
{% endif %}
mighty ledge
#

You have to write that out multiple times

inner mesa
#

if you ever feel the need to return true or false, just return the test

mighty ledge
#

{{ x in y or z in y }}

inner mesa
#

could do something crazy like
{{ ["bar"]|select('in', ['foo', 'bar'])|list|length > 0 }}

mighty ledge
#

I think regex_findall would be the best, or search

#
{{ state_attr('sensor.wejscie_person_count', 'friendly_name') | search('bicycle|all') }}
#

stupid but that would avoid the or's

inner mesa
#

ah, I was trying to use search just like that, but didn't think to just use it as a filter by itself

#

that's exactly what I was going for

mighty ledge
#

tbh, I didn't think about it until you tried to get all fancy

#

fancy rob

haughty breach
#

Might want to throw a true in there to ignore case... if you're the type that uses caps in a Name

fair gull
#

Thank You all. I finally decided to pass on wrapping code and just went with two {% if 'x' in state_attr('sensor.y', 'friendly_name') %} combined with "or" since that is clear trough UI.

pale crane
#

Hi guys! I've created a "Helper" in the gui of type "Template -> Number Template " and added {{ 1*5 }} as a template but all I get is required key not provided @ data['set_value']. Got None how do I createa a number template showing a number ?

lofty mason
pale crane
#

I want the helper to return a number

lofty mason
#

That's a template sensor.

pale crane
#

Oh.

#

aah. I was hung up in binary sensor 😄

lofty mason
#

Template number is a UI interactive control... it's a bit weird and advanced usage.

pale crane
#

Thanks, this worked 🙂 (got it!! thanks!)

hasty notch
#

im hoping this is the right/best place for my question - im trying to set up an influxdb sensor to pull data back to HA for a binary sensor. I have the query in influxdb (1.x.x) language working, but need help with the yaml/jinja in the config.yaml file

#

the 'correct' influx query is this:
SELECT count("state") AS "count_state" FROM "homeassistant"."autogen"."state" WHERE time > :dashboardTime: AND time < :upperDashboardTime: AND "entity_id"='tortoise_wheel_wheel_rotation' GROUP BY time(:interval:) FILL(null)

#

im confident in the measurement and where fields being correct in the HA config but not sure if i need to be creating a value template or what

lofty mason
#

And you'll need to check that the string returned by that matches the expected format

hasty notch
#

thanks - still no joy but at least that part is probably fixed. wondering if i need to fix the field option as in the influx db options the 'field' column i have to manually select 'count' instead of min/max/mean...and count_state is the 'as' but a few permutations havent gotten me the value yet

floral steeple
#

hi all, I have this automation which tells me if a light is on based on the location of a light/lux sensor. It works, but the problem is, when it sends the notify message, it does not include which sensor but rather just says You left the house but may have been left on. it should say the location in the message. Here's the yaml.
http://pastie.org/p/5cR8lorXhiGuvRmLWQFirQ
thanks

lofty mason
meager crown
#

Hi, I am having some trouble editing a helper template which I am almost certain was created in the UI, but is marked unmanageable in the helper UI. It's not present in my configuration.yaml and I have no other template files included in the config. I seem to be unable to edit or delete the helper. HA version 2024.9

marble jackal
#

does it show like this under helpers (so with that pencil icon)

meager crown
marble jackal
#

Then it's not created in the GUI and must be somewhere in your config.

#

Does it have a valid state currently?

meager crown
#

Yes, it has a state and changes as it should. But I cannot edit it. I have searched the configuration.yaml and it's not there

#

Hang on... I may have found it. Disregard this major brain fart of a question 🙂

marble jackal
tawdry pond
#

I finally moved from OWM 2.5 to 3.0. How can I get the high temp of the day? (I assume this is a templating question)

#

Eugh. Maybe it's messier than that because I might need to call get_forecast.

marble jackal
#

Yes, you need to do that (which is more related to you updating HA instead of moving from OWM 2.5 to 3.0)

tawdry pond
#

Then my question would turn into how do I template grabbing a specific value, such as today's high temp, from the get_forecast result

gilded tinsel
#

so, I'm trying to get the value of an entry in a dictionary, using a variable as the dictionary key

value_template: >- {{ (as_timestamp(now()) - as_timestamp(state_attr('sensor.variables', 'variables')[{{variable_dictionary_name}}].value, default = 0) | int > 60)}}

#

Home Assistant will argue that [ {{variable_dictionary_name}} ] is not a valid format, is there a way to do it?

gilded tinsel
#

solved:
state_attr('sensor.variables', 'variables').get(variable_dictionary_name)

inner mesa
#

You were unnecessarily nesting your templates above

gilded tinsel
#

what do you mean?

inner mesa
#

I mean that you have a template and then tried to use {{ variablewhatever }} inside it

#

When you just need to use variablewhatever

#

Don't ever do {{ {{ something }} }}

#

a lot of folks think that {{ variable }} is some general way to reference a variable in a template, and it's not

gilded tinsel
#

mmm not sure I understand

#

the variable is set in a previous step of the automation, based on the trigger id

#

then reused multiple times in the automatio, not only in this template

inner mesa
#

I'm make a very simple point

gilded tinsel
#

oh maybe you just mean i should NOT do [ {{variable}} ], and use [ variable ]

#

but it won't work, it's not a valid format

inner mesa
#

oh maybe you just mean i should not do [ {{variable}} ], and use [ variable ]

gilded tinsel
#

you need to use the get(variable) method

inner mesa
#

that

#

no, you don't need to do that

#

it's the same thing

gilded tinsel
#

nope, ha will throw an error

inner mesa
#

the only difference is that you can specify a default with .get(xxx)

#

alright

#

it won't if you do it right

#

what you showed above is wrong

#

it is absolutely correct that [ {{variable_dictionary_name}} ] is not valid syntax

gilded tinsel
#

but [variable_dictionary_name] is wrong too

inner mesa
#

it's no different from .get(variable_dictionary_name)

gilded tinsel
#

ha will throw an error both when saving the automation and when using it in the template editor

inner mesa
#

ok

inner mesa
#

not much to be gained by arguing at this point, IMO

marble jackal
#

okay, just wanted to chip in, as he seems to be using the template sensor to store variables I posted on the forums 🙂

inner mesa
#

ah, ok

#

at some point, if someone is happy with their solution, let them be happy 🤷

#

It only works if the earth is flat
Well, enjoy your flat earth, then 🙂

marble jackal
#

using get is a bit more forgiving, so it can be helpful 🙂

inner mesa
#

it definitely has advantages, just not really in this specific case, and not to solve any problem here

gilded tinsel
marble jackal
#

does the variable exist?

#

which error does it return in devtools > templates?

gilded tinsel
#

Let me get my laptop back, I’m on the phone right now

#

i'm not sure I can post pictures

#

give me a sec

#

{% set variable_dictionary_name = "last_garage_open_notification_for_david" %} {{ state_attr('sensor.variables', 'variables').[variable_dictionary_name].value }}

#

TemplateSyntaxError: expected name or number

#

it's the same if I don't use the .value

#

the value exists

last_garage_open_notification_for_david:
value: "2024-09-12 16:38:30.767990+02:00"
timestamp: "2024-09-12T16:38:30.769483+02:00"

gilded tinsel
#

i asked for a syntax help, not your daughter hand

gilded tinsel
#

found the error, I had the "." before the []

onyx glacier
#

i'm using this to see an attribute to an entity but i want to tag something on the end like TB and i suck with templating what am i missing?

marble jackal
#

I was aout to say that 🙂

onyx glacier
#

type: entities
entities:

  • entity: sensor.viper_home_viper_home_storage_g
    type: attribute
    name: PLEX Free Space
    attribute: AvailableSpaceMB
marble jackal
frail dagger
inner mesa
#

You got your chocolate in his peanut butter?

frail dagger
#

lol well, when you put it that way... YES

midnight dawn
#

Trying to get a Volume Control to hide if nothing is playing, Template coder says this is accurate but its not working. Any ideas?

type: custom:mini-media-player
entity: media_player.media_room
group: true
artwork: material
hide:
power: true
icon: true
source: true
progress: true
volume: >
{%- set volume = states('media_player.media_room') %} {%- if volume =='playing' %}false {%- else %}true {%- endif %}

inner mesa
#

I don't see anywhere in the docs where it says that you can put a template there

compact pond
#

Hey all,

Is there a possibility to query (retreive data out of an MS sql server) from out a template?

frail dagger
plain magnetBOT
hybrid yacht
#

Trying to determine if this is something I can create with a template or if I need to go to the developer for a fix but the Balboa Spa Client (in HACS) creates two switches for me for the hot tub jets, Pump 1 and Pump 2, now Pump 2 is on/off it is binary, Pump 1 has an attribute of Pump 1 (named the the same as the entity) that has three values, Off, Low, High. My question is, is it possible to change an attribute of a switch or is that a read-only value basically? I THINK that is the case but wanted to confirm

frail dagger
#

You could create a template switch based off the attribute and then hide the existing entity though. But, I don't think that's what you are really asking for here?

hybrid yacht
#

I probably didn't explain this properly, Pump 2 is fine (on/off only), It is Pump 1 that I wanted to setup a fan.template that had off, low, high (for a multi state switch) but the off, low, high are attributes not states of the switch Pump 1. From testing, you can't modify an attribute of a switch correct?

stray horizon
#

Hi, I'm working on a notification where I indicate an action button to launch Google Maps. This works, but I would like to add a parameter like the destination address. With action OPEN, nothing happens, with action URI and app://com.google.android.apps.maps parameter, Google maps opens but without destination. Do you know if this is possible?

hasty notch
#

so ive got the influxdb sensor mentioned above 'working' in the sense that I now get the desired value in HA

#

but

#

trying to set up the desired time range is not working. the example config shows: time > now()-1h - which does indeed work as syntaxed there, but if i try to put in today_at() instead of now()-1h it fails

#

how is today_at() formatted differently? or how would you recommend getting the same result if the context might be now()- X hours back to midnight

hallow plover
#

let's say there are a bunch of entities with names like sensor.sensor_1_geocoded_location, sensor.sensor_2_geocoded_location, etc. Is it possible to get an array of all the values if I don't necessarily know the number of matches there will be?

Is it possible to somehow select the most recently updated of those values?

haughty breach
#
{{ states.sensor | selectattr('entity_id', 'search', '_geocoded_location') 
| sort(attribute='last_changed', reverse=true) | map(attribute='state')
| reject('in', 'unknown|unavailable') | first }}
hallow plover
#

Awesome, thanks.

stray horizon
vale osprey
#

Hi guys, i'm finding it strange that there are so many helpers nowadays in HA and there is no Stopwatch. Is it the case?

#

I tried working around it by using a timer helper, but seems the timer helper only exposes the remaining attribute when the state is set to paused. Any help here?

heavy crown
#

Hi all, am trying to find a way to list all my rest-sensors. I tried via platform but that did not work (or; I donot know how)

marble jackal
#

{{ integration_entities('rest') }} might be a good starting point

lucid thicket
# vale osprey I tried working around it by using a timer helper, but seems the timer helper on...

You can set up a trigger-based template sensor or an automation with an input datetime helper. I would personally use custom events and buttons on a dashboard to start/stop/reset. The automation it trigger-based template sensor would record the datetime when it is started, and then when it is stopped it would calculate the difference between the end time and the start time.

If your goal is to display the actively-running time, you’ll only be able to do 1-seconds updates on the frontend. I would recommend against creating an entity that actually updates every second.

lucid thicket
# stray horizon Does anyone have any idea on this topic please?

You might have better luck on #android-archived . If you know what the output of your template needs to be, you can come back to this channel for help on how to write the template to generate what you want. But the people who hang out in this channel don’t necessarily know anything about Google maps on Android and actionable notifications

floral shuttle
#

trying to map my Zwave devices to their NodeID for debugging purposes I am having a hard time, and seek some assistance.
on the individual device_id we can do this {{device_attr('ef847e6d3729aa35d9ab7fdb66e38284','identifiers')}} {{device_attr('ef847e6d3729aa35d9ab7fdb66e38284','name_by_user')}}
which results in
{('zwave_js', '3967834106-33-271:1538:4099'), ('zwave_js', '3967834106-33')} Afzuigkap Zolder
The 33 is the nodeID, so ideally I seek {'Afzuigkap Zolder','33'}
Next this would have to iterate over all devices connected to the Zwave integration

{{integration_entities('zwave_js')}} doesnt really help so looking for another means

lucid thicket
#

this would be a list of tuples containing a device name and it's node:

{% set entities = integration_entities('zwave_js') %}
{% set names = entities | map('device_id') | map('device_attr', 'name') | list %}
{% set ns = namespace(nodes=[]) %}
{% for x,y in entities | map('device_id') | map('device_attr', 'identifiers') | list %}
  {% set ns.nodes = ns.nodes + [x[1].split('-')[1]] %}
{% endfor %}
{{ zip(names, ns.nodes) | unique | list }}
floral shuttle
#

Perfect! Thank you very much. Nice use of the new zip feature too 😉

#

Using name_by_user is even more useful, since it has more meaning than the ‘name’. Beautiful!

lucid thicket
floral shuttle
queen meteor
#

🎉

#

Heck yeah!!!

tender prawn
#

GREAT Channel!!!!!!

dreamy sinew
#

Oh, nice

bitter atlas
#

phnx new home lol

dreamy sinew
#

Lol pretty much

wise arrow
#

{{ halp }}

queen meteor
#

@wise arrow it should be {{ "halp" }}Otherwise you would get an error 'halp' is not defined 😉

wise arrow
#

Mr ninja himself to the rescue mildpanic

queen meteor
#

I just learned today that hass means hate in german... that makes hassbot a hatebot 😛

dreamy sinew
#

Sounds about right

queen meteor
#

lol

dreamy sinew
#

.badbot

wise arrow
#

Du, du hast mich, du hast mich

queen meteor
#

@dreamy sinew we shoulc change to BadAssBot 🙂

dreamy sinew
#

AssBot?

wise arrow
#

Badass is probably something worse in another language

bitter atlas
queen meteor
#

tink's got a good name HappyBot

dreamy sinew
#

Tinkerbot!

bitter atlas
#

Tinkinator

hexed wing
#

@queen meteor Give the thing a random girls name

#

always works 🙂

dreamy sinew
#

karen

queen meteor
#

lol

dreamy sinew
#

"sonandso's message has been moved" Thanks karen

hexed wing
#

Lucy? (reference to Hackers)

buoyant pine
#

Ada?

dreamy sinew
#

Jane from "speaker for the dead" in the enders game world

buoyant pine
#

GlaDOS

dreamy sinew
#

EDI from Mass Effect

buoyant pine
#

are you still there?

bitter atlas
#

Rosie from the Jetson's

queen meteor
#

Dolores from Westworld

wise arrow
#

You are all forgetting about Molly

queen meteor
wise arrow
#

Yes

#

This is the new lounge

#

You renamed it

queen meteor
#

first day... let the new channels settle down and hopefully people notice and post in appropriate channels

bitter atlas
#

think we ruined that already lol

dreamy sinew
#

templates are too scary 😛 this can be our secret hangout

bitter atlas
#

don't worry codex will be coming along shortly

dreamy sinew
#

**Templates can be tested via devtools > Templates **

#

can we get our first pin?

gray cedar
#

I'm at the point in my HA learning where I'm still copying and pasting what works when it comes to templates. I need help with one if someone can help. I have the HACS integration for unifi. https://github.com/custom-components/sensor.unifigateway I found a template online that works for someone's dashboard but it's not working for mine. Here is my configuration.yaml https://hastebin.com/xakivosece.bash The template part at the VERY end is where I'm stuck.. It works for someone but not me and that specific sensor isn't available to me via devices or integrations... My sensors look like this: sensor.unifi_gateway_3_bytes_received

dreamy sinew
#

see the message i just got pinned

gray cedar
#

trying it.. undefined error.. descriptive.. 🙂

dreamy sinew
#

walk it back to .attributes then

gray cedar
#

I don't understand what that means.

dreamy sinew
#

{{ states.sensor.unifi_gateway_wan.attributes }}

#

see what that says, then drill down from there

#

or {{ state_attr('sensor.unifi_gateway_wan', 'gw_system') }}

queen meteor
#

@dreamy sinew are you familiar with template editor? if not, click on the devtools icon on the left nav menu under developer tools and go to template editor. clear the text you see there, and paste {{ states.sensor.unifi_gateway_wan.attributes['gw_system-stats']['cpu'] }}. you will see the output on the right side.

dreamy sinew
#

...me?

queen meteor
#

you can then play around with the code

#

@dreamy sinew sorry! 😂

dreamy sinew
#

😦

wise arrow
dreamy sinew
#

(╯°□°)╯︵ ┻━┻

queen meteor
#

@gray cedar check my message earlier!

bitter atlas
#

🤣

wise arrow
#

You just got burned @dreamy sinew

bold valley
#

you need to provide the attribute when using state_attr

dreamy sinew
#

oh right

gray cedar
#

I'm using the template editor.. yes removing the ending shows legit things on the right: {{ states.sensor.unifi_gateway_wan.attributes }}

queen meteor
#

by the time I right click and select mention, @dreamy sinew message took over

dreamy sinew
#

fixed

queen meteor
#

@gray cedar what the hell is you profile picture?

gray cedar
#

meretrix is latin for courtesan

#

@queen meteor

queen meteor
#

It is the profile pic in question

wise arrow
#

A Santa fondling a bikini lady mildpanic

gray cedar
#

^ picture of what it shows now..

wise arrow
#

Wtf

#

That was the strangest thing I've ever seen

#

The webpage that is

gray cedar
#

first google result. "Temporary picture hosting"

silent barnBOT
#

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

gray cedar
#

damnit

queen meteor
#

my firewall blocked that site, and I can't see it. must not be a safe site!

gray cedar
#

ok.. next time.. just trying to make progress

queen meteor
#

I should add that to block list

gray cedar
#

😢

#

how do I test for the cpu part since that's a HACS thing?

wise arrow
#

It's a hacs thing?

eternal stag
#

is there an easy HA/template way to count the number of times a sensor was in a state? for example, counting how many time a sensor was a particular value

gray cedar
#

its a pulgin in hacs that's poorly documented and I can't figure it out

#

look at my 8:10pm message

eternal stag
#

we're not all in the same timezone btw

gray cedar
#

look at my message 20 minutes ago 🙂

bitter atlas
#

@eternal stag something like that would have to pull information from the db or you would use something external like grafana to accomplish. if you were looking for all time ect

eternal stag
#

ok so nothing "native"

#

might look at how the mini graph works, because clearly it's getting data, can just do a predicate test for each entry

bitter atlas
eternal stag
#

well there has to be a better way, the mini graph card can get n-number of hours just fine

bitter atlas
#

pretty sure those pull from the db to fetch that information, can't imagine they are storing that anywhere

queen meteor
#

@eternal stag that would be easy to do. I do something like that using a simple variable that I increment every time the sensor becomes the state I am looking for. I display it in my UI. I have another automation to reset at midnight, so that it keeps daily count.

eternal stag
#

hmmm... that's a good idea

queen meteor
#

I do that for counters, where I keep track of which room has more traffic, I could use that information to to start vacuuming

silent barnBOT
queen meteor
#

Yep. You could use that.

eternal stag
#

hmmm... i actually also want to track total time 🤔... basically, i want to know how LONG the sensor is active for the day

#

looks like history_states might be what i'm after?

queen meteor
#

You could do that too. Instead of count, you keep accumulating the seconds that it is on a particular state and convert to time.

#

You could do that using sql sensor if you are good with sql statements.

eternal stag
#

hmmm... yeah i thought about the adding up seconds

queen meteor
#

There are many ways to skin a cat.

buoyant pine
opaque cove
#

hi folks - i am having trouble with the template syntax to use a REST sensor to set a sensor value from a JSON feed. my template works in the template editor but not when i put it in config.yaml

buoyant pine
#

Let's see the sensor config

#

Format as code pls. Three backticks above and below

opaque cove
#
- platform: rest
  resource: https://www.data.act.gov.au/resource/ufvu-jybu.json?station=Civic
  name: ACT_air_civic
  value_template: '{{ json_value[0].pm2_5_1_hr }}'
  json_attributes: 
    - pm10_1_hr
    - pm2_5_1_hr
    - date
    - time
#

and here is the JSON

#
[{"station":"Civic","gps":"(-35.285307 ,149.131579)","datetime":"2020-01-30T13:00:00.000","pm10_1_hr":"45.94","pm2_5_1_hr":"47.57","pm10_24hr_rolling":"65.13","pm2_5_24hr_rolling":"50.79","date":"2020-01-30T00:00:00.000","time":"13:00:00"}
,{"station":"Civic","gps":"(-35.285307 ,149.131579)","datetime":"2020-01-30T12:00:00.000","pm10_1_hr":"49.89","pm2_5_1_hr":"64.45","pm10_24hr_rolling":"64.76","pm2_5_24hr_rolling":"50.31","date":"2020-01-30T00:00:00.000","time":"12:00:00"}
,{"station":"Civic","gps":"(-35.285307 ,149.131579)","datetime":"2020-01-30T11:00:00.000","pm10_1_hr":"81.17","pm2_5_1_hr":"81.7","pm10_24hr_rolling":"64.26","pm2_5_24hr_rolling":"49.51","date":"2020-01-30T00:00:00.000","time":"11:00:00"}
#

the json_attributes come out as expected but the value is just unknown

buoyant pine
#

Should be value_json I believe

opaque cove
#

doh. i will try that

#

🥳 thanks Tediore

neon barn
#

is this syntax correct for adding values of 2 other templates?

value_template: '{{ ( (states.sensor.solar_pac | float) + (states.sensor.solar_power_consumption | float) )}}'
dreamy sinew
#

could work

#
value_template: " {{ states('sensor.solar_pac')|float + states('solar_power_consumption')|float }}"```
#

little shorter and a lot safer

neon barn
#

why is it safer?

dreamy sinew
#

its in the docs

#

tl;dr, won't throw exceptions if those entities don't exist for some reason

neon barn
#

if I have double-quotes on the key I need to escape it, right?

dreamy sinew
#

in what way?

neon barn
#

like this: states.sensor.solar_data.attributes["Body"]["Data"]["YEAR_ENERGY"]["Value"]

dreamy sinew
#

just use '

neon barn
#

hm, I had to use double-quotes as the start of the template, escaping single quote didn't work for the key name

neon barn
#

ty

neon barn
#

hm, I can't access the json keys with the "safe" method, this is what I tried:

states('sensor.solar_data.attributes[''Body''][''Data''][''DAY_ENERGY''][''Value'']')
states('sensor.solar_meter_data.attributes[\"Body\"][\"Data\"][\"PowerReal_P_Sum\"]')

#

interesting, the "safe" method doesn't for attributes, unless I'm doing something wrong

#
{{ states('sensor.solar_data.attributes["Body"]["Data"]["TOTAL_ENERGY"]["Value"]') }}
{{ states.sensor.solar_data.attributes["Body"]["Data"]["TOTAL_ENERGY"]["Value"] }}
#

produces: unknown and 1851561

#

this worked: {{ state_attr("sensor.solar_data" , "Body").Data.TOTAL_ENERGY.Value }}

#

not sure if it's the right way to access it, though

dreamy sinew
#

seems like the custom component is returning an object instead of a dict

mighty ledge
#

@neon barn {{ state_attr("sensor.solar_data" , "Body").Data.TOTAL_ENERGY.Value }} is correct

#

for the 'safe way'

dreamy sinew
#

eh, since its an object will still throw an exception

#

just a different one

mighty ledge
#

only if it doesn't exist, but there's no 'safe way' with a method unless state_attr is changed to allow *args

dreamy sinew
#

an argument could be made that returning an object there isn't ideal

mighty ledge
#

rest sensors have no choice

dreamy sinew
#

or dumping an object to that attrib isn't good either

mighty ledge
#

that's definitely coming from a rest sensor

dreamy sinew
#

right, but maybe some other processing should be done before it gets to this point 😛

mighty ledge
#

You can't with rest

#

it's not like the MQTT sensor

dreamy sinew
#

as is right now, i'm saying the component should probably get some work

mighty ledge
#

Yes, it needs the mqtt attribute_template field

#

that would fix this

#

right now, rest only has the json attributes field which only works when rest returns a flat dictionary

#

it's super annoying

ancient lynx
#

So I have "{{ states.device_tracker|selectattr('state','eq','home')|selectattr('attributes.essid','eq','GUEST_SSID')|selectattr('attributes.mac','ne','00:00:00:00:00:00')|selectattr('attributes.mac','ne','00:00:00:00:00:00')|list|count|int }}" as a template sensor in my configuration. But I keep getting Template sensor 'guest_count' has no entity ids configured to track nor were we able to extract the entities to track from the value template(s). This entity will only be able to be updated manually. as an error. What can I do to fix it?

#

I just want it to say how many guests are over at an given time as a number.

arctic sorrel
mint jetty
#

If I want to count down from 20 to 2? Is this the right way to do it?

Happy birthday
dreamy sinew
#

your positioning is wrong there

#

but that's not a count-down either

mint jetty
#
   {% if states.sensor.bellas_fodelsedag.state | int == 1 %}
    Imorgon fyller Bella {{ states.sensor.bellas_fodelsedag.attributes.years_at_next_anniversary }} år! Blir det någon tårta tror ni?
   {% endif %} 

   {% if states.sensor.bellas_fodelsedag.state | int > 1 < 20 %}
    Det är bara {{ states.sensor.bellas_fodelsedag.state }} dagar tills Bella fyller {{ states.sensor.bellas_fodelsedag.attributes.years_at_next_anniversary }} år! Woop Woop!
   {% endif %}
  {%- endmacro -%}
#

I dont want it to print two times that day

#

Is that the right way to do it?

dreamy sinew
#

elseif is a thing

#

to contain everything in the same block

valid kite
dreamy sinew
#

that page is just for documentation

#

its a readability standard for displaying templates in documentation

valid kite
#

Yeah, I got that. I would like to write my templates and such on that standard 😉

dreamy sinew
#

there isn't really a style guide for templates

valid kite
#

For instance: enforcing that my code avoids white space before and after Jinja filters

#

But maybe I'll just have to force myself to write nicer code 😉

neon barn
#

should I be able to access JSON attributes from a MQTT sensor using state_attr(name, attribute)?

valid kite
neon barn
#

is it bad if I use a single MQTT sensor and just use templates for getting my data?

bitter atlas
#

@neon barn short answer: no. kind of complex question though

queen spoke
#

im having a moment... when looking at nested data, how do i reference that in a template (eg to follow)

#

faces:
total_faces: 3
matched_faces: {
"Daughter": 81.7,
"Wife": 79.7,
"Me": 71.2
}
total_matched_faces: 3
friendly_name: test_face_counter
device_class: face

#

faces: total_faces: 3 matched_faces: { "Daughter": 81.7, "Wife": 79.7, "Me": 71.2 } total_matched_faces: 3 friendly_name: test_face_counter device_class: face

#

faces is the main data element, everything else is indented

rugged laurel
#

Depends on what you want

queen spoke
#

i need to see that "Daughter" is present

#

sorry, thought i hit enter on that

rugged laurel
#

"{{ 'Daughter' in state_attr('entity.id', 'faces').get('matched_faces') }}"

queen spoke
#

Thanks! you gave me the pieces I needed!

uneven wigeon
#

Anyone know why this wouldnt work? I get an unknown error rendering template.
{{ relative_time(strptime(states('input_datetime.power_dishwasher_end'), '%Y-%m-%d %H:%M:%S')) }}

dreamy sinew
#

should start smaller and work up to see where the error starts

#

{{ states('input_datetime.power_dishwasher_end') }}

#

then start adding the layers back in

uneven wigeon
#

yeah i have. as soon as i add relative_time its when the error starts

#

the strptime function returns "2020-01-27 11:09:01"

#

so the docs say that strptime returns a datetime object. and relative_time takes a datetime object. so i just cant pick it

dreamy sinew
#

did some testing and i can't get it to work either

#

oh, it needs a timezone

#

this works

{{ relative_time(strptime(my_time, '%Y-%m-%d %H:%M:%S%z')) }}```
#

3 days

uneven wigeon
#

ahhh perfect

dreamy sinew
#

not sure if you can get your input thing to output it though

uneven wigeon
#

yeah not the most elegant solution but hey. it will do.

            {% set timezone = "0800" -%}
            {{ relative_time(strptime(states('input_datetime.power_dishwasher_end') + "+" + timezone, '%Y-%m-%d %H:%M:%S%z')) }} ago
dreamy sinew
#

you can get rid of the "+" but adding it to your timezone string

thorny snow
#
automation:
  - alias: Wills Car arrives home
    trigger:
      platform: state
      entity_id: binary_sensor.wills_car
      to: 'Connected'
    condition:
      condition: template
      value_template: >
        {{ sensor.wills_car_uptime > 1*60000 }}
#

I think my problem is my value_template

#

This automation doesnt trigger. Is value template properly formatted?

dreamy sinew
#

states('sensor.wills_car_uptime')|float > ...

thorny snow
#

ty

dreamy sinew
#

whats with the 1*x ?

thorny snow
#

it outputs in miliseconds

#

just user friendly to read

dreamy sinew
#

1*anything is useless

thorny snow
#

yeah did 1 min to test

#

gonna end it with 3 or 5 depending on usage

#

{{ states('sensor.wills_car-uptime') > 3*60000 }}

#

like that

dreamy sinew
#

string math

thorny snow
#

alot easier to understand than {{ states('sensor.wills_car-uptime') > 180000 }}

dreamy sinew
#

same shit

#

wasting a cpu cycle

thorny snow
#

yeah i know but ill forget in like 2 minutes time

dreamy sinew
#

also, you're doing string math

thorny snow
#

Not sure what you mean. Are you saying the state will always trip if its over 1 because it processes the 1 first?

dreamy sinew
#

no, what comes out of states() will be a string

#

and you're comparing it to a number

#

you dropped something from the template i gave you

thorny snow
#

oh crap

#

im sorry i see that now

#
  - alias: Wills Car arrives home
    trigger:
      platform: state
      entity_id: binary_sensor.wills_car
      to: 'Connected'
    condition:
      condition: template
      value_template: >
        {{ states('sensor.wills_car-uptime')|float > 1000 }}
#

kinda weird that never triggered

#

got it, state to needed to be on not connected

real lotus
#

I am having a logic issue that I can't seem to figure out, not sure if my template is correct . I am using the template tool on HA and the sensor condition is "snowy" the first line evaluates to "true" as I would expect with logical "or" but the second is "false". Is the syntax correct I couldn't find any examples on how to evaluate multiple conditions.


value_template: "{{ is_state('sensor.sky_condition', 'snowy' or 'fog' or 'cloudy') }}"
value_template: "{{ is_state('sensor.sky_condition', 'fog' or 'snowy' or 'cloudy') }}"```
bitter atlas
#
value_template: "{{ is_state('sensor.sky_condition', 'snowy') or is_state('sensor.sky_condition', 'fog') or is_state('sensor.sky_condition', 'cloudy') }}"
real lotus
#

I was able to get it to work in this manner I was trying to reduce the amount of code as there are 10 conditions returned by dark sky so will assume I will have to put in all the entries.

dreamy sinew
#

{{ states('sensor.sky_condition') in ['snowy', 'fog', 'cloudy'] }}

real lotus
#

Thanks all for the replies

dreamy sinew
#

@real lotus is that a tail number or initials and an area code?

real lotus
#

@dreamy sinew it goes way back, bisync Negative Acknoledgement, and the 714 well....... google: 714 + tablet. 😮

dreamy sinew
#

huh, ok

wise arrow
real lotus
#

That was from my wild youth many moons ago

gentle parcel
#

Hi Guys i am new in Hassio, and today i managed to get a Sonoff bridge working with portisch firmware and it when i give the command rfraw AA B0 4E 05 08 0168 0AE6 00D2 04F6 28BE 481828383828382838283828283828383808382828383828283828383828283838082838283828382838283828382838283838283828283838283828283828383828 55

The light goes on using tasmota console, but now , how do i het this in working in hassio, i have mqtt broker installed and find the new device, also when i go to configuration.intergration it finds the rfbridge, but how to i get the switch on and off working in the template, can someone help me so i understand the step

#

i read in the wiki i need to make the command for mqtt like this

#

cmnd/sonoffRFBridge/Backlog RfRaw AA B0 4E 05 08 0168 0AF0 00D2 04F6 28FA 481828383828382838283828283828383808382828383828283828383828283838082838283828382838283828382838283838283828283828383828283828383828 55
; RfRaw 0

silent barnBOT
mint jetty
thin laurel
#

I'm having an issue extracting the third word from a string from a sensor, it works if i do it in templates editor thingy, but when it comes to geting it over to another sensor it won't work, this is what i've got: ```

  • platform: template
    sensors:
    zm_zone_triggered:
    friendly_name: "zm_zone_triggered_mqtt"
    value_template: "{{ zm_zonetrigger_sensor_cam1.split()[2] }}" ``` and the actuall data is: sensor.zm_zonetrigger_sensor_cam1 zm_cam_framsidan:(3299) Motion zone_framsida_gatan
dreamy sinew
#

are there multiple spaces in the middle there?

#

probably worth testing in the template tester

#

split() accepts vars so you can tune what it uses to split

thin laurel
#

Problem is that sensor.zm_zone_triggered does not get a value, it works fine when i ran it in the template tester.

thorny snow
#

Could someone help met with sensor template, I am trying to setup a sensor that shows the current activity of my harmony remote so I could use the state change in node-red but everything I try gives the state off instead of the current activity.

#

This is the last one I tried:

  - platform: template
    sensors:
     harmony_activity:
       value_template: >
          {{ state_attr('remote.woonkamer', 'current_activity') }}
silent barnBOT
#

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

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

hollow bramble
#

What does current_activity currently show in states?

#

Thank you for editing your message

thorny snow
#

At the moment Radio but tried it with all my activities like Smart TV and Notebook

hollow bramble
#

What does {{ state_attr('remote.woonkamer', 'current_activity') }} show when you test it in the templates dev tool?

thorny snow
#

I will check

#
Radio'current_activity') }}
hollow bramble
#

That... doesn't seem right. Are you sure you copy/pasted correctly?

thorny snow
#

I will try again

#

No, now I get Radio

hollow bramble
#

Okay, and where are you putting the config for the template sensor? Are you sure it's under sensor: and not binary_sensor:?

thorny snow
#

I will check again, sorry and thank you for your patience.

hollow bramble
#

No problem

thorny snow
#

I think it was under binary_sensor, so I edit the configuration file and HA is now restarting.

#

Thank you, that works!!

eternal stag
#

are there jinja date math functions? ie, if i want to know months/weeks/days/etc from a date?

dreamy sinew
#

not in base jinja, but HA provides some

eternal stag
#

you mean relative_time?

#

problem is it only works on past dates, and it isn't very precise

dreamy sinew
#

if you have a datetime object you can use .day and a few other things like that

eternal stag
#

hmm.. is there a way to make reusable functions to add to jinja?

dreamy sinew
#

yes, but not in HA

#

well, not user-side

eternal stag
#

errr, what exactly do you mean by that?

#

i'm wanting to make a function in jinja to parse an entity a particular way

dreamy sinew
#

you can totally add functions to the jinja environment, but that is in the python directly

eternal stag
#

so i can just do {{ do_my_thing('sensor.something') }}

dreamy sinew
#

the way that it is implemented in HA, you can't do that

eternal stag
#

mk

dreamy sinew
#

you can make a macro but it only lives in the context of that one template

eternal stag
#

right, i've tinkered with that

#

hmm... wonder if i can do some silly include stuff to at least keep the construction somewhat dry

#

actually no i don't think that'd work

#

man that is such a bummer

jagged obsidian
#
  brightness_template: >
      {% if value_json.ZbReceived is defined and value_json.ZbReceived['0xE1F9'] is defined and value_json.ZbReceived['0xE1F9'].Dimmer is defined %}
      {{ value_json['ZbReceived']['0xE1F9'].Dimmer | int }}
      {%- else -%}
      {{ state_attr('light.fire_light', 'brightness') }}
      {%- endif -%}

This should ignore every other message on the topic that does not contain ZbReceived, 0xE1F9 and Dimmer in the json payload, right?

limber turtle
#

I need an extra pair of eyes here:

          friendly_name: 'PPPOE WAN RX Total'          
          unit_of_measurement: "Gb"
          value_template: '{{ ((states.sensor.pppoe_wan_rx_raw | float ) / 1000000000 ) | round(3) }}' ```
Trying to convert my total SNMP reported traffic in Gb format.
``` sensor.pppoe_wan_rx_raw    4793737622    friendly_name: PPPOE WAN RX Raw
hidden: true
 sensor.pppoe_wan_rx_total    0.0    unit_of_measurement: Gb
friendly_name: PPPOE WAN RX Total

By my poor math that should retrieve 4.793

queen meteor
#

@limber turtle it should be states.sensor.pppoe_wan_rx_raw.state and not states.sensor.pppoe_wan_rx_raw. Or best way to access state value is {{ states('sensor.pppoe_wan_rx_raw') | float }}

limber turtle
#

Bless you! ❤️ seems that the coffee in my system is running out. I had a working example just a few lines above that. FeelsBadMan

shadow rover
#

Hello everyone. I’m just getting started with templates and need help. I got all the sensors from my iPhone device tracker from HA app. I would like to translate some values and units to polish. Could you help me with this?

mighty ledge
#

$4

#

jk, what attributes

arctic sorrel
#

Surely it would have been 4zł 😉

mighty ledge
#

its 4$ until I help with the convert 😉

shadow rover
#

For example I have “sensor.steps” where the unit is “steps”and i would like to have “kroków”

mighty ledge
#

just customize it and change the unit of measurement

#

no need for templates

#

Configuration->Customizations. Select Steps(sensor). Pick an attribute to override, choose Other. Enter unit_of_measurement as the attribute name and "krokow" as the value.

shadow rover
#

The thing is that in polish if the value is less or equal to 4 it should be “kroki” but when it’s greater than 4 it should by “kroków”

mighty ledge
#

You don't want to do that with unit of measurement

#

it will separate your database tracking.

#

If you want that just in the UI, use a custom card and change the values there

shadow rover
#

Ok so one problem fixed, thanks! The other one is with values. I have sensor.activity and there is few possible values like stationary, walking, etc. I would like to translate each to polish. How can I achieve that?

arctic sorrel
#

Ideally you'd want to submit a translation for the UI

mighty ledge
#

I should have known about that mindblown

#

I guess it makes sense that I don't because it's all in english

shadow rover
#

@arctic sorrel I can translate it for the ui but the description how to do this is very poor

arctic sorrel
#

Unfortunately I can't help there

rugged laurel
#

Those needs to be added in the backend

shadow rover
#

Could you help me with the value translation for now?

#

sensor.activity and there is few possible values like stationary, walking, etc. I would like to translate each to polish

keen crater
#

hi all, question; I've built an P1 Energy Meter port serial reader which publish a payload to MQTT via Tasmota. All serial messages are publised on this MQTT topic but I only need a small portion of one of those messages. I already asked some help on the ha forum and petro🙌 gave me some help, but I can't get it to work. I got the regex figured out (I think) but the sensor just keeps saying unknown.
This is the payload and regex: https://regex101.com/r/o2hOtp/1/
And this is the sensor: https://paste.ubuntu.com/p/HcRCKssR8v/
Don't understand what I'm doing wrong here and how to debug

queen meteor
#

@keen crater not sure what you are trying to do there - you are doing a regex on messages with specific pattern that contains "1-0:1.7.0" in the value... you could simply check {{ '1-0:1.7.0' in value_json }} and if it, just extract the value with no need for regex

#

that template code you have won't go through all the messages and look for the one you are looking for - mqtt overrides messages with new ones in the topic, so you only have one message at any given point of time

#
{% set value_json = {"SerialReceived":"1-0:1.7.0(00.428*kW)"} %}
{{ value_json.SerialReceived if '1-0:1.7.0' in value_json.SerialReceived else 0 }}
keen crater
#

well i only need the 00.428 from the 1-0:1.7.0(00.428*kW)

queen meteor
#

ah!

keen crater
#

thats why i think i need regex

#

🙂

queen meteor
#

{{ value_json.SerialReceived.split('(')[1][:-1] }}

#

that should do it.

#

try this out ```
{% set value_json = {"SerialReceived":"1-0:1.7.0(00.428*kW)"} %}
{{ value_json.SerialReceived.split('(')[1][:-4] if '1-0:1.7.0' in value_json.SerialReceived else 0 }}

#

that even removes units from the value

keen crater
#

thanks! one moment 🙂

#

the sensor now shows a value of: 00.428 kW 🙂 but the graph still says unknown

queen meteor
#

graph is the history - it will take time before it has enough information to show up properly. make sure you have unit_of_measurement setting to the sensor

keen crater
#

okay 🙂 thanks

#

so i only have to change it to start listening to the mqtt messages

#

probably only removing the first line if im not mistaken

queen meteor
#

yup

keen crater
#

back to unknown 😦

#

i do see messages published

#

every minutes the P1 reader sends out all the messages again

queen meteor
#

ok - the sensor gets updated every time each message is published to the mqtt. if the value contains '1-0:1.7.0', it will extract the corresponding value. otherwise you should see 0.

keen crater
#

yeah, thats what i also thought reading your suggested code

#

im gonna simulate it manually by publishing manually

#

maybe the tasmota's message is faulty

#

and not a valid json

#

yep its the tasmota

#

is there a way of ignoring the message instead of using a 0?

#

if it is not a match?

#

oh just leave the else out probably

#

hmm that doesnt work 😦

#

tasmota adds a breakline to the json
{"SerialReceived":"!5F02
"}

#

thats why it doesnt work

rugged laurel
#

"{{value_json['SerialReceived'].replace('\n', ''}}"

warm isle
#

scroll up first to get a picture of all 😛

next grotto
#

Hi, I'm trying to set up a template sensor. I tested the template in the template development environment and it returns the desired values. However the template sensor remains empty. Any ideas for troubleshooting?
For better readability, my few lines of code are posted here: https://gist.github.com/mp68/611e65eea1c28d6e73a3dfb4a5d6e50f
Short code explainer: What I'm trying to do is to display a card with the chores from Grocy that are due now. If there are no chores, the sensor value should be False. If there are due chores, it should return the chores like "chore name 1, chore name 2, chore name 3". To achieve this, I loop through all the chores set in Grocy. Then I select only the due ones. Then I select the tasks which have been completed by a certain user in the past. The remaining chores are then added to a namespace variable (namespace because loops in Jinja2 keep their assigned variables isolated) and the template returns the content created in the loop if there were any chores selected.

Do you have any ideas how to get this sensor working? It returns valid values in the template development environment.

#

Hi, I'm trying to set up a template sensor. I tested the template in the template development environment and it returns the desired values. However the template sensor remains empty. Any ideas for troubleshooting?
For better readability, my few lines of code are posted here: https://gist.github.com/mp68/611e65eea1c28d6e73a3dfb4a5d6e50f
Short code explainer: What I'm trying to do is to display a card with the chores from Grocy that are due now. If there are no chores, the sensor value should be False. If there are due chores, it should return the chores like "chore name 1, chore name 2, chore name 3". To achieve this, I loop through all the chores set in Grocy. Then I select only the due ones. Then I select the tasks which have been completed by a certain user in the past. The remaining chores are then added to a namespace variable (namespace because loops in Jinja2 keep their assigned variables isolated) and the template returns the content created in the loop if there were any chores selected.

Do you have any ideas how to get this sensor working? It returns valid values in the template development environment.
@next grotto Ok, I already found a solution. I had to assign an entity_id to update the sensor. Otherwise it stays empty.

low blaze
#

Hoping someone can help me. I'm attempting to use a template to turn seconds into minutes:seconds but I'm getting stuck on probably the most basic part, literally using examples of other people's code. I guess the examples are just different enough that when I try to modify them to fit, it just breaks. I don't think I'm having any problem finding the minutes/seconds calculation part, I found plenty of examples, but I have no idea how to put it into my configuration to change my counter (of seconds)

#

here's my code:

silent barnBOT
low blaze
#

it's coming up as unavailable

#

counter.guest_timer is correctly counting seconds from 0 and up

#

Could not render template Time: UndefinedError: 'counter' is undefined
12:21 AM components/template/sensor.py (ERROR)
Template sensor 'guest_friendly' has no entity ids configured to track nor were we able to extract the entities to track from the value template(s). This entity will only be able to be updated manually.
12:21 AM components/template/init.py (WARNING)

low blaze
#

-- Made progress. figured out a few mistakes. understanding states and .state on both ends of the counter.guest_timer fixed those errors

eternal stag
tacit glen
#

{{ states('media_player.kd_65xf9005') != 'playing' }} <-- is this the correct template for when something is NOT playing?

#

I tried it and it's not working. the state of the media player is playing, but the automation was still triggered

queen meteor
#

@tacit glen what do you see when you try the code in template editor?

tacit glen
#

hang on

queen meteor
#

devtools -> Templates

tacit glen
#

value_template: '{{ states(''media_player.kd_65xf9005'') != ''playing'' }}'

queen meteor
#

let's try this again, what do you see when you try the code in template editor?

tacit glen
#

hang on 😄

#

I never used that tab

#

Error rendering template: TemplateSyntaxError: expected token ',', got 'media_player'

#

ah wait, I copied over the one from the automations.yaml

queen meteor
#

ok - there are single quotes, and there are double quotes. thy are different. You can't put two single quotes as one double quote

tacit glen
#

if I copy the one I enter into the automations page I get true

queen meteor
#

use proper double quote - like " instead of ''

tacit glen
#

the two single quotes come automatically

#

I'm using single quotes

queen meteor
#

ok - try this ```
value_template: "{{ states('media_player.kd_65xf9005') != 'playing' }}"

weary jasper
#

no i dont want too!

tacit glen
#

nope the automation is still being triggered

queen meteor
#

ok - you need to tell me what you see when you paste ☝️ code in the template editor

tacit glen
#

"True"

queen meteor
#

try pasting this code and see ```
{{ states('media_player.kd_65xf9005') }}

tacit glen
#

off

queen meteor
#

ok - you got it. the state is off, that is not playing. you are all set then!

tacit glen
#

but it is playing

#

and the actual state (from the states tab) is playing

queen meteor
#

well, then you got the entity id wrong, or looking at wrong thing.

tacit glen
#

hm

#

I'll copy it again, hang on

#

wtf it was wrong

#

how can that be, I copied it right off the states page

queen meteor
#

have more ☕

weary jasper
#

its always @rugged laurel fault

tacit glen
#

hate coffee 😛

#

thanks though

queen meteor
#

there's your problem!

dawn sable
#

trying to setup a template to get game score not sure how to do varaibles and get the value in an automation does this look right

#
sensor 2:
# Get SF score
- platform: rest
  resource: https://feeds.nfl.com/feeds-rs/scores.json
  name: "Get Score"
  value_template: >
    {% for game in value_json.gameScores %}
       {% if game.gameSchedule.homeTeamAbbr == 'SF' %}
          {Score} = game.score.homeTeam.pointTotal
       {% endif %}
       {% if game.gameSchedule.visitorTeamAbbr == 'SF' %}
          {Score} = game.score.visitorTeam.pointTotal
       {% endif %}
    {% endfor %}
silent barnBOT
#

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

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

paper hazel
#

Hi all - I'm trying to get my head around why this template is not working. Any help will be appreciated. I posted it under automations, before I saw there is a templating sub forum - Sorry for the cross post. - condtion: template value_template: >- {%- if trigger.entity_id == 'input_select.risco_partition_huis' -%} {{is_state('sensor.risco_alarm_huis_status', 'armed_home')}} {%- elif trigger.entity_id == 'input_select.risco_partition_onder_huis' -%} {{is_state('sensor.risco_alarm_onder_huis_status', 'armed_home')}} {%- elif trigger.entity_id == 'input_select.risco_partition_buite' -%} {{is_state('sensor.risco_alarm_buite_status', 'armed_home')}} {%- elif trigger.entity_id == 'input_select.risco_partition_garage' -%} {{is_state('sensor.risco_alarm_garage', 'armed_home')}} {%- endif -%}

charred dagger
#

Things can "not work" in infinitely many ways. Which one is yours?

paper hazel
#

@charred dagger fair enough - Config check was failing. I found the issue, apparently my spelling on a Sunday evening sucks! 'condtion' does not equal 'condition'

charred dagger
#

Sometimes it's the simple things.

paper hazel
#

Agreed - and they are the ones easiest glanced other! Appreciated...

bold vale
#

I have a garbage card showing the remaining days till collection, using custom:card-templater to show the garbage sensor attribute:

name_template: '{{ states.sensor.papier_2.attributes.days }} dagen'

but with this the text always says 'dagen' (days) even when there is 1 dag (day) left. The sensor has 3 states, 0 (today) , 1 (tomorrow) & 2 (later)
How can i change the text to say: dag when its only 1 day left? I was thinking something like this:

name_template: '{% if is_state('sensor.papier_2', '1') %} dag {% else %} dagen {% endif %}'

but obviously that doesnt work.. am i in the right direction though?

queen meteor
#

@bold vale ```
name_template: "{{ 'dagen' if states.sensor.papier_2.attributes.days |int > 1 else 'dag' }}"

bold vale
#

it doesnt show the number of days using that.

#

it does show ' dag' though

#

Fixed it, thanks @queen meteor

dreamy sinew
thin laurel
#

ah true

noble pawn
#

can someone double check this and please tell me whats wrong? i dont get it..

#
  • platform: template
    sensors:

    Wohnzimmer

    temperature_arbeitszimmer:
    value_template: "{{ state_attr('climate.thermostat_19', 'current_temperature') }}"
#

error: "end of the stream or a document separator is expected at line 24, column 1:
- platform: template
^"

dreamy sinew
#

share the full thing

silent barnBOT
noble pawn
#

like this?

dreamy sinew
#

seems fine

noble pawn
#

yeah, it gets accepted now

#

but i dont get it how to access the sensor / graph

buoyant pine
#

add it to a history graph card?

noble pawn
#

i think i need to add a new "card" to my dashboard, right?

#

yeah

#

there should be a new entity right?

#

which represents my code snippet

buoyant pine
#

yep, should be sensor.weather_temperature unless that entity ID already exists, then it'll be something like sensor.weather_temperature_2

noble pawn
#

its there now, but i dont get correct data.. its always like 5 degrees celsius 😄

noble pawn
#

:/

bitter atlas
#

flat line! clear!

noble pawn
#

yeah not good

#

the values are there but the graph doenst get it ^^

#

any ideas?

bold vale
#
name_template: >-
  {{ states.sensor.papier_2.attributes.days }} {{ 'dag' if
  states.sensor.papier_2.attributes.days |int == 1 else 'dagen' }}

I now have this for my garbage cards now, thanks to @queen meteor
The sensor has 3 states: 2 = later, 1 = tomorrow, 0 = today, so the above code shows the collection day '0 dagen'. which is works, but i rather have it say ' vandaag' (today)

#

-is

#

can i somehow remove the first part of the template {{ states.sensor.papier_2.attributes.days }} when the attribute state is 0 (today) ?

#

otherwise it would still show that 0 on the name of the card.

#

im probably overthinking this.. :/

bitter atlas
#

seems like it would be easier to just turn that into a template sensor and have it spit out what you want it to say exactly as the state @bold vale

bold vale
#

ok ill try that, tnx 🙂

shrewd sedge
#

hey guys having trouble understanding templates, I want to make a climate entity (thermostat) which parses this MQTT payload from other device MQT: sonoff/tele/RESULT = {"IrReceived":{"Protocol":"COOLIX","Bits":24,"Data":"0xB29FC0","DataLSB":"0x4DF903","Repeat":0,"IRHVAC":{"Vendor":"COOLIX","Model":-1,"Power":"On","Mode":"Cool","Celsius":"On","Temp":25,"FanSpeed":"Min","SwingV":"Off","SwingH":"Off","Quiet":"Off","Turbo":"Off","Econo":"Off","Light":"Off","Filter":"Off","Clean":"Off","Beep":"Off","Sleep":-1}

#

cleaner [23:50:55] sonoff/tele/RESULT {"IrReceived":{"Protocol":"COOLIX","Bits":24,"Data":"0xB29FC0","DataLSB":"0x4DF903","Repeat":0,"IRHVAC":{"Vendor":"COOLIX","Model":-1,"Power":"On","Mode":"Cool","Celsius":"On","Temp":25,"FanSpeed":"Min","SwingV":"Off","SwingH":"Off","Quiet":"Off","Turbo":"Off","Econo":"Off","Light":"Off","Filter":"Off","Clean":"Off","Beep":"Off","Sleep":-1}}}

dreamy sinew
#

@bold vale {% set days = "2" %} {% set suffix = ' dag' if days|int == 1 else ' dagen' %} {{ days + suffix if days|int != 0 else 'vandaag'}}

#

tested in the template tester

#

so remove the days check and replace it with state_attr('sensor.papier_2', 'days')

#
value_template: >-
  {%- set suffix = ' dag' if state_attr('sensor.papier_2', 'days')|int == 1 else ' dagen' -%}
  {{ state_attr('sensor.papier_2', 'days') + suffix if state_attr('sensor.papier_2', 'days')|int != 0 else 'vandaag'}}
#

eh, that's ugly 😄

#
value_template: >-
  {%- set days = state_attr('sensor.papier_2', 'days') -%}
  {%- set suffix = ' dag' if days|int == 1 else ' dagen' -%}
  {{ days + suffix if days|int != 0 else 'vandaag'}}```
bold vale
#

@bitter atlas This works too :)

name_template: >-
  {%- if is_state("sensor.papier_2", "0")%} Vandaag {% elif
  is_state("sensor.papier_2", "1")%} Morgen {% else %} {{
  states.sensor.papier_2.attributes.days }} dagen {%- endif %}
dreamy sinew
#

mine gets you dag, dagen, and vandaag though 😛

bitter atlas
#

both can be on on either side lol, many ways to skin a cat isn't that right phnx?

dreamy sinew
#

and won't crash if that entity isn't there

#

yup

#

if/elif is probably faster

#

dunno though

shrewd sedge
#

cleaner [23:50:55] sonoff/tele/RESULT {"IrReceived":{"Protocol":"COOLIX","Bits":24,"Data":"0xB29FC0","DataLSB":"0x4DF903","Repeat":0,"IRHVAC":{"Vendor":"COOLIX","Model":-1,"Power":"On","Mode":"Cool","Celsius":"On","Temp":25,"FanSpeed":"Min","SwingV":"Off","SwingH":"Off","Quiet":"Off","Turbo":"Off","Econo":"Off","Light":"Off","Filter":"Off","Clean":"Off","Beep":"Off","Sleep":-1}}}
@shrewd sedge do I have to parse every setting manually or there's something built in for this already ?

eternal stag
#

I'm trying to build a template that will let me select entities by partial match of the name... so far I have:

{% set majority_on = states.input_boolean | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list | count > 0 %}

Before the on eval, i want to limit to a naming convention

dreamy sinew
#

i haven't delved enough into the state object

eternal stag
#

trying to go the route of building an array, but not having any luck

queen meteor
#

@eternal stag what are you trying to do?

eternal stag
#

Filter a list generated similarly as above, by only grabbing entity_ids that match a pattern of some sort... I have something going, but it's not near as elegant as I'd want

#

Trying to program in a config basically 😭

queen meteor
#

ok... not all the filters you see in the Jinja documentation is available in HA - it may not be one liner, if you already have something working, you can always refine it

eternal stag
#
{%- macro findByName(_states, _startsWith) -%}
{%- set entities_on = _states | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list -%}
{%- for _ent in entities_on -%}
  {%- if _ent.startswith(_startsWith) -%}
    {{_ent}},
  {%- endif -%}
{%- endfor -%}
{%- endmacro -%}

{{ findByName(states.input_boolean, 'input_boolean.presence_') }}
#

i wanted a proper array, but i guess that's asking too much

queen meteor
#

everything is a list in jinja - there is not much distinction between array and list

queen meteor
#

@eternal stag you could simplify that a bit further

#
{%- macro findByName(_states, _startsWith) -%}
{%- set entities_on = _states | selectattr('state', 'eq', 'on') |list  -%}
{{ entities_on | selectattr('entity_id', 'eq', _startsWith) | map(attribute='entity_id') |list}}
{%- endmacro -%}

{{ findByName(states.input_boolean, 'input_boolean.dummy') }}
#

that finds exact match, but not something like starts with... 😦

dreamy sinew
#

sucks that we can't dynamically build a list, otherwise we could pull them out with a loop

eternal stag
#

yeah i don't actually want startswith, i want partial match

#

so sounds like i can't do what i want?

chrome temple
#

Sure you can. You just need to use namespaces.

eternal stag
#

mm i thought that was just a dictionary?

chrome temple
eternal stag
#

hmm, i think you're misunderstanding the situation

#

i'm trying to do a string partial match

#

not a semaphore in a loop

chrome temple
#

I thought I read that you're trying to build a list with Jinja. You're trying to filter a list of entity IDs that match some sort of selection criteria.

eternal stag
#

yeah, and i have it working, but it will only work on a startswith match, not a mid-string match

#

ie: some_sensor_name_OBSCURE_NAMESPACE_NAME_total, i'd want to find all entities with OBSCURE_NAMESPACE_NAME in the entity_id

#

well hell, actually... hang on... that's a python method

#
{%- if _contains in _ent -%}
    {{_ent}},
{%- endif -%}

lol duh

#

ok so now the question is, how do i build a proper list? I found very little info on it, but ended up doing just a string output with commas after everything (although not sure if that'll break at run-time)

chrome temple
#

Yes, your macro/script was building a string, not a list. I thought that was what you were asking about, and why I suggested using a namespace.

eternal stag
#

i swear i saw someone do myvar.append() but i get a SecurityError, i guess because we're in a sandboxed jinja instance

chrome temple
#

You can do myvary = myvar + [new_item].

bitter atlas
#

what kind of complex mumbo jumbo you up to now? lol

chrome temple
#

Start with:

{% set ns = namespace(myvar = []) %}

Then in the loop:

{% set ns.myvar = ns.myvar + [new_item] %}
eternal stag
#

but {% set ns = [] %} won't work?

#

oh, that's the sandbox, i take it?

#

let me try

chrome temple
#

No, you have to use the namespace. How many times do I have to say that?! 😜

eternal stag
#

@bitter atlas my architect mind wants to make things reusable, even if they're truly not... I refuse to explicitly list out entities where i know they'll be growing

bitter atlas
#

it's the only exception to the scope

eternal stag
#

well saying and explaining are two different things

bitter atlas
#

follow what he's telling you, it's the only exception that will work

eternal stag
#

oh so the for block is it's own scope in this context?

dreamy sinew
#

yep

bitter atlas
#

what you gonna do in say a year something breaks you forgot everything you done, your gonna look at this stuff and be like.. wtf lol

eternal stag
#

no i can read it just fine

#

it's knowing the best practice that's the confusing part

bitter atlas
#

i think in this case best practice is staying somewhat simplistic for futureproofing hehe

eternal stag
#

i'm fine

dreamy sinew
#

best practice would be to not do it in jinja 😛

bitter atlas
#

lol

eternal stag
#

lol i literally thought "god damnit, phnx is going to love hearing me say i'm going to try appdaemon"

dreamy sinew
#

heh

eternal stag
#

but yes, templating isn't really meant to do this crap... not realistically, anyway

bitter atlas
#

if you had stuck with node red you'd be done already lol

eternal stag
#

bleh node-red is too redundant for me

bitter atlas
#

lol

dreamy sinew
#

jinja is really powerful but some of the environment settings picked in HA limit what you can do

eternal stag
#

i don't blame jinja or HA, it's the nature of the beast... templating engines are not logic engines

dreamy sinew
#

list.append('thing') is locked out 😦

eternal stag
#

forcing them to be makes things ugly, very quick... i was just hoping to do some quick filtering

#

lemme try the ns version

chrome temple
#
{% set ns = namespace(entities=[]) %}
{% for e in states.input_boolean|selectattr('state','eq','on')|map(attribute='entity_id')
   if e.split('.',1)[1].startswith('a') %}
  {% set ns.entities = ns.entities + [e] %}
{% endfor %}
{{ ns.entities }}
#

Of course change the if e... part to whatever you want. That was just for my test.

eternal stag
#

hmm, guess i gotta give up the "function" concept with the macro....

#

but yeeah i had it working with the namespace

chrome temple
#

Which would probably use regex_search...

dreamy sinew
#

eh, you can do it. still run in to namespace issues though

chrome temple
#
   if e|regex_search('OBSCURE_NAMESPACE_NAME')
eternal stag
#
{%- set ns = namespace(
              _states = states.input_boolean, 
              _contains = '.presence_',
              entities = []
) -%}

{%- set entities_on = ns._states | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list -%}
{%- for _ent in entities_on -%}
  {%- if ns._contains in _ent -%}
    {% set ns.entities = ns.entities + [_ent] %}
  {%- endif -%}
{%- endfor -%}

{{ ns.entities }}
chrome temple
#

So:

{% set ns = namespace(entities=[]) %}
{% for e in states.input_boolean|selectattr('state','eq','on')|map(attribute='entity_id')
   if e|regex_search('OBSCURE_NAMESPACE_NAME') %}
  {% set ns.entities = ns.entities + [e] %}
{% endfor %}
{{ ns.entities }}
#

You don't need to put the inputs into the namespace. Only the "output" variable whose scope you want to be beyond the loop.

eternal stag
#

yeah, i just wanted it so i can edit all the vars in one spot

chrome temple
#

And you don't need all those dashes!

eternal stag
#

that way if i fix something up later, i can just replace wholesale from everything

#

doesn't that strip the newline?

#

i've just made it a practice to do it on everything

chrome temple
#

Do you need to strip the newlines?

dreamy sinew
#

good practice

chrome temple
#

LOL

eternal stag
#

i'd rather have the data as clean as it can be, that's just how i work 😛

#

it's not a big deal really, doesn't alter the functionality

dreamy sinew
#

things can go wonky in the yaml if you don't strip the crap out

chrome temple
#

Oh, I see, all those dashes cluttering everything up so it becomes difficult to read is a good thing???

eternal stag
#

yeah i had some issues with another automation that the fix was to actually do ALL the dashes

#

potato potato

chrome temple
#

That's probably because you were building a string that wasn't stripped. Whatever. If it makes you happy, then it's a good thing. 😄

#

Anyway, I hope you found the namespace and regex_search suggestions useful.

eternal stag
#

yep

#

thank you!

bitter atlas
#

next update everything breaks and it's back to square one lol

dreamy sinew
#

templates have been pretty stable

chrome temple
#

BTW, using in is probably better than regex_search if you're not using a more complex pattern. That was a good idea.

eternal stag
#

i toyed with it, and i think i prefer regex as the goto

chrome temple
#

It's certainly more generic.

eternal stag
#

even though i can't be fully DRY with this setup, i plan on treating it as such... whole blocks replaced blindly if i update it in one place, so that way it's consistent

dreamy sinew
#

its one of those things that doesn't really matter until it does

thin laurel
#

I'm failing to grasp how i can re-write this to dynamicly handle values being fed to it from 1-9 or whatever i need to via templates. - platform: mqtt name: "test Motion sensor" state_topic: "zoneminder/1" value_template: "{{ value_json.monitor }}" payload_on: "1" off_delay: 7 device_class: motion This works fine for monitor "1" but i have a bunch and it would be great not having to create like 10 of them manually. Also i learn a bit by doing it dynamicly 🙂

silent barnBOT
dreamy sinew
#

.rule6 @shrewd sedge

silent barnBOT
#

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

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

shrewd sedge
#

sigh so nobody is willing to help or suggest anything so what this discord is for ?

dreamy sinew
#

a comment like that will reduce willingness

shrewd sedge
#

was a honest question

buoyant pine
#

This is free support, no one here owes you anything

shrewd sedge
#

templates aren't that common in the industry thats im having a hard time grasping it

dreamy sinew
#

jinja is very common in the industry

#

especially if you come from ansible

shrewd sedge
#

new to automation

queen meteor
#

@shrewd sedge people volunteer their time here - don't expect answers the moment you post a question

shrewd sedge
#

I like approach of putting good tools to use but Im kinda used just to programming seems more straight forward to me

#

posted yesterday nobody seemed to respond however I was pointed to the spam rule fairly quickly lol ,I still appreciate the help

dreamy sinew
#

following the rules also helps with getting responses 😉

queen meteor
#

ok - I saw the message, but not very clear on the ask. there is no such thing called json inside json. It is all json. other than that, I am not sure what you are asking

shrewd sedge
#

yeah I suck at everything web based pretty much

queen meteor
#

are you seeing errors? or need help accessing a specific value from the json... what seem to be the problem?

#

it's ok, we all have to start somewhere, and there is always some learning curve. Just be clear on the question/problem, someone can help

#

are you familiar with Template Editor? If not, I highly encourage spending some time and play around.

#

devtools ->Templates

shrewd sedge
#

can I subscribe to topics from there so I can test some templates ?

queen meteor
#

you can hardcode the json value there

#

there is an mqtt tab, if you want to see actual messages

shrewd sedge
#

Yeah I have already the payloads, kinda got hang most of the basic stuff in HA except templates

#

👍

queen meteor
shrewd sedge
#

Pretty neat stuff,Thanks so much.

#

just to clarify, what for the json_attributes_template is made ?

#

used for

queen meteor
#

that I am not sure, as I don't use it

shrewd sedge
#

like if I can access directly the values via other templates

#

Reading the example from mqtt sensor page doesn't help

shrewd sedge
#

Leaving it here if somebody needs it:

#
  - platform: mqtt
    name: "BedrromAC"
    min_temp: 17
    max_temp: 30
    current_temperature_topic: "sonoff/tele/RESULT"
    mode_state_topic: "sonoff/tele/RESULT"
    fan_mode_state_topic: "sonoff/tele/RESULT"
    swing_mode_state_topic: "sonoff/tele/RESULT"
    
    current_temperature_template: "{{ value_json.IrReceived.IRHVAC.Temp }}"
    mode_state_template: "{{ value_json.IrReceived.IRHVAC.Mode | lower() }}"
    fan_mode_state_template: "{{ value_json.IrReceived.IRHVAC.FanSpeed | lower() | replace('min', 'low') | replace('max', 'high') }}"
    swing_mode_state_template: "{{ value_json.IrReceived.IRHVAC.SwingV | lower() | replace('auto', 'on') }}"```
long basalt
#

Simple AND syntax for a value_template? {{ this && that }}

#

Wanting to do something like this for a template_switch value template -- Eval to true (on) if both attributes match {{ is_state_attr('climate.hvac', 'hvac_action', 'heating') && is_state_attr('climate.hvac', 'temperature', '80') }}

rugged laurel
#

{{ True and True }}

long basalt
#

Thank you!

rugged laurel
#

but

#
{%set t=state_attr('climate.hvac', 'hvac_action')%}{{t in ['heating','80']}}

That's how I would have done it

long basalt
#

fits me...to a T

rugged laurel
#

or...

#
{{state_attr('climate.hvac', 'hvac_action') in ['heating','80']}}

Actually

long basalt
#

Huh, that one is actually evaluating to true right now when it should be false