#templates-archived

1 messages · Page 21 of 1

fading patio
#

ok, can the {{ evaluate the subtraction and then also output? or do I need to do something with {% %} first and then output it using {{ }}?

silent seal
#

Yes, it can do both

inner mesa
#

You can do both

dim aurora
#

Hello, I am quite new here, but trying to get something to work for quite a while now. I can only find unanswered posts on the internet, so hoped someone could help me out a bit in here. I am trying to get the background of my card in the color of my hue light by styling it. I have created a custom template sensor that is getting the rgb color as example it outputs : (255, 211, 130). How do I print this in the styling code? I can't seem to find out what the correct syntax is.

#

style: |
ha-card {
{% if states('light.lm_corner') == 'on' %}
background-color: rgb({% states('sensor.lm_light_color') %});
{%- endif %}
}

silent seal
#

You can't use Jinja code in most cards.

dim aurora
#

Ah alright, are there any other routes I can check to archieve on a different method?

silent seal
#

Well the question is always what your overall aim is. You could use auto entities and the layout card for example, but that might not be a good solution for you

dim aurora
#

well the idea is to show my light scenes dynamicly on the cards. So I have as background set : background-image: linear-gradient(to right, blue, red, yellow);. Instead of the preprogrammed colors I would like to have the actual light colors inthere as they get changed often. I couldnt find any otherway to get a gradient then with mod_card, but from there I am unable to get the sensors with the colors.

plain magnetBOT
#

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

inner mesa
#

this channel is for Jinja templates

hidden crag
#

oh sorry

inner mesa
plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

naive remnant
#

so my car has a door sensor that has open and closed, but about 2 mins after closing the sensor state is Unavailable, this is the only issue on all doors, when sensor is open it stays showing as open looking for right direction for value template to make it possible to show closed if Unavailable.

marble jackal
#

You can create a template sensor for that

naive remnant
#

yep it went over my head, I can do the timed ones using strptime, but stuck on this

marble jackal
#

I don't see a need for strptime here

#

are they binary_sensors (so real state on or off) or do they really have the state open or closed

naive remnant
#

I understand how to creat those ones I am saying but I dont know for open and close how to create ones for open closed and yes they show open and closed

#

I am fine with the timed ones, just first time I have had to do this for a open and closed one, (sorry for miss jumbled englished I, am on pc now apple predictive text is a pain.

marble jackal
#

{{ 'open' if is_state('sensor.your_door_sensor', 'open') else 'closed' }} will give you open or closed

#

open when the source sensor is open, otherwise closed

naive remnant
#

lol oh well I was 100% over thinking it then lol

#

I had binary_sensor.megane_hatch:
value_template: >
{% if binary_sensor.megane_hatch %}
{{ (binary_sensor.megane_hatch, 'open')}}
{% else %}
closed
{% endif %}
availability_template: >
{{ states('binary_sensor.megane_hatch') not in ['unknown', 'unavailable'] }}

marble jackal
#

that's about the same, but mine uses a single line variant

#

but if your source sensor is a binary_sensor it will be on or off

#

check developer tools > states for the real state

#

the GUI translates it for you based on the device_class

naive remnant
#

ill have a check when I go out in car in the morning before trying again and check why I am live opening and closing the door 🙂

marble jackal
#

but, if it will change to unavailable after 2 minutes, your availability_template will do the same to your template sensor

#

in this case you should remove it

thorny snow
#

If I have a template sensor that uses the jinja2 (% set variable = foo %} stanza on a line, can I then add an attribute to that template sensor that refers to that field?

#

or do I have to fully redefine each attribute to contain all datasources needed to calculate the attribute a second time

marble jackal
#

nope, you need to redefine it.
You can put it in an atttriubute itself and refer to the attribute

thorny snow
#

hmm that is fairly annoying then. I use this in a way where I set a bunch of variables all at once and do caluclations based on a variety of sources. I'd have to redefine each attribute with 6 lines, some of which are duplicated per attribute

#

actually, given the staged calculations most are duplicate

mighty ledge
marble jackal
#

ah right, that's another option

#

but if you have a variety of sources you need to make sure you add them all to the trigger. You can use a state trigger without to: and from: to also let it trigger on attribute changes

thorny snow
#

well provided I can just add all my current variables as triggers it should work the same

#

so I could move {% set gaming_temp = state_attr('climate.gaming_thermostat_thermostat', 'current_temperature') %} to a template trigger which I then add to the template sensor? Sounds a bit templateception but if it works I'll take it

mighty ledge
#

no, you have to use trigger variables

#
trigger:
- platform: ...
  variables:
    gaming_temp: "{{ state_attr('climate.gaming_thermostat_thermostat', 'current_temperature') }}"
thorny snow
#

hmm I'm not seeing how I would integrate this though. I have a separate input_templates/sensor.yaml which only has one sensor key, and a list of sensors underneath. It looks like this trigger attribute will then count for all of them

#

ex:

- sensor:
  - name: "net_power_flow"
    unit_of_measurement: "kW"
    state: >

(...)

  - name: "Boiler CS WDC"
    icon: mdi:heating-coil
    state: >-
#

I only want the triggers on the latter one

mighty ledge
#

yes it would

thorny snow
#

not on the first

mighty ledge
#

don't put them all with the same trigger

thorny snow
#

or any of the others I omitted

mighty ledge
#

this is valid

template:
- trigger:
  ....
  sensor:
  - name: ...
    state: ...
  - name: ...
    state: ...
- trigger:
  ....
  sensor:
  - name: ...
    state: ...
  - name: ...
    state: ...
#

you can also leverage this.state to just use the last state if nothing updated

marble jackal
#
- trigger:
    - platform: state
  sensor:
    - name: bla
- sensor:
    - name: foo
mighty ledge
#

that's also valid

marble jackal
#

the trigger in this case will only affect sensor bla

thorny snow
#

okay, so given template: !include_dir_merge_list input_templates I'd have to move this particular sensor into a new file so the trigger won't affect the other sensors that don't need it then

mighty ledge
#

right

thorny snow
#

actually that won't help, it's all a big list anyway

mighty ledge
#

you can also do this via an automation that creates an event

marble jackal
#

it doesn't even has to be a different file, but with that include it would make sense to have in a separate one

mighty ledge
#

and then have a series of event based template entities

#

there's a bunch of different ways to avoid reusing code, but sometimes it's not worth it

thorny snow
#

I mean, yes, that's also an option. but then I'd be using automation -> template -> automation which feels a bit redundant

mighty ledge
#

think of it as calculation -> update entity

#

you can even make it a package

narrow field
#

Hi all, I'd like a binary_sensor which is set to "off" when another sensor is off OR a specific calendar event is in progress. I'm sure I read about doing this with a template the other day, but I can't find the thing I was reading, can anyone help please?

thorny snow
#

I.e. I only have one sensor key in the yaml now, but I could add another one of course

#

which could then have the triggers in it

#

then a third sensor key could reset it?

mighty ledge
thorny snow
#

it's a list so adding a second key shouldn't be a problem

thorny snow
#

ah I now see that that is what @marble jackal is referring to

#

so yes, that would work then

#

perfect

mighty ledge
thorny snow
#

yes exactly

mighty ledge
#

if you attach a trigger to a sensor section, then that whole sensor section will update via the trigger.

thorny snow
#

so I could simply make a new file, add a new sensor list item and have the trigger affect only that

mighty ledge
#

yes

thorny snow
#

perfect

mighty ledge
#

as long as you used merge_dir_list

#

or whatever the key is

marble jackal
#

you could define multiple sensors which use the same trigger as well

thorny snow
#

include_dir_merge_list

mighty ledge
#

yes that

thorny snow
mighty ledge
#

not the named one.

marble jackal
#
- trigger:
    - platform: state
  sensor:
    - name: sensor 1
    - name: sensor 2
thorny snow
#

yep

#

that's what I'm making

#

thanks

#

so I could sum all climate entities with their own variable under the climate platform, number entities under the number platform etc...

mighty ledge
#

yep

thorny snow
#

calculations I'd still have to do within the template state section itself I suppose

#

hmm too bad I can't test that in the template editor now 🙂

marble jackal
#

you can, but you have to assign a variable, something like
{% set trigger = { 'entity_id': 'sensor.foo' } %}

#

this will allow you to use trigger.entity_id in the template editor

#

if you need the entire trigger object, easiest is to create an automation with the trigger, trigger it by use of devtools > states and copy the entire trigger variable from the trace (the json file you can download)

thorny snow
#

okay so: a variable set in the trigger will be usable as is in any sensors associated with the trigger right? can I then still refer to those variables simply by name if I want their state?

#

keeping in mind that I'm making all my variables simply hold the state, any attributes they refer to are already taken care of

rare karma
#

Hi everyone. I have two sensors which have to be subtracted from each other. One is my EV Charger's total consumption and one is my current PV consumption. I basically want to treat this new template sensor in the following way: EV Charger - PV Consumption, but only when if EV Charger is higher than value 0. So basically it's a template sensor with some sort of net_consumption, so it should never go negative. Is this possible in any way?

thorny snow
#

"{{ [states('sensor.car_usage'), 0] | max - states('sensor.pv_production) }}" should do it

#

mind you the way you worded it right now will result in a sensor that is mostly negative based on how much you produce with PV

marble jackal
#

the templates will be rendered on the moment of the trigger, and the variables can be used (by variable name) inside the entire template configuration then

thorny snow
#

and any subsequent sensor can make use of the same base set of data

rare karma
thorny snow
#

One is my EV Charger's total consumption and one is my current PV consumption do you mean here the energy, or do you mean power

#

because when you're talking about net consumption power springs to mind

marble jackal
thorny snow
#

ah, that kinda makes this approach worthless :/

marble jackal
#

no, you can use yaml anchors

#

but your triggers are also incorrect, there is no platfom: sensor trigger

#

one moment

mighty ledge
#

well that config is wildy incorrect

thorny snow
#

then it's good that I haven't enabled it yet

mighty ledge
#

you aren't using triggers

thorny snow
#

but this is what i get when I take the previous advice into account

mighty ledge
#

you made up triggers

#

you need to use triggers that you'd use in an automation

#

like state triggers

marble jackal
rare karma
# thorny snow `One is my EV Charger's total consumption and one is my current PV consumption` ...

I think I know the issue I'm running into. I'm basically talking about Energy, I want to rebuild the energy graph in my own graph and split off the ev charger consumption from my main power. As I have PV, there will be a moment that I'm producing more energy with PV, that all works fine. But as soon as I would be charging the car, the PV Consumption would be something like 4 kWh, my own home usage is like 0.5 kWh, so somewhere in the whole calculation I want the 11 kWh the charger would consume, minus that PV production, so the bar in chart should be 8.5 kWh

thorny snow
#

yeah okay but then we're back to the thing I said about adding template triggers to a template

mighty ledge
#

no, look at what the fes posted

thorny snow
#

I'm reading the other message

thorny snow
mighty ledge
#

what the fes posted should just be a straight copy/paste

thorny snow
#

because that makes things a lot simpler

#

An error occurred during a connection to pastie.org.

rare karma
# thorny snow do you know your net import/export?

I have two "production" sensors and I have the total produced energy of PV. So if I take that total energy PV (kWh) and I subtract the two production sensors, I have my net solar consumption. I also have net import of course, those are the two "consumption" sensors"

mighty ledge
thorny snow
#

okay wow. no that was not clear at all

mighty ledge
#

I'm not sure how it wasn't

#

you just started using made up triggers

thorny snow
#

I even asked about adding things like climate entities to a climate key and numbers to a number key

mighty ledge
#

🤷‍♂️

#

it's a state trigger

#

you've made automations right?

#

all triggers are the same, everywhere

thorny snow
#

never in templates

mighty ledge
#

still doesn't mean the yaml changes

#

same trigger, same yaml

thorny snow
#

Still, thank you for the assistance

#

so now with all this I can add the attributes I wanted

mighty ledge
#

Yes, using the variables

white totem
#

Hi! For a room, I have the measured temperature (as a sensor), and the setpoints for heating and cooling (as numbers) in HA. I'd like to create a thermostat on the dashboard, but it doesn't show up. Should I create a climate entity from those entities?

mighty ledge
white totem
lofty mason
#

Can you define what a "thermostat" means to you if it cannot turn on or off a heater? I thought that was it's only function.

white totem
#

Well. Currently, I have a sensor with just a number from the thermometer. And two sliders with numbers for the setpoint for heating and cooling. That already works using the heating/cooling appliance.
So it's only a matter of displaying it like a thermostat in HA. So I thought using a template to create a climate entity from it. But if a generic thermostat could work, I can use that (and ask help in #integrations-archived if necessary(.

mighty ledge
#

just tie it to a fake heater, i.e. input boolean.

thorny snow
#

uhhh

#

[trigger] is an invalid option for [template]

#

wha?

mighty ledge
#

remove the first -sensor:, thefes must have had a typo

marble jackal
#

whoops, that was wrong indeed

thorny snow
#

but don't I need that sensor list key to isolate the trigger items?

lofty mason
thorny snow
#

or can that be used instead of the sensor key

#

like, it's a type, like sensor is a type

mighty ledge
#

the dash indicates the item

thorny snow
#

okay yeah it's a type

mighty ledge
#

so just remove the first - sensor: line and it'll work

marble jackal
#

you can use any type of template entity in combination with the trigger

#
template:
  - trigger:
    sensor:
    number:
    text:
    binary_sensor:
  - sensor:
  - number:
thorny snow
#

yeah that's what I mean, the -trigger is just another type like -sensor

#

it replaces it

mighty ledge
#

it's an option

thorny snow
#

forget it

mighty ledge
#
template:
- sensor:
  - ....

Optionally add a trigger to sensor

template:
- trigger:
  sensor:
  - ...
#

I think you're missing the impression that - indicates the start of an item inside the template collection.

#

you can have as many options as you want paired with that -

#

the next - indicates the start of the next item

thorny snow
#

the WORD trigger replaces the WORD sensor since this is a TYPE trigger and not a TYPE sensor

mighty ledge
#

nope

thorny snow
#

whatever

mighty ledge
#

it's still a sensor

#

you added a trigger to the sensor

#

I feel like your'e getting frustrated but you aren't trying to learn the yaml

#

you're making incorrect assumptions and it will just hurt you later on

#

@thorny snow just to show you why...

- sensor:
  ...
  trigger:
  ...

That's identical yaml but sensor is first instead of trigger but the trigger is triggering the sensor.

marble jackal
#

you could even write it like this:

template:
  - sensor:
    trigger:
#

too slow

mighty ledge
#

The point is: Take the time to understand the YAML. It will help you learn yaml everywhere, not just in this template.

white totem
mighty ledge
#

that's just automations

mighty ledge
white totem
# mighty ledge that's just automations

You mean, don't control the number entities directely from the generic thermostat, but write thermostat's min_temp and max_temp to the number entities with an automation?

mighty ledge
#

it turns the heater on/off based on the values you put into the min/max in combination by looking at the temperature sensor that's supplied to the integration

#

if you want a 'climate' entity for your frontend, that's the integration that you'd use

#

if you don't care about that and just want to see the values, just add that stuff to the frontend without a climate entity

#

and for your automated values, just make an automation

white totem
#

I think I should be able to manage. I'll let you know. Thanks

rare karma
nimble copper
#

Is there a template based way to get all the entity ids for a given domain?

E.g. all the entity ids for alarm_control_panel?

#

Or is states.alarm_control_panel the way to go?

inner mesa
#

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

lost locust
#

I'm trying to get "low temp" from today's forecast out of open meteo. it looks like it's all stored in the forecast array.

is there a better way of doing it than this?
{{ state_attr("weather.home", "forecast")[0].templow }}

the forecast attribute's value ({{ state_attr("weather.home", "forecast") }}) looks like this:

[{'datetime': '2022-12-19', 'condition': 'rainy', 'wind_bearing': 252, 'temperature': 32, 'templow': 30, 'wind_speed': 18.95, 'precipitation': 0.01}, {'and_so': 'on'}] 
inner mesa
#

there's nothing wrong with that if you always want the value from the first element in the. list

mighty ledge
#

which is the most current time/value

lost locust
#

yeah, the array appears to be ordered properly for me to grab "today" as the 0th indexed item. thanks, y'all.

slow vine
#

is there a simple way to get the length of a list using templates? i.e. the number of items in a input_select using something like length() I know I could do a for-loop and count but that seems overly complicated.

slow vine
#

i thought I tried that. I'll check again.

mighty ledge
#

there's also | count

slow vine
#

🤦 I thought my mistake was in length turns out I forgot to do |list first i had map only.

white totem
plain veldt
#

Im getting kinda lost at the various options for what I try to achieve. I have a sensor that has a specific state attribute when its turned on and its null or not existing when turned off. I want to template or turn this into a boolean which I can then use for automations.
With {{ state_attr() }} I can read the value but how do I turn this into a boolean or a template sensor which returns True of False

marble jackal
#

when do you want it to be true, on a specific value, or on any value?

plain veldt
#

Basically any value is True and no value or when the attribute doesn't exist False.

marble jackal
#

{{ state_attr('sensor.your_sensor', 'your_attribute') is not none }}

plain veldt
#

Oh awesome thanks! And I can basically turn that into template sensor if i'm correct

marble jackal
#

I would use a binary sensor here, which will then be on or off

plain veldt
#

Thanks for the pointers! Checking if it works in a second!

#

Yes! Works perfectly! Thanks a lot

spark tangle
#

I created two sum sensors using the new “sum” helper. The helper ofc did not have the correct state class. And then used customize to change the device class. The errors in the energy panel disappeared but it’s been 2 days and it’s still saying “it might take data to show up”. Anyone got any clue?

#

customize:
sensor.all_energy_total:
last_reset: '1970-01-01T00:00:00+00:00'
device_class: energy
state_class: measurement
sensor.lights_energy_total:
last_reset: '1970-01-01T00:00:00+00:00'
device_class: energy
state_class: measurement

marble jackal
#

You've been using very old tutorials here. state_class should betotal_increasing and last_reset is not needed

waxen meadow
modern patio
#

i try to get yet another mqtt sensor to work. but for the first time I don't get why my value_template seems to not work. my value template is

value_template: "{{ value_json.SR04.Distance }}"

this is the complete content inside the state topic:

{'Time': '2022-12-20T08:21:23', 'SR04': {'Distance': 78.509}}

i get the correct expected value when trying this inside the developer tools:

The value is {{ (my_test_json).SR04.Distance }}```

but the logs still say `Template variable error: 'value_json' is undefined when rendering '{{ value_json.SR04.Distance }}'`

I already changed value_json to just value. But this just confirms that I am using the correct input as mentioned above. any help? am i blind?
waxen rune
#

Just curious before actual troubleshooting:
Do you really get correct expected value with this in Dev Tools?

The value is {{ my_test_json.SR04.Distance }}```
I get `UndefinedError: 'str object' has no attribute 'SR04'`
#

However, this works fine: {% set my_test_json = {'Time': '2022-12-20T08:21:23', 'SR04': {'Distance': 78.509}} %} The value is {{ my_test_json.SR04.Distance }} (no ")

modern patio
#

yah... sorry. of course without "s. copied the wrong example due to all the debugging i did... i upated the question.

mighty ledge
#

@modern patio this is the best you can do in that case {{ (value | replace("'", '"') | from_json).SR04.Distance }}

#

Keep in mind that you have to use multiline yaml notation. You cannot use single line yaml notation for that template.

mighty ledge
marble jackal
#

what about {{( value | to_json | from_json ).SR04.Distance }} 🙂

#

seems to work in devtools > templates

marble jackal
mighty ledge
#

{% set value = "{'Time': '2022-12-20T08:21:23', 'SR04': {'Distance': 78.509}}" %}

marble jackal
#

ah okay

ember cloud
#

Hi there experts. I'd be happy if someone could help me to make this look more elegant. Doorbell Camera {{ now().day }}-{{ now().month }}-{{ now().year }} {{ now().hour }}:{{ now().minute }}:{{ now().second }} It works like this, but I think there is a better way to do it. I want this to look like Doorbell Camera 20-12-2022 16:49:01, however what I noticed is when say seconds are single digits it won't display 01 but just 1

mighty ledge
#

A whole mechanism would have to be built to house and store templated configuration options that could work on all integrations.

mighty ledge
ember cloud
modern patio
mighty ledge
#

then value_json will work

ember cloud
#

I'm building an automation where I want to notify multiple services of Open sensors. I'm trying to assign the template of getting the open sensors as variable so that I can use that variable later, but cannot succeed. https://pastebin.com/raw/iWCre4dQ Could you please help?

#

How do I assign a template as a variable in automations?

mighty ledge
#

the template's a little verbose, but it'll work

marble jackal
#

should work indeed, but to show what petro means with verbose, the template could also be this:

 {{ expand('binary_sensor.water_leak') | selectattr('state', 'eq', 'on') | map(attribute='name') | join(', ') }}
ember cloud
#

Thanks guys, as I'm very new to HA I'm still getting my head around these things. It didn't work the first time I wrote it for whatever reason. It works now!

pine musk
#

I have a markdown card for NWS alert(s)

#

it shows the first, but will not handle more than one

mighty ledge
#

You'll have to elaborate

pine musk
#
{{ state_attr( "sensor.nws_alerts","display_desc" ) }}
<hr>
#

Gives:

Wind Chill Watch

Headline: WIND CHILL WATCH IN EFFECT FROM LATE THURSDAY NIGHT THROUGH FRIDAY AFTERNOON
Status: Actual
Message Type: Alert
Severity: Severe
Certainty: Likely
Expires: 2022-12-20T22:00:00-06:00
Description: * WHAT...Dangerously cold wind chills possible. Wind chills as
low as 15 below zero
#

before my NAS ate itself, I had a markdown card that displayed multiples, but its been a year since I did it.

mighty ledge
#

I'm still not seeing what the problem is

#

you have 1 entity, with 2 attributes. Each attribute only has 1 info

pine musk
#

the value of the sensor is # Alerts... attributes for each alert

mighty ledge
#

does the entity have the other alerts in it's attributes? If yes, then show me the attribute. If no, then it's not possible

pine musk
#

ie, NWS_Alerts = 1 right now.

mighty ledge
#

ok

#

that still doesn't change the attribute from a string to a list

pine musk
#

ok, let me read more, sorry

mighty ledge
pine musk
#

no, using HACS/NWS Alerts

mighty ledge
mighty ledge
#

It looks like it only contains the last alert

#

i.e. not possible

mighty ledge
#

@odd maple is NWS something that finity forked?

mighty ledge
odd maple
#

finity did the leg work, I added the config_flow stuff

#

and the update coordinator

mighty ledge
#

Ah ok

#

That makes sense

odd maple
#

there was a requirement to make sure YAML config still worked for it too 😛

mighty ledge
#

Yeah I get it. I keep both on mine too

odd maple
#

is it broken?

mighty ledge
#

No, just reading the code, trying to help jazz

pine musk
#

no, Im just trying to use it

mighty ledge
#

It seems to just have the last alert

odd maple
#

it collects them all into attributes

mighty ledge
#

It doesn’t look like he’s keeping them a list

pine musk
#

aand how do you iterate through?

mighty ledge
#

It would be like any other listed attribute

#

Post the dev tool -> stages page showing the attributes

odd maple
#

index 0 will be the "latest" alert

mighty ledge
#

In which attr

odd maple
#

here's how I parse the latest alert:

    - service: script.notifications_handler
      data:
        the_title: NWS Alert - {{ state_attr('sensor.nws_alerts', 'title').split(' - ')[0] }}
        this_message: >
          "NWS: {{ state_attr('sensor.nws_alerts', 'spoken_desc').split('-')[0] }}"
mighty ledge
#

Oh….

#

Wow

odd maple
#

ya

#

not ideal, but 🤷‍♂️

mighty ledge
#

🤮

odd maple
#

it works

pine musk
#

ok, so how do I iterate through?

odd maple
#

for each on state_attr('sensor.nws_alerts', 'title').split(' - ')

mighty ledge
#

Like with what first posted

pine musk
#

ok, lemme try it.

odd maple
#

I only care about the latest alert

mighty ledge
#

It’s probably easier to use REST

odd maple
#

it is using a rest call 😛

mighty ledge
#

Lol I figured

odd maple
#

well, it's using aiohttp

#

it's the best solution for the data available 😛

vestal narwhal
#

Hi - question about passing an entity_id to a script. I can use it in a template to act on it e.g. toggle a switch. But I want to set a variable with an initial state so I can check that it has changed (some switches seems to need a prod sometimes) e.g.

alias: ReallyToggle
variables:
  init_state: “states(‘{{entity_id}}’)”
sequence:
  - service: switch.toggle
    target: “{{ entity_id }}”

then code to wait to see that the state changes …
The switch toggles, but the init_state variable doesn't hold the evaluated value - only a string containing "states('switch.bedside_light')"
How do I get the initial state stored in a variable for later use?

inner mesa
#

that is broken syntax

#

there are some great docs in the channel topic

#

this in particular:
init_state: “states(‘{{entity_id}}’)”

#

init_state: "{{ states(entity_id) }}"

vestal narwhal
#

Thanks - I thought I had tried that.

pine musk
#

firstof9: I am trying to use the restapi package?

gaunt peak
#

Are templates the only way to calculate how much time my heater has been on? I'm using a Nest thermostat.

plain magnetBOT
gaunt peak
#

Oh awesome. I did a bunch of searching and somehow missed that.

gaunt peak
# plain magnet

Hmm....The example shows a light, pretty basic with entity and state but my thermostat has an extra....state I guess? I'm not sure what it would be called. What I mean is to get it to say "heating" in a template I need to put:
{{ state_attr('climate.hallway', 'hvac_action') }}
For history_stats I'd put "climate.hallway" as the entity and "heating" as the state, but where does "hvac_action" go?

marble jackal
#

Well, if you want to keep track of an attribute, you'll need to create a template sensor out of that attribute

#

At least if you want to use history stats

#

Which will probably be easier than keeping track of the duration the attribute was heating in a template sensor (which still is another option)

gaunt peak
#

Thanks

pine musk
#

got something strange happening

#

conditional card, not turning off.

#
type: conditional
conditions:
  - entity: sensor.weatheralerts_1_alert_2
    state_not: 'off'
card:
  type: markdown
  content: >-
    <font size=12>**{{ state_attr(
    "sensor.weatheralerts_1_alert_2","alert_event" ) }}```
#

stays active

#

no matter what sensor.weatheralerts_1_alert_2 says

#

right now it is off

#

I have tried making it state: off

#

and state: on

#

and state_not: off

buoyant pine
#

Is it actually a sensor or is it a binary sensor?

pine musk
#

sensor

#

sensor.weatheralerts_1_alert_2

#

nevermind, I'm an idiot

#

lovelace doesn't hide things when you're editing

tired sandal
#

Trying to filter an array of forecast objects thusly:

{% set forecast = state_attr('weather.home_hourly', 'forecast') %}
{% set future_entries = [] %}
{% for entry in forecast %}
  {% set datetime_object = entry.datetime | as_datetime %}
  {% if datetime_object > now() %}
    {% set future_entries = future_entries + [entry] %}
  {% endif %}
{% endfor %}
{{ future_entries }}
inner mesa
#

That could be simpler 🙂

cobalt tinsel
#

I have a usb serial device that I am able to read in windows and linux, with different methods (snmp+rest sensor). How can I merge them into one sensor output so I can dual boot and keep feeding data after changing OS (without having 2 different sensors)

tired sandal
#

sorry - had to go deal with a baby

#

yes, it could

#

it also doesn't work

#

it returns []

inner mesa
#
{% set dates = state_attr('weather.home', 'forecast')|map(attribute='datetime')|map('as_datetime')|select('gt', utcnow())|map('string')|list %}
{{ state_attr('weather.home', 'forecast')|selectattr('datetime', 'in', dates|replace(' ', 'T'))|list }}
#

there's gotta be a better way

tired sandal
#

Ahhh so we get an array of dates, then only let through records in that array

inner mesa
#

right

#

it's just much more complicated because dates in attributes are strings

tired sandal
#

yeah, no kidding

inner mesa
#

this is cleaner:

{% set forecast = state_attr('weather.home', 'forecast') %}
{% set curtime = utcnow().replace(microsecond=0).isoformat() %}
{{ forecast|selectattr('datetime', 'gt', curtime)|list }}
#

strings comparisons are okay with that timeformat

tired sandal
#

....that's it?!

#

...wow.

#

I'm impressed.

#

so if i wanted to further filter that list so that it only contains entries where templow < 32 and condition in conditions - i could do that with something similar to what yo uhad first time round?

inner mesa
#

just keep adding selectattr() to the last line

tired sandal
#

🙂

#

thx

#
{% set forecast = state_attr('weather.home', 'forecast') %}
{% set curtime = utcnow().replace(microsecond=0).isoformat() %}
{%
  set data = forecast
  | selectattr('datetime', 'gt', curtime)
  | selectattr('templow', 'lt', 32)
  | selectattr('condition', 'in', ('cloudy'))
  | list
%}
inner mesa
#

yes

tired sandal
#

basically i want to know if i should turn on my heat cables or not

#

(obviously swapping out 'cloudy' for something more sensible)

#

im wondering if it would make more sense to check precipitation instead

inner mesa
#

although selectattr('condition', 'in', ('cloudy')) probably isn't what you want

tired sandal
#

😉

#

was thinking 'snow', 'hail', 'rain'

inner mesa
#

that's the same as 'eq'

tired sandal
#

wait what

inner mesa
#

ok

tired sandal
#

so, selectattr('condition', 'in', ('cloudy')) is the same as condition == ['cloudy']?

inner mesa
#

if it's just those exact words, then it's okay

tired sandal
#

well i want to know if we're expecting any one of conditions over the next 24 hours

inner mesa
#

if it's "partly cloudy" and "mostly cloudy" and "cloudy with a chance of meatballs", then you want to use a regex_search()

tired sandal
#

right

#

at this point, does checking precipitiation make more sense?

inner mesa
#

🤷

#

do you care if it's raining or snowing?

#

or frogs falling from the sky?

tired sandal
#

i dont care which

#

i just want to know im not going to end up with ice dams

#

under the assumption that it's not going to start raining men I'm going to guess that any kind of precipitation is a situation where i might want to turn on the ice melters

inner mesa
#

well, in any case, you have the technology

tired sandal
#

sure

#

just wanted a sanity check that what I'm suggesting roughly makes sense

#

precipitation > 0?

inner mesa
#

in theory that should be the same as "rain", I would think

tired sandal
#

interesting

#

next time it snows, i'll keep an eye on that and see if it reacts to that also

#

the documentation on what the various weather attributes do isn't terribly clear

inner mesa
#

they come from the provider

#

you can just go see on the website?

#

whatever you're using

tired sandal
#

Also, did you say I needed regex_search?

inner mesa
#

ok

#

{{ forecast|selectattr('datetime', 'gt', curtime)|selectattr('condition', 'search', 'sunny|cloudy')|list }}

elfin pawn
#

hi, I have a question here:
Can we use global variants in templates?
e.g.

  • binary_sensor:
    • name: "my sensor"
      state: >
      {% set test = some value %}
      .....

      attributes:
      value: "{{ test}}"

I define test in "state", and want to access test's value from "attributes".

marble jackal
#

You can define them as trigger variables on a trigger based template sensor, or in an attribute

#

And refer to the attribute

analog mulch
#

Hi. I'd like to set up a numeric_state trigger when any of my battery entities falls below e.g. 10%. I'd rather generate this dynamically, instead of keeping track in a pre-defined group, so e.g. testing for any entity ending with *battery. Is this possib;e? I guess one difficulty is that I would like to know which of the entities caused the trigger, so that I can message myself to change it.

marble jackal
#

My approach would be to create a template sensor which has a count of the battery sensors below 10% as it's state, and use that to trigger your automation

analog mulch
#

I was thinking about something like that, but then how would I know which is the new battery which has fallen below 10%. Is there some way of writing that into the attributes of a template sensor?

silent seal
#

Yes

marble jackal
#

You can list the batteries below 10% in an attribute

#

And then compare the from_state and to_state of that attribute

floral shuttle
#

or have that listed in auto-entities and sorted.

#
    filter:
      template: >

        {% set threshold = states('input_number.battery_alert_level')|float(0) %}
        {% for s in expand('group.battery_sensors_auto')
           if s.state|float(0) < threshold %}
          {{s.entity_id}}
        {%- endfor %}
    sort:
      method: state
      numeric: true```
#

which only sorts on state, but ideally you;d not have too many batteries dying on you...

analog mulch
floral shuttle
#

a yes, sorry, didnt read closely enough. my solution indeed is for the frontend.

#
      - unique_id: low_level_batteries
        name: Low level batteries
        state: >
          {% set alert_level = states('input_number.battery_alert_level')|int(default=0) %}
          {{expand('group.battery_sensors_auto')
                   |rejectattr('state','in',['unknown','unavailable'])
                   |map(attribute='state')
                   |map('int',default=0)
                   |select('<',alert_level)
                   |list|count}}``` and variants should do the templating and you could do what TheFes suggests: from_state < to_state (though I confess I have to look that up... these template triggers are not as obvious as one might think)
#

btw, the auto created group is made with: action: service: group.set data: object_id: battery_sensors_auto entities: > {{states.sensor |selectattr('attributes.device_class','defined') |selectattr('attributes.device_class','eq','battery') |map(attribute='entity_id')|list}} at homeassistant start

analog mulch
mighty ledge
#

everyone that's cool is doing it

floral shuttle
#

suppose the only way is to trigger on the state of the sensor, and then add a condition the from_state < to_state. there's is no way to write that in the trigger

#

smthng like this```
trigger:
- platform: state
entity_id: sensor.low_level_batteries
id: count
- platform: state
entity_id: binary_sensor.battery_alert
from: 'off'
to: 'on'
id: alert
condition:
- >
{{trigger.id == 'count' and trigger.to_state.state > trigger.from_state.state or
trigger.id == 'alert'}}

floral shuttle
#

really odd, that automation now works perfectly, but I can have my ancient condition template``` - >
{% set x = ['unavailable','unknown'] %}
{{trigger.to_state.state not in x and trigger.from_state.state not in x}}}}

#

which somehow prevents it from executing the action, even though none of the states are unavailable/unknown...

mighty ledge
#

you don't have the conditions in the correct order @floral shuttle

#

your second condition should be first

floral shuttle
#

a yes, thats true. a c&p error, caused by testing the trigger.id condition I added for wigster. thx.

#

doesnt change the outcome though, it still stops on that same condition

marble jackal
#

Hehe
Would be nice if expand would work on every attribute entity_id. Then you don't need to create groups using automations, but to can use template sensors

#

You can already use expand(state_attr('sensor.foo', 'entity_id')) of course

floral shuttle
#

yes, there's an ancient FR for that iirc (use that as template trigger), but it was rejected

mighty ledge
floral shuttle
#

this is the one failing condition. I figured it could be because I added a second state trigger, and it stumbles on that, but it really shouldnt given the fact its state is known and available at all times.

mighty ledge
#

in order for it to be checked, the other two need to be true

#

i.e. the result will not compute and it will just show false

#

are the other two true?

floral shuttle
#

yes they are. And, if I leave the condition out, it fire correctly

#
    condition:
      - >
        {{trigger.to_state is not none and trigger.from_state is not none}}
#       - >
#         {% set x = ['unavailable','unknown'] %}
#         {{trigger.to_state.state not in x and trigger.from_state.state not in x}}}}
      - >
        {{trigger.id == 'count' and
          trigger.to_state.state|int(default=0) > trigger.from_state.state|int(default=0) or
          trigger.id == 'alert'}}
mighty ledge
#

ah, well you have 4 }}}} at the end, that's why

floral shuttle
#

works fine.

#

right!! ....

buoyant pine
floral shuttle
#

let me check that 😉

mighty ledge
#
#         {% set x = ['unavailable','unknown'] %}
#         {{trigger.to_state.state not in x and trigger.from_state.state not in x}}}}
                                                                                   ^^
floral shuttle
#

yep, that was it... grrr so sorry

#

so the config checker doesnt choke on that (its incorrect yaml...) the automation reload doesnt, and the trace simply says the result is false... might be an #automations-archived issue

mighty ledge
#

it won't choke on that

#

{{ }} is the template }} is extra characters you added that's considered a string

floral shuttle
mighty ledge
#

no different than outputting
Hey my name is {{ }}

#

instead what you were outputting was True}}

#

which isn't true/false so that rejects the condition

floral shuttle
#

yes, of course I understand that, but we also know having }}}} in a yaml file is not supposed to be . I wonder if ChatBot would notice...

mighty ledge
#

that's not necessarily true

#

what if I was creating a dictionary

#

}} is an escaped }

floral shuttle
#

in any case, the last 2 }} are orphans.

#

if nor prepended by {{ ?

mighty ledge
#

right, but you still aren't accepting that the user may want those characters

#

its no different than {{ ... }}xx

#

it just so happens that the characters are the same as jinja identifiers

#

still does not change the fact that someone may actually want that in their string

floral shuttle
#

sure, purely theoretically one might want that in a string. I challenge you though to find a correct condition template having 4 }}}} at the end of the condition and be valid syntax..

mighty ledge
#

a populated dictionary resolves true 😉

#

i already solved that challenge

floral shuttle
#

you spotted it didnt you?

mighty ledge
#

4 posts up

#

{} will resolve false

#

{'x':1} will resolve true

#

if someone is piecing together a dictionary for their condition, they will have lopsided }}

floral shuttle
#

lopsided had to look that up 😉

#

o well, even the smily is

mighty ledge
#

does your language not have a word for lopsided?

floral shuttle
#

sure, I just hadnt heard of that before.

#

crooked, off-balance, askew. languages are a beautiful thing.

floral shuttle
#

all conditions are valid, but they need to be evaluated.. to true

gaunt peak
#

Hi,
I'm trying to use history_stats but I feel like something is set up wrong, just can't figure out what.
I created a template sensor that shows the state of my heater

      state: >
        {{ state_attr('climate.hallway', 'hvac_action') }}```
Then I added that to my history_stats with
```sensor:
  - platform: history_stats
    name: Heating on today
    entity_id: sensor.hvac_action
    state: "heating"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now() }}```
Since last night I'm still getting 0.0 hours.  Where did I go wrong?
marble jackal
#

Could be a copy paste error, but you are missing }" at the end

#

And your template sensor exists and works?

gaunt peak
#

Sorry, it was a copy paste error. It's there for sure.

Yes. I have it in my Lovelace just to make sure.

#

I tried to paste a screenshot but apparently I can't.

floral shuttle
#

did you include the new sensor in your recorder settings (or at least didnt exclude it by some filter)

mighty ledge
#

it looks like it's already in history. Are you sure the state is heating

gaunt peak
#

It's currently heating now so if you go back to the imgur (https://imgur.com/a/CGZSBEZ) I added another image showing what sensor.hvac_action is showing now.

mighty ledge
#

then it should be working

gaunt peak
mighty ledge
#

the only other option is that you have 2 sensor sections

gaunt peak
#

Negative. My Config is pretty small still as I've just started from scratch again. Only 43 lines total so it's pretty easy to check for that.

mighty ledge
gaunt peak
#

Balls.

marble jackal
#

And the entity_id doesn't have a _2 added by any chance?

gaunt peak
#

The "sensor.hvac_action" one?

marble jackal
#

Yep

gaunt peak
#

There is no "_2" from what I can see through what I have in Lovelace, or in the Entities list.
However, here's something interesting....
I added recorder just for fun, even though it was said it shouldn't be needed and got a number show up but only on my sensor card, not my stat card
https://imgur.com/a/CGZSBEZ

inner mesa
#

If you don't have recorder:, you have no history

floral shuttle
#

it would need some time before that (statistics) would come up

gaunt peak
#

I just started "recorder" today but the entity was created yesterday.

marble jackal
#

If you wouldn't already had recorder, you would not be able to see the graph with the state changes

mighty ledge
#

recorder is in default_config so you shouldn't need it unless you removed default_config

marble jackal
#

This one

mighty ledge
#

also, what fes said

#

so, everything is working in my eyes except the history stats entity

#

which doesn't make sense. Unless the units are something crazy

gaunt peak
#

I put type as time and it automatically put h, so I'm assuming the units defaulted to hours, which is fine.

#

Now that recorder is on, it is increasing but the number doesn't make sense. It says 5.89 hours today and it's only 9:11 where I am. It's -34C with a windchill of -47C but it still hasn't been on that long.

inner mesa
#

Did you remove default_config:?

mighty ledge
#

it's saying ~6 of the 9 hours, heating was on

gaunt peak
mighty ledge
#

Just look at your graph that you posted

#

it's mostly dark blue

#

where idle is light blue

#

you got way more dark blue than light blue

#

just my 2c

gaunt peak
#

~5.91 hours adding them up manually, I guess it is correct. Damn it's cold, haha.

#

Ok, cool so that's correct.
It seems if recorder needs to be on, that should be mentioned somewhere in the history_stats document. All it says there about recorder is

If the duration exceeds the number of days of history stored by the recorder component (purge_keep_days), the history statistics sensor will not have all the information it needs to look at the entire duration.

mighty ledge
#

history stats require history

#

history requires recorder

#

if you don't record anything, how would it know the history?

#

it's pretty much implied

#

however, recorder and history are in default_config, so if you're running default config, you don't run into this issue. default config is on by default in all installations

gaunt peak
#

Ya, it makes sense now but even you said it's not necessary because it's already there. Mine wasn't there and I don't remove anything.

#

default_config is the same as configuration.yaml?

mighty ledge
#

no

#

it's in configuration.yaml

#

if you started with a blank configuration.yaml, then you are to blame. You should at least start with the default configuration.yaml, which is created by HA on first boot

gaunt peak
#

This is what was in there when I started:

default_config:

http:
  ssl_certificate: /ssl/fullchain.pem
  ssl_key: /ssl/privkey.pem

# Text to speech
tts:
  - platform: google_translate

automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml```
mighty ledge
#

then recorder was enabled

floral shuttle
mighty ledge
#

hmmm

gaunt peak
floral shuttle
#

history is, so it might be a secondary dependency?

mighty ledge
#

maybe it was changed, doesn't seem right

#

history does require recorder

floral shuttle
#

It depends on the recorder integration for storing the data and uses the same database setting.

gaunt peak
#

It seems like maybe the recorder integration isn't there by default anymore?

marble jackal
#

I believe it is impossible not to use recorder so that's why it is not in default_config

floral shuttle
#

no, its loaded as dependency for history, so it should be there if you have default_config: in your configuration.yaml

floral shuttle
gaunt peak
#

I do have default_config but had to add recorder separately for it to work. Or at least that's the only way I could get it to work.

marble jackal
#

I think that's changed in one of the recent releases, I kinda remember something like that. Not sure though

floral shuttle
#

well, in any case that is unintuitive , and needs to be made explicit in the docs

#

and what tical experiences feels like a bug: using default_config: and still required to explicitly include recorder:

gaunt peak
#

Agreed.

#

Side note, even though the sensor card shows 6.01 hours now, the graph is still at 0.

#

I don't really need the graph though.

floral shuttle
#

just to be sure: you did restart after adding that configuration change?

gaunt peak
#

Yup. That's when the number showed up.

floral shuttle
#

well at least that proves what Petro said, all requirements are met, so its now up to figuring out what's wrong with this specific entity

gaunt peak
#

Another side note/question. I can't add this to the energy dashboard right? Seems like you can only add certain entities.

floral shuttle
#

you can add any energy sensor. this is a time sensor. how would you add that?

gaunt peak
#

I'd add another step to do some math.

floral shuttle
#

btw, we should really try and keep this talk on topic 😉

gaunt peak
#

Sorry, haha.

#

I think we've determined we now need to add "recorder" where we didn't before. As far as the stats card not working and still showing 0h. This is the yaml for that

entity: sensor.heating_on_today
period:
  calendar:
    period: day
stat_type: mean```
vs the sensor card
```hours_to_show: 24
graph: line
type: sensor
entity: sensor.heating_on_today
detail: 1
unit: hours```
floral shuttle
#

right, and since this is the #templates-archived topic, you really should move further investigation to #integrations-archived . Or if you like to keeps things together, writeup a community post and reference that in Discord. way easier imho.

gaunt peak
#

Will do.
Thanks for the help everyone.

#

OK sorry. This probably goes into integrations as well but just more of an FYI, I went into statistics and got this for pretty much, if not, everything

This entity is no longer being recorded

#

I didn't put in any exceptions/exclusions when I added recorder, I just added the heating on entity.

mighty ledge
#

that means you're only recording what you included 😉

#

you can simply just have recorder: and it'll do all entities.

gaunt peak
#

Oh ok. Thanks

ember cloud
#

Hi. Can cards take templates?

inner mesa
#

depends on the ard

ember cloud
inner mesa
ember cloud
#

Thank you

solar hemlock
#
data_template:
  entity_id: >
      {% for light in area_entities('living room') | select('match', 'light') | select('is_state', 'on') %}
      - {{ light }} {% endfor %}
  kelvin: 300```
Is there anything wrong with the syntax of the entity_ID template? It seems to work within the developer tools but fails when used in a script. 
End goal is to check what lights are on in a particular room and to set the kelvin for the lights that are currently turned on.
plain magnetBOT
#

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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

inner mesa
#

and yes, you should output a list, rather than trying to create the YAML for it

marble jackal
#

You also don't need a for loop here

inner mesa
#

{{ expand(area_entities('office'))|selectattr('domain', 'eq', 'light')|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}

#

O

#

I'm sure petro will be along to show how the latest HA update has some new tricks for that 🙂

marble jackal
#

Basically adding | list to the selection for the for loop would work

#

He's already using the new stuff

inner mesa
#

oh, indeed

#

I feel like a dinosaur

solar hemlock
#

Thank you both

inner mesa
#

I could get used to this:
{{ area_entities('office')|select('match', 'light')|select('is_state', 'on')|list }}

marble jackal
#

Well, that works now

#

Using something like this will remove the need to check if an attribute is defined
{{ states.sensor | selectattr('entity_id', 'is_state_attr', 'device_class', 'battery') | list }}

inner mesa
#

I used to be happy to be able to solve something with a line of filters. Now it has to all happen within a single filter 🙂

#

{{ states.sensor|do_useful_stuff(x, y, z, a, b, c)|list }}

marble jackal
#

The old line of filters still works 🙂

inner mesa
#

you just look like a 🦎

solar hemlock
#

Question is there an easy way to remove one light entity from the list?

inner mesa
#

a list of what? entity_ids?

#

yes, with reject() or rejectattr()

ember cloud
#

How can I condition if media player volume is increasing or decreasing? is it possible to get last volume and compare to current ?

marble jackal
#

in an automation?

#

if so, what is the trigger?

desert tangle
#

Ok, couldnt make it, i asked it in general.. and answer was "you need templates"

#

Is there way to get "box" where to write message you want, and just send it to TV?

#

Already made input_text helper, and managed to make it work with button card, but i dont want to edit it everytime to change message

marble jackal
#

you want to have a box to enter messages, but you don't want to edit the message every time?

desert tangle
#

I meant, i have now button to send message to my LG_tv, but it send everytime same message, when triggered, unlessa i edit UI and change the message from button configurations

marble jackal
#

ah, okay

silent seal
#

Two cards. An input text and a button that makes the call?

desert tangle
#

How do i do that ? 😮

marble jackal
#

do you have the service call to send the message in a tap_action of the button now?

desert tangle
marble jackal
#

you can´t use templates in a tap action

ember cloud
marble jackal
#

you need to use a script here, and call the script

#

in the script you can use

message: "{{ states('input_text.your_input_text') }}"
#

instead of message: "Your fixed message"

desert tangle
#

and this i put in to scripts.yaml ?

marble jackal
#

or create it in the GUI

#

it will put it in scripts.yaml

marble jackal
desert tangle
#

Omg im poor MF 😄

#

i just dont get it 🫣

silent seal
#

When does the message need to send?

#

Is it when the washing machine finishes? Window is open? Or when you type something in a box and click a button?

desert tangle
#

Id like to type messages.

silent seal
#

Ok, did you make the script already?

desert tangle
#

Nope

silent seal
#

Start by doing that 🙂

desert tangle
#

I mean, i have just made that text helper, and made it to call service... And it work, i just dont get that box where to write text, and press send/notify or smthg

silent seal
#

The entity will be for the text, and the button calls the script

desert tangle
#

and for button entity, is that TV ?

silent seal
#

No, the script which sends the message using the template.

desert tangle
silent seal
desert tangle
#

:D:D:D

#

Looks like i dont need these kind of things

#

dafug

elfin pawn
# marble jackal And refer to the attribute

That is exactly my goal, to refer to the attribute which I can pass some value based on the state section.
e.g.
After some process in the state section, I set value to the variant X, and I want to refer X in the attribute section.
I do not know how to do that.

marble jackal
#

Set the attribute or refer to it?

elfin pawn
marble jackal
#

No you should do it the other way around. Do the calculations in the attribute, and use the value of the variable in the state template

copper sedge
#

Taking my first steps into templates with a Binary Sensor - Is it possible to change the 'states' from on/off to be true/false instead? Itd make more sense for the output to be a true or false for the sensors use, as opposed to on/off

#

I saw the Device class supposedly changes it, but the one I set it to (presence) seems to still be on/off

silent seal
#

In a nutshell, no. Use things like is_state('binary_sensor.my_sensor_here', 'on') to output booleans

copper sedge
#

Unfortunate - seems like binary would make sense to return true or false, but glad it can be 'translated' to it

#

As a followup, Im trying to iterate through a list, and if any element of the if statements are true, I want the sensor to be on. However, it keeps returning 'off', even when the templating testing grounds shows that the output of the if statements are true.

silent seal
#

Well usually for that you would use | selectattr('state', 'eq', 'on') | list | count or similar

copper sedge
#

Could you expand a bit on that? I havent figure out how to properly use the filters

#

For reference, Im trying to loop through a list of chores returned by the Grocy integration, and create a sensor to see if there are chores due today or tomorrow to send notifications with that info.

- binary_sensor:
    - name: PERSONS chores today boolean
      state: >
        {% for chore in state_attr('sensor.grocy_chores','chores') 
            if chore['next_estimated_execution_time'].split('T')[0] == now().date().strftime('%Y-%m-%d')
          and chore['next_execution_assigned_user']['username'] == "PERSON"%}
          {% endif %}
        {% endfor %}
silent seal
#

Did you check the pins? There are links to various useful resources on using Jinja there

copper sedge
#

Ive been reading the HA templates page, but havent looked a jinja specific resources. Ill check those out though

elfin pawn
#

@marble jackal I have no idea what to do.
I cannot put statements in the attributes section. But I have to put statements in every attributes. Which means lot of duplicates codes.😓

  • binary_sensor:
    • name: "mySensor_Test"
      state: >
      {{ output1 }}

      attributes: >
      {%
      set output1 = "aaa"
      set output2 = "bbb"
      %}

      attr_1: {{output1}}
      attr_2: {{output2}}

little salmon
#

How can I tell if a dict has a given key?

buoyant pine
#
{{ key in dict_name.keys() }}
``` will return True or False. Replace `key` with the key you're looking for and `dict_name` with the dict you're referencing
little salmon
#

Thanks!

marble jackal
elfin pawn
fallen nova
#

hello. i am triying to create a sensor with 4 states for my gate: 1 open,2 closed, 3 opening,4 closing. i am using an esp8266 willing ot achieve this. i managed to create the open and close states but i do not know how to build the opening and closng ones. is there a syntax that can be used that uses "if from state closed to state open then opening" and "if from state open to state closed then closing"?

waxen rune
elfin pawn
# marble jackal No, like this ```yaml - binary_sensor: - name: Test state: "{{ state_a...

Your example works well. But I am afraid that this is not my goal.
In the template, I want to create a sensor named "Test", which is based on multiple door sensors. I want to enumerate all those sensors, find which one is opened,
then put the sensor's name into Test's attribute.
So, the automation which is triggered by the Test can know which door is opened.

marble jackal
#

Sure, then create an attribute which lists those sensors

#

And for the state template you can check if the attribute has any entities listed

elfin pawn
#

my code like this

  • binary_sensor:
    • name: "Test"
      state: >
      {% if door opened %}
      {% set state_attr(this.entity_id,'TS1') = door's name %}
      {% set state_attr(this.entity_id,'TS2') = timestamp %}
      {% endif %}

      {{ "on" }}
      device_class: "problem"
      unique_id: "f160f1a9f6a0e89a2b0d24fe865de7ba"
      icon: "mdi:alarm-light"
      attributes:
      TS1: "TS1"
      TS2: "TS2"

fallen nova
# waxen rune "if from state closed to state open then opening" - how will you know when it sh...

the idea is to use the 3 contacts of the mechanical limiter of the gate: if the closed limiter is active, then gate closed. if the open limiter active, then gate open. if the limiter in neutral position(not closed or open) but the last active limiter e.g was the "open" then as the gate is moving it can move only towards closing..so state "closing. and this is logic i do not know how to write it

waxen rune
#

Ok, I am sure there are more clever ways to do it, but I use an automation that records the last certain state (open/closed) in a helper (input_text).
And a template that uses that.
Like "if input_text is open and the mechanical limiter is neutral then 'closing' and vice versa"

fallen nova
waxen rune
marble jackal
#

you can not assign an attribute value in your state template

#

but if you just want a binary sensor which is on if any door is open, you can just create a binary sensor group in the helper section

fallen nova
floral shuttle
fallen nova
# floral shuttle

Thank You also for the input. will test both scenarios when i will get to that point 🙂

plain magnetBOT
#

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

obtuse zephyr
#

Did you try wrapping the value in quotes? value: "{{ states('input_number.sleep_timer_bedroom_minutes') | int + 5 }}"

mortal talon
#

also just value: {{ states('input_number.sleep_timer_bedroom_minutes') }} doesn't work, so it's like states isn't available on dashboard widgets? can that be the case? 🤔

mighty ledge
#

you can't template in the frontend

#

you have to make a script and use that in the frontend

mortal talon
#

ah. well that explains it then 🙂 I'll do some more research on that, thanks!

mighty ledge
#

so make an increment script and a decrement script and call those instead

little salmon
#

I am so close to getting this to work as I want, the current flaw with this code is that it doesn't output 0 in the case none match, but I'm sure there is a better way to get the length of matching entities without looping

{% set room = 'office' %}
{% for tracker in expand('group.esphome_trackers') if states(tracker.entity_id) == room %}
  {{ loop.length if loop.first }}
{% endfor %}
obtuse zephyr
little salmon
tidal sinew
#

Hi all, I’m looking to creat a sensor to track when my load is coming from batteries versus the grid. Batteries take over at 7pm turn off when battery hits 20%. So I need a way that my sensor only collect load after 7pm. Any ideas?

#

Before 7 I’m collect the data in my general overall energy consumed sensor.

plain magnetBOT
#

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

obtuse zephyr
#

Did you check your log?

hazy surge
#

Nothing special, unless this that happens when I reload the Template entities :
Request for https://homegraph.googleapis.com/v1/devices:reportStateAndNotification failed: 404

obtuse zephyr
#

Seems odd, that section works for me without issue. That's just straight in your configuration.yaml?

hazy surge
#

yes

#

Oh I think I figured something !
I was looking from the "entity search" (or "e" shortcut). It's not there. But it's present in the Dev tools/States

obtuse zephyr
#

Maybe Ctrl+F5, hard refresh

hazy surge
#

you are right!

#

Thanks all seems fine now 🙂

obtuse zephyr
#

Glad to hear!

willow skiff
#

Hello 🙂

#

is HA able to parse JSONL ( json line )

silent seal
#

Not directly, but it depends on where it's coming from

willow skiff
#

using REST, but the output is a JSONL rather than a JSON array

silent seal
#

Did you look at other ways to get LoRaWaN devices into HA already?

#

You might have better luck with a command line script that writes to a file, and then reading from that file.

willow skiff
#

alternative I can get MQTT but I just thought i would give a try to REST 🙂

silent seal
#

If REST isn't returning JSON or XML I would skip it and try MQTT

willow skiff
#

ok cool 🙂 that was my failback but it sounds like I have to do so

elfin pawn
elfin pawn
marble jackal
#

Well, your example showed a binary sensor, which will also be on or off

#

But you can do something like this

- sensor:
    - name: Doors open
      state: "{{ state_attr(this.entity_id, 'doors_open') | count }}"
      attributes:
        doors_open: "{{ states.binary_sensor | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | select('is_state_attr', 'device_class', 'door') | list }}"
cobalt tinsel
#

Is there an easy way to merge sensors? I have a situation where I'm getting data from 2 places, but only one of them can be active at a time

obtuse zephyr
#

Is it clear when one should be read versus the other? Should be pretty easy to come up w/ an expression, if so

cobalt tinsel
#

Not really, just based on which one is available. I'm reading a usb device and dual booting. If I'm on windows, it's SNMP, if on linux, REST

#

Have not yet found a better solution (can't use the same method in each OS yet)

marble jackal
#

{{ [ 'sensor.sensor_1', 'sensor.sensor_2' ] | map('states') | reject('eq', 'unavailable') | list | first }} should give you the state of the one which is available

#

Can they be both unavailable as well?

cobalt tinsel
#

🪄 thank you this is great. I suppose they could, if that computer is off

marble jackal
#

Then this will give an error

#
{% set a = [ 'sensor.sensor_1', 'sensor.sensor_2' ] | map('states') | reject('eq', 'unavailable') | list %}
{{ a[0] if iif(a) else 'inactive' }}
#

That won't give an error

cobalt tinsel
#

if I read this right, the bottom part is setting it to inactive so it avoids the error from reject('unavailable')?

#

Thank you, this is great. I'll do some testing

marble jackal
#

Sorry, that was incorrect, now it should work

#

It avoids the error from first which can't be applied to an empty list

cobalt tinsel
#

Worked perfectly, thanks again @marble jackal

remote saffron
#

I'm trying to create a REST sensor using an endpoint which returns XML (which is converted automatically to JSON).

When the conversions happens, at XML twig like:

<sysuptime value="206391" />

gets converted to :

{ 'sysuptime': { '@value': '259730' }}

The XML to JSON conversion documentation at https://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html suggests that this should be accessed as:

sysuptime["@name"]

But I cannot get any permutation of this to work in the value_template configuration. For example:

value_template: "{{ value_json[\"value\"] }}"

returns an entity with attribute sysuptime and value:

'@value': '260560'

Am I missing something obvious here?

marble jackal
#

I think this should work

value_template: '{{ value_json.sysuptime["@value"] }}'
remote saffron
marble jackal
#

What's the yaml for the rest sensor?

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

loud wave
#

Yesterday this worked:

  • platform: template
    sensors:
    garage_state_right:
    friendly_name: Garage State (Right)
    value_template: >-
    states('sensor.garage_door_sensor_right_alarm_level')
    icon_template: >-
    {% if states('sensor.garage_door_sensor_right_alarm_level') | int == 0 %}
    closed
    mdi:garage
    {% else %}
    open
    mdi:garage-open
    {% endif %}

Today the icon doesn't appear. Anyone have any ideas?

#

It only shows the name I gave it in the button cfg

obtuse zephyr
#

What's the state of sensor.garage_door_sensor_right_alarm_level

#

Feels like there's extra text in your icon_template. Why do you have "closed" and "open" on their own lines

fringe sail
#

Hey guys. Can anybody tell me why the following code doesn't make the icon color match the lightbulb color?```

type: custom:mushroom-template-card
entity: light.office_light
primary: Office Light
layout: vertical
icon: mdi:lightbulb-outline
icon_color: "{{ state_attr('light.office_light', 'rgb_color') }}"```

This "{{ state_attr('light.office_light', 'rgb_color') }}" returns the rgb color in dev tools.

loud wave
#

I put the open and close status and the value template section so I fixed that but it just won't load the icon based on the state which is 0 or 255 for the tilt sensor

#

Up till yesterday this all worked fine but all of a sudden just blank where the icon would be. Now. I just can't figure it out

obtuse zephyr
#

What's the state of that sensor

loud wave
obtuse zephyr
#

If you put that template in Dev Tools -> Template, does that output just the mdi:icon text?

loud wave
#

This:

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

{% if states('sensor.garage_door_sensor_left_alarm_level') | int == "0" %}
mdi:garage-variant
{% else %}
mdi:garage-open-variant
{% endif %}

Outputs this:

0
mdi:garage-open-variant

#

The output is both?

obtuse zephyr
#

Well, {{ states('sensor.garage_door_sensor_left_alarm_level') }} isn't part of your icon_template, right?

#

Just the lower part is

plain magnetBOT
#

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

loud wave
#

I should probably remove quotes from "0", right?

obtuse zephyr
#

Yup

loud wave
#

Done and restarting

obtuse zephyr
loud wave
# obtuse zephyr Yup

It's working now! Man I have no idea but maybe I made a change there and didn't remember

#

Thx so much for your time, @obtuse zephyr

obtuse zephyr
#

You bet!

loud wave
#

I also learned what value_template is for

#

Now that I know it sounds so stupid that I DIDN'T know of course lol

obtuse zephyr
#

Just takes a little learning, now you know

loud wave
loud wave
obtuse zephyr
#

The different keys you can set up

fringe sail
obtuse zephyr
#

That effectively puts a new line between each integer. Ideally, it'd be a comma, but that flips it back to an array

loud wave
fringe sail
#

Are you saying that particular custom card isn't written to conform to all of the same rules as HA cards?

obtuse zephyr
#

Maybe? If your initial template worked for other cards... then it's likely the other cards know how to interpret the input as an array. The Mushroom card though, expects a string

fringe sail
#

Oh ok. I don't think that I'll ever really get a good handle on a lot of this. Every time that I think that I've got a good understanding of a rule, there's an exception to that rule, that I didn't know about.

#

I'm pretty sure this is my ocd in action, but what happened to the light "halo" when I use your method?

#

The halo normally appears when the light is on or off, but with your method, it only appears when the light is off.

obtuse zephyr
#

{{ state_attr('light.office_light','rgb_color') | join(',\n') }}

#

Told you it was hacky

#

that'll fix it

spice jasper
#
stats:
  default: >
      {% if iif(state_attr('vacuum.alfred', 'error_text')) %}
      - attribute: error_text
      {% endif %}
``` seems to not show the card at all, but if i remove the template and the `>` it works, i'm not sure what's wrong with it?
remote saffron
plush willow
#

Is this the best way to count the number of lights that are powered on? (I have a Hue Smart Plug on which are 5 spots connected: light.spots_achtertuin):

template:

  • sensor:
    • name: "total_lights_on"
      state: >
      {% set lightcount1 = states.light | rejectattr('attributes.entity_id', 'defined') | rejectattr('object_id', 'match', '(spots_achtertuin)') | selectattr('state','eq','on') | list | count %}
      {% if (states('light.spots_achtertuin')) == "on" %}
      {% set lightcount2 = 5 %}
      {% else %}
      {% set lightcount2 = 0 %}
      {% endif %}
      {{ lightcount1 + lightcount2 }}
inner mesa
#

Your 'match' call has extra parens around the object_id

plush willow
#

oh that is a typo I think of me

inner mesa
#

And I don't know what you're doing with the first rejectattr

#

Rejecting light groups?

plush willow
#

I found that online....let me explaihn...exactly rejecting light groups. Maybe there is a better way?

inner mesa
#

It's fine

plush willow
#

okay ...the number of lights was first wrong. But I think there is a change not long ago that Hue rooms are now automatically enabled as an entity and that was not before I think....But anyway the count is now right (i have disabled that hue room entity)

fringe sail
obtuse zephyr
#

I can't say I know 100% either.... however, the comma would typically be used as a separator for R, G, B. Ideally, that's how you would've passed the string.... but I'm not sure how to do that with out magic converting it to a list automatically.

#

Presumably the color parsing logic was intelligent enough to grab the R G B values from prior... maybe there's independent logic to calculate the halo color? 🤷

plain magnetBOT
#

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

loud wave
#

@obtuse zephyr Can we split covers into their own files with the same include statement? If so is it cover or covers?

#

Good ol' ChatAI says we can

crystal idol
#

I'm not sure if it's my template or the generic camera entity but my still image isn't working anymore.
{{state_attr("sensor.killian_activity", "title_image")}}

When I tap submit, I get a n error that relative URLs are not supported..

ember gull
#

I'm trying to do a text to voice announcement for the weather, but I can't figure out how to get today's high, just today's temp. Any ideas to get the high?
It is currently {{state_attr('weather.home', 'temperature')}} degrees and {{states('weather.home')}} with a humidity of {{state_attr('weather.home', 'humidity')}} percent

silent seal
#

Which weather integration are you using?

ember gull
#

Just the standard one that comes with HAOS

#

I didn't even think about trying to get a new one

lofty mason
#

Go look in your developer tools at all the weather attributes, and see if you can pick out which number in the attributes is the days high. It may not be present if its already the evening, for example met.no looks like it only has it available for tomorrow, not for today.

ember gull
#

Yeah, that's what I'm seeing for this one too. Only available for tomorrow and the rest of the 7 day, but not today

lofty mason
#

I guess if you really wanted accurate high, you could get an hourly forecast and pick out the highest number between [now .. midnight], and create an entity for actual temperature from [midnight .. now], and pick the max of the two.

#

or just look for a weather integration that reports it for the whole day.

ember gull
#

Yeah, probably the later

#

thanks!

elfin pawn
elfin pawn
#

{{
expand(states.binary_sensor)
| selectattr('state', 'eq', 'off')
| map(attribute='entity_id')
| select('is_state_attr', 'device_class', 'door')
| map('device_attr', 'area_id')
| list
}}

plain magnetBOT
#

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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

silent seal
#

And you can't have both binary sensors for doors as well as temperatures in the same output, but you can use a similar process to get temperatures

crisp glen
#

Hi, I have problem with cover template and blinds:
There is no sensor showing status of blinds, but for some reason one of arrows is always greyed out.
https://paste.debian.net/hidden/adf4e1d7/ posting it here because it looks like more logical place to post question about template

silent seal
#

That is what tells it what the current state is to allow it to open or close 🙂

crisp glen
#

I don't have any sensor to provide such info and blinds are controlled using 433mhz commands

silent seal
crisp glen
#

@silent seal I have for now forced, position_template: "50" so now have all arrows active, but will try input helper later

violet flare
#

I'm trying to solve apparently a common problem - monitoring low battery levels. I was hoping to create a template that would create a binary_sensor for each battery below a static value. While I've found lots of threads and different approaches, it doesn't look like it's possible to define a template that can create multiple sensors automagically. I'm not missing something, am I?

inner mesa
#

No, you cannot create a bunch of sensors from a single template

violet flare
#

Curses. Copy and paste is probably the way then. Blech.

modest granite
#

Hello, I am trying to make a 'sensor:' with the 'history_stats' platform that uses 'weather.forecast' module to create a history graph card.
any one have a working template or a possible solution?

rose scroll
swift mortar
#

hey all - this template works fine but as soon as I added the entity which starts with a number 7 it falls over.
http://pastie.org/p/5CACYnfyHY3AC7uZW0wMSW
- platform: template sensors: lowest_entity: friendly_name: "Cheapest Unleaded Petrol" value_template: >- {% set entities = [ states.sensor.ampol_cambridge_park_p95, states.sensor.ampol_eastern_creek_eastbound_p95, states.sensor.ampol_foodary_werrington_p95, states.sensor.bp_werrington_p95, states.sensor.eg_ampol_kingswood_p95, states.sensor.7_eleven_kingswood_p95 ] %} {% set lowest_entity = entities | min(attribute="state") %} {{ lowest_entity.attributes.friendly_name }}: {{ lowest_entity.state }}

marble jackal
#

You could also use:
{% set entities = expand("sensor.ampol_cambridge_park_p95", "sensor.ampol_eastern_creek_eastbound_p95", "sensor.ampol_foodary_werrington_p95", "sensor.bp_werrington_p95", "sensor.eg_ampol_kingswood_p95", "sensor.7_eleven_kingswood_p95") %}

#

Or, when these are the only entities ending on _p95
{% set entities = states.sensor | selectattr('entity_id', 'search', '.*_p95$') | list %}

swift mortar
#

That's awesome {% set entities = states.sensor | selectattr('entity_id', 'search', '.*_p95$') | list %} - means if I add stations later I don't have to remember to modify the template! You sir are a champion.

plush willow
#

Does anybody know how I can add a - before every item:

{{ expand(states.cover.covers) |
selectattr('attributes.current_position', 'eq', 0) |
list |
map(attribute='name') |
join('\n') }}

floral blaze
#

Morning people, and merry Christmas! Can someone help me here with this code:

secondary: >-
  {% if is_state('media_player.receiver', 'playing') %} {{
  state_attr('media_player.receiver', 'media_artist') }} - {{
  state_attr('media_player.receiver', 'media_title') or
  states('media_player.receiver')}}

  {%- elif is_state('media_player.receiver', 'off') -%}
      off
    {%- else -%}

    {%- endif -%}

When my receiver is On it still displays 'Off' trying to fix this but im out of options. Someone here to help me out?

marble jackal
plush willow
marble jackal
#

You can add them to the names using a for loop (and a namespace)

marble jackal
floral blaze
#

Hi, thanks for replying. So what i want is to show information when (and only when) its playing music, else it should say 'On' when on and 'Off' when off.

#

And yes, when its playing music i can see what it's playing

plush willow
fossil venture
floral blaze
#

Hmm, that opens up a whole new can of problems

plush willow
#

Looks like this is the solution:

{% set covers = expand(states.cover.covers) | selectattr('attributes.current_position', 'eq', 0) | list | map(attribute='name') %}
{%- for coverName in covers -%}

  • {{ coverName }}
    {% endfor%}
floral blaze
# fossil venture Replace the `or` with an `{% elif %}`

fixed it like this:

{% if is_state('media_player.receiver', 'playing') %} {{ state_attr('media_player.receiver', 'media_artist') }} - {{ state_attr('media_player.receiver', 'media_title') or states('media_player.receiver')}}
{%- elif is_state('media_player.onkyo_receiver', 'off') -%}
    off
  {%- else -%}
    {{ states('media_player.onkyo_receiver') }}
  {%- endif -%}

Aside of this, i was wondering if its possible to show the same attributes from another entity in this very same card?

wraith token
plush willow
# marble jackal You can add them to the names using a for loop (and a namespace)

Okay this one works good in the UI (has a bullet for each item and each item is printed on a seperate line). If this is the correct way to do I don't know:

            {%- set covers = expand(states.cover.covers) | selectattr('attributes.current_position', 'eq', 0) | list | map(attribute='name') %}
            {%- set data = namespace(entities=[]) -%}
            {%- for state in covers -%}
            {%- set data.entities = data.entities + ['- ' + state] -%}
            {%- endfor -%}
            {{ data.entities | join("\n") }}
marble jackal
#

Looks fine, the only thing is that you can expand the group directly, so expand("cover.covers")

plush willow
#

okay

marble jackal
#

Oh, and you don't need the | list filter in the first line

ivory lotus
#

Hi, i am quite new to template sensors and I am trying to get on binary sensor 'Misch.HK1' which should be ON, when 'Misch.HK1_auf' = 1 (normally it is 0) and OFF when 'Misch.HK1_zu' = 1 (normally it is 0)... how must the template sensor look like?

#

template:

  • binary_sensor:
    • name: "Misch_HK1"
      unique_id: Misch_HK1
      state: >
      {% if states('sensor.node_1_output_3') | float) >= 0.5 %} # Misch.Hk1_auf
      {{ ON }}
      {% endif %}
      {% if states('sensor.node_1_output_4') | float) >= 0.5 %} # Misch.Hk1_zu
      {{ OFF }}
      {% endif %}
#

i tried it like this, but there must be something wrong... 😦

marble jackal
#

Can they be both on or off?

ivory lotus
#

get the following error: ValueError: Template error: float got invalid input 'sensor.node_1_output_3' when rendering template 'template:

#

both can be off, but only one can be on

marble jackal
#

So if both are off, what should be the state of this binary sensor

ivory lotus
#

it should keep the state it had before... I have a Mixing valve in my heating system and there this valve get controlled by a short impuls... then it stays open/clodes, until it recieves another implus

#

so if sensor.node_1_output_3 gets 1 the valve opens and stays open until sensor.node_1_output_4 gets 1...

#

in the meantime both will be 0

marble jackal
#
{% set o3, o4 = is_state('sensor.node_1_output_3', '1'), is_state('sensor.node_1_output_4', '1') %}
{% if o3 and o4 %}
  {{ this.state | bool }}
{% else %}
  {{ o3 }}
{% endif %}
ivory lotus
#

thank you!

#

this script keeps the state if both sensors have the same value and set it to ON if o3 is true

#

is this correct?

#

but there is missing to set it to false if o4 is true, or am i wrong?

marble jackal
#

If o4 is true o3 will either be also true (which will hold the state) or o3 will be false, which will make the binary sensor turn off

ivory lotus
#

o4 + o3 false --> keep previous state
o4 + o3 true --> keep previous state ( this will never happen)
o4 true, o3 false --> state should be false
o4 false, o3 true --> state should be true

#

{% set o3, o4 = is_state('sensor.node_1_output_3', '1'), is_state('sensor.node_1_output_4', '1') %}
{% if o3 and o4 %}
{{ this.state | bool }}
{% else %}
{% if o3 %}
{{on}}
{% endif %}
{% if o4 %}
{{off}}
{% endif %}
{% endif %}

#

I think it should be like this? what do you say?

glossy mica
#

Can someone help me understand why this: value_json.Heatmaster.status | regex_replace('/s','') doesn't work when creating my entity name, but works in the developers tools?

#

I'm trying to create a friendly name for the state being passed.

marble jackal
#

This covers all cases:

{% set o3, o4 = is_state('sensor.node_1_output_3', '1'), is_state('sensor.node_1_output_4', '1') %}
{{ this.state | bool if o3 == o4 else o3 }}
#

And the binary_sensor expects true or false as result of the template

marble jackal
spice current
#

How do i update a entity's state without triggering it's associated actions?

silent seal
#

You mean without running automations? What are you trying to do?

spice current
#

I'm trying to have a dropdown for my PC status like

- On
- Hibernate
- Shutdown
- Restart
- Sleep
- Lock
- Logout

and i want my pc to be able to send a "status update" to HASS when one of these actions is being run on the PC itself and also send the status "On" when a restart is finished for example (i can detect and handle that on the PC side)
but i don't want the necessary automations for "Restart" for example to be run by HASS when i do that from outside of HASS

silent seal
#

Sounds like you need to check the trigger variables, and/or use events or similar to update the state from one side rather than the same thing.

#

That said, I'd split actions and state myself, call an action from HA, let the PC always report the state and never assume it.

floral steeple
#

hi all, im trying to tie in HOW a switch was turned on as a trigger, for example, triggered on by voice (google assistant/nabu casa) or service call.

#

When the swtich turns on/off via an automation service, the log book entry is as follows:

  • shellyplus1 switch_0 turned on triggered by service switch.turn_on
    But when the switch is turns on/off via voice assistant, the log book entry is as follows:
  • shellyplus1 switch_0 turned on triggered by Google Assistant sent command OnOff
#

would adding a condition like this, work?

#
  • condition: template
    value_template: |
    {{ trigger.to_state.context.context_id == 'service.turn_on' }}
#

and

#
  • condition: template
    value_template: |
    {{ trigger.to_state.context.context_id == 'Google Assistant' }}
teal umbra
#

Maybe a stupid question, but is it possible to make a template sensor that gets its info from a input.number in lovelace?

- platform: template sensors: energy_cost_dal_eur: friendly_name: 'Kosten Dal tarief' value_template: "{{ states.sensor.input_number.dal }}" < input from lovelace? unit_of_measurement: "€"

marble jackal
#

Yes, value_template: "{{ states('input_number.dal') }}"

#

But if this is for the Energy dashboard, you can use an input number directly

#

You do need something like €/kWh as unit of measurement

teal umbra
#

Thx @marble jackal

violet flare
#

There isn't a built in function to convert between C/F in templates, is there? It's a simple formula, just typing it in again and again (silly US standards) introduces probability of errors/fat fingering something somewhere.

silent vector
#

How would I convert the output of this to a string?

{% set user_id = '8797dae84d8b4a8fad34d3e60dc00269' %}
{% set user_match = { '06b48a1c8bcb46b6870291459d022ba2': 'test1',
        '8797dae84d8b4a8fad34d3e60dc00269': 'test2' } %} {{
        user_match.items()|selectattr('0', 'in',
        user_id)|map(attribute='1') | list }}
[
  "test1"
]
#

Got it using join(',')

marble jackal
#

If you know there can be only one item, you can just just | join

silent seal
#

| first also works for just one item 😛

marble jackal
#

Yes, but it will error when there are no items, join won't

inner mesa
#

That is a good insight

#

Seems like first should take a default

sonic sand
#

hi everyone,
I'm trying to set up a sensor for my Sensibo - Power Consumption, I managed to successfully make a sensor for the humidity, but for some reason the power consumption showing me N/A output instead of numbers.

Here is the code:

template:

  • sensor:
    • name: Sensibo_Humidity
      state: "{{ state_attr('climate.ofir_a_c', 'current_humidity') }}"
      unit_of_measurement: '%'
      icon: mdi:water-percent
  • sensor:
    • name: Sensibo_Power_Consumption
      state: "{{ state_attr('climate.ofir_a_c', 'current_voltage') }}"
      unit_of_measurement: 'W'
      icon: mdi:power-plug
inner mesa
#

Hard to tell without formatting

sonic sand
#

formatting what?

plain magnetBOT
#

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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

inner mesa
#

Your code

sonic sand
#
template:
   - sensor:
      - name: Sensibo_Humidity
        state: "{{ state_attr('climate.ofir_a_c', 'current_humidity') }}"
        unit_of_measurement: '%'
        icon: mdi:water-percent
   - sensor:
      - name: Sensibo_Power_Consumption
        state: "{{ state_attr('climate.ofir_a_c', 'current_voltage') }}"
        unit_of_measurement: 'W'
        icon: mdi:power-plug
#

There you go

#

I have also tried to change

'current_voltage'

to

'current_power'

and it is still showing me NaN next to the icon.

inner mesa
#

Where are you looking?

sonic sand
#

On the dashboard after restarting the whole HA

#

I have used this sensor in some card I have

inner mesa
#

What does it say in devtools -> States ?

sonic sand
#

which one the climate.ofir_a_c or something else?

inner mesa
#

That

#

And the new sensors that you're trying to create

sonic sand
#

hvac_modes: cool, heat, fan_only, dry, heat_cool, off
min_temp: 16
max_temp: 32
target_temp_step: 1
fan_modes: quiet, low, medium, high, auto, strong
swing_modes: stopped, rangeFull
current_temperature: 22.1
temperature: 20
current_humidity: 72.8
fan_mode: high
swing_mode: stopped
icon: mdi:air-conditioner
friendly_name: AC
supported_features: 41

#

and the sensor:

unit_of_measurement: W
icon: mdi:power-plug
friendly_name: Sensibo_Power_Consumption

inner mesa
#

Is there a current_power or current_voltage attribute there?

sonic sand
inner mesa
#

Well...

#

It's describing some other sensor

#

That is not a sensor

sonic sand
#

mmm.. okay

keen pollen
#

Hi people,
I am trying to set up a sensor that records the duration of a value of a battery sensor. For example, if a battery is at 50% at 12:00 and at 13:00 the battery is at 60%, I want the sensor to say "1" (duration in hours). I have searched both the internet and the community page but can't find a working solution. I'm either getting N/A or something that is wildly different from what I am trying to achieve.

Thanks in advance.

silent seal
#

What is the purpose of this?

#

Because the battery will likely register at 51%, 52%, etc.

keen pollen
#

You are right, it will register changes between 50% and 60% but I am trying to get the duration between each of those changes. The purpose of this is to use it to calculate the average charging speed.

silent seal
#

Is there a particular reason you want to do this by 10s?

#

I would detect when the device goes on charge, log the time to an input datetime, and log the starting % to an input number, and then when it comes off charge log that data wherever you want it to go

lofty mason
keen pollen
# silent seal Is there a particular reason you want to do this by 10s?

Apologies, I made it unclear, sorry about that. The percentages are examples. I'm just trying to get the duration between when the battery changes from a certain percentage, to the next percentage. Yesterday, the battery charged from 54% to 58% in 14 minutes. The sensor then needs to say 0,233.

keen pollen
silent seal
#

Well you can use templates to output the current rate of charging as well

keen pollen
#

That is the idea, I have already made a template to calculate the difference in percentage (and kWh) between each jump, I only need the time between those jumps to calculate charge speed

fickle kettle
#

Seems like you need automation (triggers) not sensor, and maybe saving the last/previous value somewhere...

#

If you have both the datetime, you can just subtract one from the other, then divide to get it into whatever unit you want.

silent vector
#

Does anyone know how to compare 2 lists? rgb_color is a list. This is resulting as true all the time even when rgb_color is not equal to color
https://dpaste.org/qJ5v2

#

That's how one of the lights looks right now when using

{{ states.light | selectattr('entity_id', 'in', area_entities(area)) | list }}

https://dpaste.org/25LSq

marble jackal
silent vector
#

That was too easy whoops lol. Thank you.

#

Although it still shows as true even when I made them integers for color. It should be false right now.

marble jackal
#

Try to debug it first by actually selecting and not rejecting the lights with that color selecting, and list them instead of count

#

Then when that works, apply the logic you need

#

Looking at your second link it seems rgb_color is a tuple, not a list

silent vector
#

This shows undefined for all 4 lights. Weird.

{{ states.light | selectattr('entity_id', 'in', area_entities(area)) |
selectattr('attributes.rgb_color') | map(attribute='rbg_color') | list }}
#

[Undefined, Undefined, Undefined, Undefined]

#

If I mapped entity I got all 4 lights.

marble jackal
#

You need attributes.rgb_color

silent vector
#

Like this?
map(attributes.rbg_color)

marble jackal
#

No, map(attribute='attributes.rgb_color')

silent vector
#

1 step ahead lol. But still undefined.
map(attribute='attributes.rbg_color')

sonic nimbus
#

how to substract two dates? {{states('sensor.frontdoor_last_open_time') - states('input_datetime.resident_last_time_entered_home_zone')}}

marble jackal
silent vector
#

🤦‍♂️
[(255, 136, 13), (255, 136, 13), (255, 136, 13), (255, 136, 13)]

marble jackal
#

So, these are tuples (I already mentioned that above)

#

Your color variable is a list

silent vector
#

How would I make this work? I haven't worked with tuples before.

marble jackal
#

Just use ( and ) instead of [ and ] when defining your color variable

#
{{ ( 1, 2 ) == [ 1, 2 ] }} # False
{{ ( 1, 2 ) == ( 1, 2 ) }} # True
sonic nimbus
# marble jackal Convert them to a datetime using `as_datetime`
{{as_datetime(states.binary_sensor.front_door.last_changed | string)}}
{{as_datetime(states('input_datetime.resident_last_time_entered_home_zone'))}}

{{as_datetime(states.binary_sensor.front_door.last_changed | string) - as_datetime(states('input_datetime.resident_last_time_entered_home_zone'))}}

I have an error: TypeError: can't subtract offset-naive and offset-aware datetimes

mighty ledge
silent vector
#

It's true when the lights are not (255, 43, 0) and false when they are.

mighty ledge
#

you're rejecting it

silent vector
#

Completely forgot the way I setup the Automation that uses this. Before I only looked at color temperature now I will look at color too. I just checked and it's working as designed lol 🤦‍♂️

#

This is for when ZigBee light groups don't transition correctly which happens often.

ember cloud
#

Hi, can someone please correct me here:

#

{%- for item in expand('binary_sensor.door_window_open') -%} {%- if item.state == 'off' and now().second - as_local(states.item.last_changed).second <= '3' -%} {{ item.name }} is closed. {%- endif -%} {%- endfor -%}

#

Trying to figure out which sensor just closed, and print its name. Otherwise I'll get a long list of all the closed sensors. Thanks.

#

There is obviously something wrong with as_local(states.item.last_changed).second I just don't know who to get it to work in the loop and check each sensor's last changed time. Or maybe there is a better approach than this. Thanks.

arctic sorrel
#

Something like this @granite granite:

{{ expand('group.flood_sensors') | selectattr('state', 'eq', 'on')|map(attribute='name')|list|join(', ') }}
granite granite
granite granite
marble jackal
earnest cosmos
#

I have a question about identifying the number of people at home, or in the zone.home.
I thought I would use {{ states('zone.home')|int == 0 }} to determine this, but then I realized my youngest daughter rarely brings her mobile when leaving the house, so the state for zone.home would not always be set to "0". Any suggestions how to work this out?

silent seal
#

How else might you track your daughter?

#

Because you can have multiple device trackers per person

#

Or if she's rarely at home alone, you can check if she's the only one home and assume she's not there

earnest cosmos
#

I do not track her otherwise

#

She is home alone at times

silent seal
#

You might want to consider something, even if it's a proxy through a calendar. Otherwise this will be quite tricky I think

earnest cosmos
#

So I realize too

#

Thing is I control ingterior lighting.

#

meaning I will only turn on light when the first person enters the house

#

and the setup is by turning the dimmable spots on at 40% to make sure they all are lit, then dim them to 5%. I do this by a script, and it works fine...

#

Except when this "someone coming home" script triggers even if somone is at home already

silent seal
earnest cosmos
#

We all have iPhones

#

I get your point of device usage. Se uses her iPad a lot, which never leaves the house, and her iPhone she only brings occationally and when at school.

silent seal
#

Well, if she uses her iPad a lot, then installing the app on there would make sense too.

earnest cosmos
#

Slo now in the holidays both her iPhone and her iPad are left at home even if she comes with us down town

silent seal
#

Any chance you can teach her to take her phone with her? 😂

earnest cosmos
earnest cosmos
silent seal
silent seal
# earnest cosmos I know! She´s only 10 still

Well, that's a good age to start taking a phone with her if she has one, so if she does need to get in touch with you she can. And you could encourage it with a theme song playing on a smart speaker when she comes home 😛

earnest cosmos
silent seal
#

Hmmm, I think I would work around it for now with a "when you leave, if she's the only person detected at home send a push notification to ask if she's there or not" and then use that to set a proxy device tracker for her

#

It also conveniently avoids accidentally re-enacting Home Alone 😛

earnest cosmos
silent seal
#

Well, I would probably create an MQTT device tracker for her, and set that to "away" when you tap the notification (actionable notification), and then set it back to home if it is away when you return home.