#templates-archived
1 messages · Page 21 of 1
Yes, it can do both
You can do both
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 %}
}
You can't use Jinja code in most cards.
Ah alright, are there any other routes I can check to archieve on a different method?
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
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.
@hidden crag I converted your message into a file since it's above 15 lines :+1:
this channel is for Jinja templates
oh sorry
that is a #frontend-archived topic
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
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.
You can create a template sensor for that
yep it went over my head, I can do the timed ones using strptime, but stuck on this
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
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.
{{ '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
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'] }}
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
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 🙂
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
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
nope, you need to redefine it.
You can put it in an atttriubute itself and refer to the attribute
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
use trigger variables, but keep in mind the template will only update based on your trigger
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
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
no, you have to use trigger variables
trigger:
- platform: ...
variables:
gaming_temp: "{{ state_attr('climate.gaming_thermostat_thermostat', 'current_temperature') }}"
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
yes it would
not on the first
don't put them all with the same trigger
or any of the others I omitted
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
- trigger:
- platform: state
sensor:
- name: bla
- sensor:
- name: foo
that's also valid
the trigger in this case will only affect sensor bla
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
right
actually that won't help, it's all a big list anyway
you can also do this via an automation that creates an event
it doesn't even has to be a different file, but with that include it would make sense to have in a separate one
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
I mean, yes, that's also an option. but then I'd be using automation -> template -> automation which feels a bit redundant
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?
Given the list nature of the sensors in the template section, would it be fair to say that a trigger type sensor woul affect all subsequent sensor entities you define? or can it be reset?
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?
{{ is_state('binary_sensor.abc', 'on') or (is_state('calendar.abc','on') and is_state_attr('calendar.abc', 'message', 'ABC')) }}
it's a list so adding a second key shouldn't be a problem
Perfect, thank you
ah I now see that that is what @marble jackal is referring to
so yes, that would work then
perfect
the sensor keys are different templates all together and do not impact each other]
yes exactly
if you attach a trigger to a sensor section, then that whole sensor section will update via the trigger.
so I could simply make a new file, add a new sensor list item and have the trigger affect only that
yes
perfect
you could define multiple sensors which use the same trigger as well
include_dir_merge_list
yes that
yes that is the plan indeed
not the named one.
- trigger:
- platform: state
sensor:
- name: sensor 1
- name: sensor 2
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...
yep
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 🙂
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)
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
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?
"{{ [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
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
okay. so sanity check: https://pastebin.com/NhrfE5LM this should work then
and any subsequent sensor can make use of the same base set of data
Hmmm, it should never get negative, so for example it starts at 11.400, it should never go lower than this value, only increasing
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
Nope, there is always only one trigger, so not all variables will be available
ah, that kinda makes this approach worthless :/
no, you can use yaml anchors
but your triggers are also incorrect, there is no platfom: sensor trigger
one moment
well that config is wildy incorrect
then it's good that I haven't enabled it yet
you aren't using triggers
but this is what i get when I take the previous advice into account
you made up triggers
you need to use triggers that you'd use in an automation
like state triggers
@thorny snow try this: http://pastie.org/p/3z5I0q43SVVbT9Rh7yLQrL
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
yeah okay but then we're back to the thing I said about adding template triggers to a template
no, look at what the fes posted
I'm reading the other message
do you know your net import/export?
what the fes posted should just be a straight copy/paste
because that makes things a lot simpler
An error occurred during a connection to pastie.org.
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"
okay wow. no that was not clear at all
I even asked about adding things like climate entities to a climate key and numbers to a number key
🤷♂️
it's a state trigger
you've made automations right?
all triggers are the same, everywhere
never in templates
Still, thank you for the assistance
so now with all this I can add the attributes I wanted
Yes, using the variables
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?
you can create a generic thermostat and #integrations-archived can help you with that
I see! From its documentation I thought that was an active element. In this case HA shouldn't turn on or off a heater, for example.
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.
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(.
just tie it to a fake heater, i.e. input boolean.
remove the first -sensor:, thefes must have had a typo
whoops, that was wrong indeed
but don't I need that sensor list key to isolate the trigger items?
This might be able to do something for you: https://www.home-assistant.io/integrations/climate.mqtt/
Allow you to create a climate entity from a bunch of input data (and no fake booleans or fake heating states)
or can that be used instead of the sensor key
like, it's a type, like sensor is a type
- trigger:
sensor:
the dash indicates the item
okay yeah it's a type
so just remove the first - sensor: line and it'll work
you can use any type of template entity in combination with the trigger
template:
- trigger:
sensor:
number:
text:
binary_sensor:
- sensor:
- number:
yeah that's what I mean, the -trigger is just another type like -sensor
it replaces it
forget it
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
the WORD trigger replaces the WORD sensor since this is a TYPE trigger and not a TYPE sensor
nope
whatever
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.
The point is: Take the time to understand the YAML. It will help you learn yaml everywhere, not just in this template.
I'm not sure how this is going to work. I need to sync the min_temp and max_temp to the number entities, so they are written to the heating/cooling appliance.
that's just automations
I think I pissed them off 🤷♂️
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?
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
I think I should be able to manage. I'll let you know. Thanks
What is your suggestion for my problem? I do have that information available 🙂
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?
{{ states.alarm_control_panel|map(attribute='entity_id')|list }}
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'}]
there's nothing wrong with that if you always want the value from the first element in the. list
which is the most current time/value
yeah, the array appears to be ordered properly for me to grab "today" as the 0th indexed item. thanks, y'all.
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.
| length
i thought I tried that. I'll check again.
there's also | count
🤦 I thought my mistake was in length turns out I forgot to do |list first i had map only.
I've used Dual Mode Generic Thermostat (https://github.com/zacs/ha-dualmodegeneric) and it works now. thanks!
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
when do you want it to be true, on a specific value, or on any value?
Basically any value is True and no value or when the attribute doesn't exist False.
{{ state_attr('sensor.your_sensor', 'your_attribute') is not none }}
Oh awesome thanks! And I can basically turn that into template sensor if i'm correct
I would use a binary sensor here, which will then be on or off
Thanks for the pointers! Checking if it works in a second!
Yes! Works perfectly! Thanks a lot
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
You've been using very old tutorials here. state_class should betotal_increasing and last_reset is not needed
And for further questions #energy-archived can help you better
Template Value in CFG for Integration Working? i mean this: https://imgur.com/a/SiopiKQ
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?
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 ")
yah... sorry. of course without "s. copied the wrong example due to all the debugging i did... i upated the question.
That means your output is not json and something is blocking the value from converting to JSON. If your result is
{'Time': '2022-12-20T08:21:23', 'SR04': {'Distance': 78.509}}, then that's not JSON. JSON has a strict double quote requirement for all strings, your output is single quote.
@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.
no, you can only template where the docs say you can tempalte. I doubt that allows you to use a template there. Also, that seems like a custom integration and you should ask your question in the custom integrations issue page.
what about {{( value | to_json | from_json ).SR04.Distance }} 🙂
seems to work in devtools > templates
just checked that for the enabled setting on triggers and conditions. Would be nice if you could template those, you can then actually disable a trigger based on an input_boolean. Unfortunately the docs don't mention template support there
That won't work, value needs to start as a string, i.e.
{% set value = "{'Time': '2022-12-20T08:21:23', 'SR04': {'Distance': 78.509}}" %}
ah okay
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
It would be nice for templates in alot of those places, however there's no simple "Template this config option" built in functionality to home assistant
A whole mechanism would have to be built to house and store templated configuration options that could work on all integrations.
{{ now().stftime('%d-%m-%Y %H:%M:%S') }}
Thanks a lot. I tried like this {{ now().strftime(%d-%m-%Y %H:%M:%S) }}, that's why it didn't work . Thanks for your help!
I will try that later. Thx so far. Will also have to check where the single quotes come from. The json comes from a tasmota devices invoking a webhook on my home assistant instance. I simply forward that json to mqtt via a publish with payload: "{{ trigger.json }}"...
change your payload to "{{ trigger.json | to_json }}"
then value_json will work
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?
what's the problem, that looks like it should work
the template's a little verbose, but it'll work
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(', ') }}
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!
I have a markdown card for NWS alert(s)
it shows the first, but will not handle more than one
You'll have to elaborate
{{ 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.
I'm still not seeing what the problem is
you have 1 entity, with 2 attributes. Each attribute only has 1 info
the value of the sensor is # Alerts... attributes for each alert
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
ie, NWS_Alerts = 1 right now.
ok, let me read more, sorry
@pine musk are you using REST? Did you copy this thread? https://community.home-assistant.io/t/severe-weather-alerts-from-the-us-national-weather-service/71853?
no, using HACS/NWS Alerts
you have a link?
@odd maple is NWS something that finity forked?
the alerts? no
Who created the code???
there was a requirement to make sure YAML config still worked for it too 😛
Yeah I get it. I keep both on mine too
is it broken?
No, just reading the code, trying to help jazz
no, Im just trying to use it
It seems to just have the last alert
it collects them all into attributes
It doesn’t look like he’s keeping them a list
aand how do you iterate through?
It would be like any other listed attribute
Post the dev tool -> stages page showing the attributes
index 0 will be the "latest" alert
In which attr
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] }}"
🤮
it works
ok, so how do I iterate through?
for each on state_attr('sensor.nws_alerts', 'title').split(' - ')
Like with what first posted
ok, lemme try it.
I only care about the latest alert
It’s probably easier to use REST
it is using a rest call 😛
Lol I figured
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?
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) }}"
Thanks - I thought I had tried that.
thanks!
firstof9: I am trying to use the restapi package?
Are templates the only way to calculate how much time my heater has been on? I'm using a Nest thermostat.
Oh awesome. I did a bunch of searching and somehow missed that.
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?
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)
Thanks
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
Is it actually a sensor or is it a binary sensor?
sensor
sensor.weatheralerts_1_alert_2
nevermind, I'm an idiot
lovelace doesn't hide things when you're editing
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 }}
That could be simpler 🙂
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)
sorry - had to go deal with a baby
yes, it could
it also doesn't work
it returns []
{% 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
Ahhh so we get an array of dates, then only let through records in that array
yeah, no kidding
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
....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?
just keep adding selectattr() to the last line
🙂
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
%}
yes
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
although selectattr('condition', 'in', ('cloudy')) probably isn't what you want
that's the same as 'eq'
wait what
ok
so, selectattr('condition', 'in', ('cloudy')) is the same as condition == ['cloudy']?
if it's just those exact words, then it's okay
well i want to know if we're expecting any one of conditions over the next 24 hours
if it's "partly cloudy" and "mostly cloudy" and "cloudy with a chance of meatballs", then you want to use a regex_search()
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
well, in any case, you have the technology
sure
just wanted a sanity check that what I'm suggesting roughly makes sense
precipitation > 0?
in theory that should be the same as "rain", I would think
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
they come from the provider
you can just go see on the website?
whatever you're using
Also, did you say I needed regex_search?
looking at this: https://developers.home-assistant.io/docs/core/entity/weather/#recommended-values-for-state-and-condition there's alot of different types of rain and snow
ok
{{ forecast|selectattr('datetime', 'gt', curtime)|selectattr('condition', 'search', 'sunny|cloudy')|list }}
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".
You can define them as trigger variables on a trigger based template sensor, or in an attribute
And refer to the attribute
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.
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
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?
Yes
You can list the batteries below 10% in an attribute
And then compare the from_state and to_state of that attribute
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...
Where is this? Is this the auto-entities card? I'm trying to generate an automation that will send me a message, but this is nice for displaying the status, thanks.
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
This is a beautiful idea. I never thought about autocreating groups at startup!
everyone that's cool is doing it
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'}}
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...
no, its even sillier. If I leave that condition in, the trace indicates the first condition is not true...
you don't have the conditions in the correct order @floral shuttle
your second condition should be first
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
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
yes, there's an ancient FR for that iirc (use that as template trigger), but it was rejected
well, keep in mind that it won't be checked if another condition fails first
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.
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?
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'}}
ah, well you have 4 }}}} at the end, that's why
Brace yourself
let me check that 😉
# {% set x = ['unavailable','unknown'] %}
# {{trigger.to_state.state not in x and trigger.from_state.state not in x}}}}
^^
yep, that was it... grrr so sorry
for reference....
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
it won't choke on that
{{ }} is the template }} is extra characters you added that's considered a string
btw, you need the is_number test in there too: {% set threshold = states('input_number.battery_alert_level')|float(0) %} {% for s in expand('group.battery_sensors_auto') if s.state|is_number and s.state|float(0) < threshold %} {{s.entity_id}} {%- endfor %} to filter out unavailables
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
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...
that's not necessarily true
what if I was creating a dictionary
}} is an escaped }
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
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..
you spotted it didnt you?
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 }}
does your language not have a word for lopsided?
sure, I just hadnt heard of that before.
crooked, off-balance, askew. languages are a beautiful thing.
on the language aspect, and since we were talking conditions: the phrase valid in the docs https://www.home-assistant.io/docs/scripts/conditions/#and-condition should really be True and not valid https://www.home-assistant.io/docs/scripts/conditions/#not-condition would need to be replaced by NOT true
all conditions are valid, but they need to be evaluated.. to true
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?
Could be a copy paste error, but you are missing }" at the end
And your template sensor exists and works?
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.
did you include the new sensor in your recorder settings (or at least didnt exclude it by some filter)
it looks like it's already in history. Are you sure the state is heating
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.
then it should be working
Hmh. Peculiar.
https://imgur.com/a/CGZSBEZ
the only other option is that you have 2 sensor sections
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.
^
Balls.
And the entity_id doesn't have a _2 added by any chance?
The "sensor.hvac_action" one?
Yep
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
If you don't have recorder:, you have no history
it would need some time before that (statistics) would come up
I just started "recorder" today but the entity was created yesterday.
If you wouldn't already had recorder, you would not be able to see the graph with the state changes
recorder is in default_config so you shouldn't need it unless you removed default_config
This one
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
Right.
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.
Did you remove default_config:?
why doesn't that make sense?
it's saying ~6 of the 9 hours, heating was on
Ya, that's a lot...I think. Maybe it's not with these temps, haha. I should check the other entity.
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
~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.
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
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?
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
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```
then recorder was enabled
oddly enough, recorder: isnt listed on https://www.home-assistant.io/integrations/default_config/
hmmm
Interesting because to get it to work, I added this at the bottom
include:
entity_globs:
- sensor.hvac_action```
history is, so it might be a secondary dependency?
yes it does: https://www.home-assistant.io/integrations/history/
It depends on the recorder integration for storing the data and uses the same database setting.
It seems like maybe the recorder integration isn't there by default anymore?
I believe it is impossible not to use recorder so that's why it is not in default_config
no, its loaded as dependency for history, so it should be there if you have default_config: in your configuration.yaml
if you dont use default_config (as do I) you need to add recorder: if you want to record anything
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.
I think that's changed in one of the recent releases, I kinda remember something like that. Not sure though
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:
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.
just to be sure: you did restart after adding that configuration change?
Yup. That's when the number showed up.
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
Another side note/question. I can't add this to the energy dashboard right? Seems like you can only add certain entities.
you can add any energy sensor. this is a time sensor. how would you add that?
I'd add another step to do some math.
btw, we should really try and keep this talk on topic 😉
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```
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.
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.
you put inclusions
that means you're only recording what you included 😉
you can simply just have recorder: and it'll do all entities.
Oh ok. Thanks
Hi. Can cards take templates?
depends on the ard
I'm trying to configure a card: https://paste.debian.net/plain/1264870 it works in templates however I get error when doing it inside the card
you'll get more help on that in #frontend-archived
Thank you
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.
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.
and yes, you should output a list, rather than trying to create the YAML for it
You also don't need a for loop here
{{ 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 🙂
Basically adding | list to the selection for the for loop would work
He's already using the new stuff
Thank you both
I could get used to this:
{{ area_entities('office')|select('match', 'light')|select('is_state', 'on')|list }}
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 }}
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 }}
The old line of filters still works 🙂
you just look like a 🦎
Question is there an easy way to remove one light entity from the list?
How can I condition if media player volume is increasing or decreasing? is it possible to get last volume and compare to current ?
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
you want to have a box to enter messages, but you don't want to edit the message every time?
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
ah, okay
Two cards. An input text and a button that makes the call?
How do i do that ? 😮
do you have the service call to send the message in a tap_action of the button now?
Yes: Notifications: Send a notification with lg_webos_smart_tv
you can´t use templates in a tap action
Yes in an automation, Scenario is TV volume increases --> Increase LED brightness and vice versa.
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"
and this i put in to scripts.yaml ?
what is the actual code of the trigger
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?
Id like to type messages.
Ok, did you make the script already?
Nope
Start by doing that 🙂
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
Then in a dashboard you want two cards:
https://www.home-assistant.io/dashboards/entity/
https://www.home-assistant.io/dashboards/button/
The entity will be for the text, and the button calls the script
and for button entity, is that TV ?
No, the script which sends the message using the template.
To make this hard as possible, what sequence should i use
The script just needs the action to send a message, with the message as TheFes showed earlier. #templates-archived message
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.
Set the attribute or refer to it?
Below does not work.
The attribute is empty when refer to it.
- binary_sensor:
-
name: "my sensor"
state: >
{% set test = some value %}
.....attributes:
value: "{{ test}}
-
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
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
In a nutshell, no. Use things like is_state('binary_sensor.my_sensor_here', 'on') to output booleans
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.
Well usually for that you would use | selectattr('state', 'eq', 'on') | list | count or similar
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 %}
Did you check the pins? There are links to various useful resources on using Jinja there
Ive been reading the HA templates page, but havent looked a jinja specific resources. Ill check those out though
Thanks. I will try your way.
@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}}
-
How can I tell if a dict has a given key?
{{ 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
Thanks!
No, like this
- binary_sensor:
- name: Test
state: "{{ state_attr(this.entity_id, `atrr_1') > state_attr(this.entity_id, `atrr_2') }}"
attributes:
attr_1: >
{% some highly advanced jinja templates %}
{{ result }}
attr_2: >
{% some highly advanced jinja templates %}
{{ result }}
I see. Thanks so much. I will try asap.
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"?
"if from state closed to state open then opening" - how will you know when it should change from "opening" to "open"?
The actual state is already open.
So unless the ESP reports the transitioning states (which I assume it doesn't), I think you need something more in your condition. Like a door/window magnetic sensor that defines if it is open or not open.
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.
Sure, then create an attribute which lists those sensors
And for the state template you can check if the attribute has any entities listed
The problem is the state_attr read only? I cannot set state_attr to the sensor name in the state section.
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"
-
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
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"
that idea suits me well. thank You for Your kind reply. now to figure out how to adapt it to my needs: i am thinking of having one button and the icon/color icon changing based on the state: green gate open, yellow opening or closing, red closed.
To just change the icon, you can set that based on state in the template like this:
icon: "{{ 'mdi:alert-box-outline' if states('sensor.current_version') != states('sensor.latest_available_version') else 'mdi:checkbox-marked-outline' }}"
For changing colors, I'm not sure, but I think you need to use https://github.com/thomasloven/lovelace-card-mod
No, you are still missing my point, if you don't want to redo calculations in your config, the calculation has to be done in the the attribute
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
Thank You. Will give that a try.
this is how I solved all of those issues... albeit using custom-ui and you can leave that out ofc. but the main problem was telling HA about the opening/closing of the Ikea cover
Thank You also for the input. will test both scenarios when i will get to that point 🙂
@mortal talon I converted your message into a file since it's above 15 lines :+1:
Did you try wrapping the value in quotes? value: "{{ states('input_number.sleep_timer_bedroom_minutes') | int + 5 }}"
yep, I've tried that too. also casting to float, though that shouldn't make a difference because yaml is between input and output anyway. I've also tried appending .0 (i.e. value becomes "20.0" to force float, but that didn't work either
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? 🤔
you can't template in the frontend
you have to make a script and use that in the frontend
ah. well that explains it then 🙂 I'll do some more research on that, thanks!
so make an increment script and a decrement script and call those instead
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 %}
How about {{ expand('group.esphome_trackers') | map(attribute='entity_id') | select('is_state', 'office') | list | length }}
Thanks! Never would have thought of that, still very new with these ||still, imo there should be an integration for ESPresense that solves this||
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.
@hazy surge I converted your message into a file since it's above 15 lines :+1:
Did you check your log?
Nothing special, unless this that happens when I reload the Template entities :
Request for https://homegraph.googleapis.com/v1/devices:reportStateAndNotification failed: 404
Seems odd, that section works for me without issue. That's just straight in your configuration.yaml?
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
Maybe Ctrl+F5, hard refresh
Glad to hear!
Not directly, but it depends on where it's coming from
I am trying to get this api into my HA: https://www.thethingsindustries.com/docs/reference/api/storage_integration/
using REST, but the output is a JSONL rather than a JSON array
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.
alternative I can get MQTT but I just thought i would give a try to REST 🙂
If REST isn't returning JSON or XML I would skip it and try MQTT
ok cool 🙂 that was my failback but it sounds like I have to do so
Sorry, I got your point, I will try again. Thanks again.
I have other sensors. Using a group, I can only have an on-off event in automation,I want to identify the exact sensor. So do I have to do it in a template or there is other way?
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 }}"
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
Is it clear when one should be read versus the other? Should be pretty easy to come up w/ an expression, if so
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)
{{ [ '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?
🪄 thank you this is great. I suppose they could, if that computer is off
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
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
Sorry, that was incorrect, now it should work
It avoids the error from first which can't be applied to an empty list
Worked perfectly, thanks again @marble jackal
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?
I think this should work
value_template: '{{ value_json.sysuptime["@value"] }}'
Thanks. That parses ok but the entity shows this attribute after a restart:
Sysuptime '@value': '261049'
What's the yaml for the rest sensor?
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
REST YAML: http://pastie.org/p/1BTcO6rQPtxehA5rG1meBg
Raw XML: http://pastie.org/p/5ps5I2LOdvt4o52yXrjvQe
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
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
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.
I'm learning templating so that was a mistake to have that text in there.
It looks like it's just not loading the icon when I add it to a button which is very weird
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
What's the state of that sensor
Both "0"
If you put that template in Dev Tools -> Template, does that output just the mdi:icon text?
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?
Well, {{ states('sensor.garage_door_sensor_left_alarm_level') }} isn't part of your icon_template, right?
Just the lower part is
@loud wave I converted your message into a file since it's above 15 lines :+1:
I should probably remove quotes from "0", right?
Yup
Done and restarting
This is extremely awkward... however, HA seems to convert strings that have numbers separated by commas to lists, which that card doesn't like.
{{ state_attr('light.office_light','rgb_color') | join('\n') }} Hopefully someone has something that's more elegant, but that should work
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
You bet!
I also learned what value_template is for
Now that I know it sounds so stupid that I DIDN'T know of course lol
Just takes a little learning, now you know
And knowing is half the battle..
GI JOOOOooooooooeeeee
Is there a list of all the possible template sections?
That indeed does work sir! What is the | join('\n') though?
That effectively puts a new line between each integer. Ideally, it'd be a comma, but that flips it back to an array
This was it...
Are you saying that particular custom card isn't written to conform to all of the same rules as HA cards?
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
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.
{{ state_attr('light.office_light','rgb_color') | join(',\n') }}
Told you it was hacky
that'll fix it
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?
Ok. I figured it out. I had to extract the JSON from the REST and the parse the values in additional template sensors.
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 }}
- name: "total_lights_on"
Your 'match' call has extra parens around the object_id
oh that is a typo I think of me
I found that online....let me explaihn...exactly rejecting light groups. Maybe there is a better way?
It's fine
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)
Right again sir, thank you! I wish that I understood why that comma makes the halo appear when the light is on, but I probably never will.
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? 🤷
@solar hemlock I converted your message into a file since it's above 15 lines :+1:
@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
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..
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
Which weather integration are you using?
Just the standard one that comes with HAOS
I didn't even think about trying to get a new one
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.
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
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.
That is brilliant, you are genius. @marble jackal
Except the area, can I also include temperature inside the map?
{{
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
}}
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.
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
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
You should add a value_template: https://www.home-assistant.io/integrations/cover.template/#value_template
That is what tells it what the current state is to allow it to open or close 🙂
I don't have any sensor to provide such info and blinds are controlled using 433mhz commands
You can create an input helper and assume it based on the commands sent in HA
@silent seal I have for now forced, position_template: "50" so now have all arrows active, but will try input helper later
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?
No, you cannot create a bunch of sensors from a single template
Curses. Copy and paste is probably the way then. Blech.
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?
Try this custom component, it will simulate the necessary data on your blind movements so that HA can handle the UI seamlessly. https://github.com/nagyrobi/home-assistant-custom-components-cover-rf-time-based
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 }}
You need to use states.sensor.["7_eleven_kingswood_p95"]
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 %}
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.
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') }}
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?
Why do you need that? Is it for displaying on a dashboard?
I'm using the browser_mod and want to show a list with started each item a kind of bullet
You can add them to the names using a for loop (and a namespace)
Is it actually playing something? And does the template work when you test it in devtools > templates
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
Do you have any kind of example how that works?
Replace the or with an {% elif %}
Hmm, that opens up a whole new can of problems
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%}
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?
You can use states() or state_attr() for that, I think.
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") }}
Looks fine, the only thing is that you can expand the group directly, so expand("cover.covers")
okay
Oh, and you don't need the | list filter in the first line
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 %}
- name: "Misch_HK1"
i tried it like this, but there must be something wrong... 😦
Can they be both on or off?
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
So if both are off, what should be the state of this binary sensor
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
{% 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 %}
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?
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
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?
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.
No, in any case it should be one if statement, not two
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
thank you! i will try it 🙂
I've simplified it a bit more
How do i update a entity's state without triggering it's associated actions?
You mean without running automations? What are you trying to do?
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
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.
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' }}
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: "€"
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
Thx @marble jackal
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.
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(',')
If you know there can be only one item, you can just just | join
| first also works for just one item 😛
Yes, but it will error when there are no items, join won't
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
- name: Sensibo_Humidity
- sensor:
- name: Sensibo_Power_Consumption
state: "{{ state_attr('climate.ofir_a_c', 'current_voltage') }}"
unit_of_measurement: 'W'
icon: mdi:power-plug
- name: Sensibo_Power_Consumption
Hard to tell without formatting
formatting what?
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.
Your 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
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.
Where are you looking?
On the dashboard after restarting the whole HA
I have used this sensor in some card I have
What does it say in
-> States ?
which one the climate.ofir_a_c or something else?
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
Is there a current_power or current_voltage attribute there?
Not that I can see, but on the HA documentation
https://www.home-assistant.io/integrations/sensibo/
They say there is a sensor for Voltage
mmm.. okay
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.
What is the purpose of this?
Because the battery will likely register at 51%, 52%, etc.
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.
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
I would look at Trend sensor, that will give you the gradient of the slope of charge. Then in a template it should be pretty easy to use the slope, and the current charge, to predict a time to cross 100%
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.
This certainly is a way about accomplishing this but I'd rather get a more ''real-time'' speed.
Well you can use templates to output the current rate of charging as well
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
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.
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 }}
The number in the attributes rgb_color are integers, not strings
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.
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
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.
You need attributes.rgb_color
Like this?
map(attributes.rbg_color)
No, map(attribute='attributes.rgb_color')
1 step ahead lol. But still undefined.
map(attribute='attributes.rbg_color')
how to substract two dates? {{states('sensor.frontdoor_last_open_time') - states('input_datetime.resident_last_time_entered_home_zone')}}
You have rbg_color now
Convert them to a datetime using as_datetime
🤦♂️
[(255, 136, 13), (255, 136, 13), (255, 136, 13), (255, 136, 13)]
So, these are tuples (I already mentioned that above)
Your color variable is a list
How would I make this work? I haven't worked with tuples before.
Just use ( and ) instead of [ and ] when defining your color variable
{{ ( 1, 2 ) == [ 1, 2 ] }} # False
{{ ( 1, 2 ) == ( 1, 2 ) }} # True
{{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
Still showing as true.
https://dpaste.org/j3VQf
{{ states.binary_sensor.front_door.last_changed | as_local - states('input_datetime.resident_last_time_entered_home_zone') | as_datetime | as_local }}
It's true when the lights are not (255, 43, 0) and false when they are.
you're rejecting it
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.
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.
Something like this @granite granite:
{{ expand('group.flood_sensors') | selectattr('state', 'eq', 'on')|map(attribute='name')|list|join(', ') }}
Wow, I never would've gotten there. That's a lot
That's amazing. Works like a charm. Thank you again and have a wonderful end of the year!
You don't need as_local. As long as for both datetimes the timezone is provided, it will work out fine.
I assume this binary_sensor which you are expanding is a group? In that case just use:
{%- if item.state == 'off' and (now() - item.last_changed).seconds <= '3' -%}
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?
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
You might want to consider something, even if it's a proxy through a calendar. Otherwise this will be quite tricky I think
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
What kind of phone does she have? #android-archived? #ios_and_mac-archived? If it's android maybe you can use device usage to "test" if she's at home
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.
Well, if she uses her iPad a lot, then installing the app on there would make sense too.
Slo now in the holidays both her iPhone and her iPad are left at home even if she comes with us down town
Any chance you can teach her to take her phone with her? 😂
How is that? You meann I would track usage on her iPad and thus determine if she really is at home?
I know! She´s only 10 still
Yes, if she uses it a lot then you could use Shortcuts to tell the HA app when she opens her favourite apps.
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 😛
I know. But it rarely happends when we all leave as a family
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 😛
interresting. Could you elaborate on "set a proxy device tracker" for her?