#templates-archived
1 messages Β· Page 12 of 1
I'm not looking for temperature. I have that working.
I want state (heating/idle/cooling) as a sensor. But using the above template, it's returning as if it expects units in Farenheit
Interesting challenge (I hope)
I have a sensor with two attibutes
date and value
I want to select on the date to collect the value but only (!) the first and last one of that date
date
- 2022/10/07
- 2022/10/07
- 2022/10/07
- 2022/10/07
- 2022/10/08
- 2022/10/08
value
- A
- B
- C
- D
- E
- F
I would like to have A and D returned
How can I find the index of A and D (i.e. 0 and 3) ? I would also be happy if the list can be truncated/split out from the values not equal to 2022/10/07, then I could use count for last index and 0 for first
{% set date = [ "2022/10/07", "2022/10/07", "2022/10/07", "2022/10/07", "2022/10/08", "2022/10/08" ] %}
{% set value = [ "A", "B", "C", "D", "E", "F" ] %}
{% set search_date = "2022/10/07" %}
{% set i_first = date.index(search_date) %}
{% set i_last = i_first + date | select('search', search_date) | list | count - 1 %}
{{ value[i_first] }}
{{ value[i_last] }}
Great, replaced the hardcode with my sensor stuff and works very fine, met dank
graag gedaan
using - unique_id: here_destination name: Here destination state: > {% set select = states('input_select.destination') %} {% if select == 'Thuis'%} {% set destination = 'zone.home' %} {% elif select in ['Marijn','Members','Family'] %} {% set destination = 'person.' ~ select|lower %} {% else %} {% set destination = 'zone.' ~ select|slugify %} {% endif %} {{destination}} I get the name of the entity alright showing either person.marijn or zone.home but using that template sensor as an input for the Here traveltime wont see that state as input in a Map....
it this because of an issue in the template, or would it be the specifics for the Here integration. Aware the outcome of the template is a string, this might be it?
I don't think it accepts templates
You use an input select and an automation to select the option you need
yeah, I was moving from templated input_selects with a name (and rebuild the lat/long in the attributes, to a direct zone/person in the state (see above). that wont work though, because it isnt a true tracker, but a string.. Have to use the real trackers in the select, and then template those names. just the other way around...
Any idea why {{ expand(area_devices('Master Bathroom')) }} returns nothing? area_entities works fine
expand doesn't expand devices
it expands entities
@proven fog ^
there's no reason to use area_devices if you're trying to get an area's entities
if you want device names, then that's a different story.
I want device names
{% set ns=namespace(names=[]) %}
{% for id in area_devices('Family Room') %}
{% set ns.names=ns.names+[device_attr(id, 'name')] %}
{% endfor %}
{{ ns.names }}
I don't know why device_attr can't be used as a filter...
I've got a ping binary sensor pinging a machine to see if it's awake or not every 30 seconds. That state is being fed into a switch template which runs a wake/suspend script when turning on/off. When I flip the switch to off I can see the switch flip back to on and be in that state until the next ping cycle happens. Is there a way to have the switch template hold it's state until the binary sensor's value changes?
Really hoping there's an easy solution that doesn't require me to automate flipping another toggle somewhere else.
Hello All,
Total noob question here...
I have a binary sensor attached to a reservoir tank which activates when the water level gets low. The sensor is called: binary_sensor.grow_reservoir
The sensor is integrated with ESPHome and seems to be working fine - the only thing is that it returns "on" "off" and I would like to customise these values.
I understand that I need to do this in a template which I have written in configuration.yaml and tested in Developer Tools > Template
configuration.yaml loads fine.
However when I check the output of the sensor in an entity card on the dashboard it just returns "on" for it's value.
Do I have to apply the template in the card or somewhere else for it to work?
Thanks...
The Template Code:
template:
- binary_sensor:
- name: Grow Reservoir
state: >
{{ 'Resovoir Full' if is_state('binary_sensor.grow_resorvoir_water_level', 'on') else 'Rasorvoir is empty' }}
- name: Grow Reservoir
you've managed to spell "reservoir" three different ways π
that template doesn't change the original sensor, it creates a new one
you can't "customize" an existing sensor, you need to create a new one that reports the values that you care about, which is seems like you have, but these two statements appear to conflict:
I have a binary sensor attached to a reservoir tank which activates when the water level gets low. The sensor is called: binary_sensor.grow_reservoir
{{ 'Resovoir Full' if is_state('binary_sensor.grow_resorvoir_water_level', 'on') else 'Rasorvoir is empty' }}
Thanks Rob,
Yea, that was a bit embarrassing, I just corrected the spelling while you were replying π
Also the incomplete name for the sensor was a weird cut and paste, they are the same in the name and correct.
So once I have created the Template, Home assistant creates a new sensor that I can use in the card, right?
yes
Thanks very much for your help. Much appreciated.
Folks, I need help. I think it's some kind of punctuation or syntax... N
state_topic: "openevse/temp"
device_class: temperature
unit_of_measurement: "Β°C"
value_template: "{value | states(entity_id) * 0.1 }"```
Just need to divide the MQTT topic by 10
I'm on my 12th check config > reboot
I'm just copying out of the documentation π
and trying everythign!!!!
value_template: "{{ value * 0.1 }}"
that's referring to the previous value
ah I see...
in any case, value | states(entity_id) doesn't mean anything
I thank you for your help - I find the documentation assumes the reader has a LOT of prerequisites
for fluency in yaml, jinja, etc
So RobC - It's still not rendering...
- name: "OpenEVSE Temperature"
state_topic: "openevse/temp"
device_class: temperature
unit_of_measurement: "Β°C"
value_template: "{{ value * 0.1 }}"
Sensor state is coming back unknown (Others from the device are fine, but I don't need to math on them)
what do your logs say?
TypeError: can't multiply sequence by non-int of type 'float'
Exception in message_received when handling msg on 'openevse/temp': '317' Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/components/mqtt/debug_info.py", line 44, in wrapper msg_callback(msg) File "/usr/src/homeassistant/homeassistant/components/mqtt/sensor.py", line 297, in message_received _update_state(msg) File "/usr/src/homeassistant/homeassistant/components/mqtt/sensor.py", line 262, in _update_state payload = self._template(msg.payload, default=self._state) File "/usr/src/homeassistant/homeassistant/components/mqtt/models.py", line 234, in async_render_with_possible_json_value return self._value_template.async_render_with_possible_json_value( File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 583, in async_render_with_possible_json_value return _render_with_context( File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1915, in _render_with_context return template.render(**kwargs) File "/usr/local/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render self.environment.handle_exception() File "/usr/local/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception raise rewrite_traceback_stack(source=source) File "<template>", line 1, in top-level template code TypeError: can't multiply sequence by non-int of type 'float'
ah - It's a string then, and it's gotta get converted to a float...
THEN we can math it.
Now, as far as the publishing device, and this is more an MQTT question, but I didn't' know there were data types in an MQTT
Gotta take that up in C++ on the publishing device..
I acctually notice this in lots of integrations, HACS for the car shows the range on the EV for example as that beautifully colored bar graph...
at least it "should" be JSON. in this case, it looks like it's just a raw value, which is interpreted as a string
Brilliant man, I think this is it, the data types. Thanks @inner mesa
So sir, interestingly, when these raw values come in and I apply a device class and unit of measurement to them (current, for example) this whole raw value thing goes away merrily
or the problem with it anyhow
I see some special casing in the code for dates and timestamps, but not numeric values. I guess it could be there somewhere
Newbie here, can anybody help me with messages tempates in trigger context
Just ask your question @devout halo π
this is doesnt trigger the automation:
{{ (as_timestamp(states("sensor.mob_harro_next_alarm"), 0) | round(0)) == (as_timestamp(now()) | round(0)) }}
i can see it working in development tools templating, when i make a countdown timer of it...
Because now is evaluated every minute. So I think im your system might be a little slow, so it rounds to 1 second over the minute, making you missing the match
that's a pretty over engineered alarm template
And that
hahahahaha! touchΓ©
im looking for 20min before next alarm
and the error catch when none is set....
2022-10-10T05:15:00+00:00
will it always have the timezone?
which is odd because its actually 7:15
Which is correct, because you are at GMT +2
ok got it
{{ states("sensor.mob_harro_next_alarm") | as_datetime >= now() }}
we are now +1 AND +1 summertime
I would say the other way round
hah, was just going to say that
Same here
{{ now() >= states("sensor.mob_harro_next_alarm") | as_datetime }}
if you want 20 minutes
{{ now() >= states("sensor.mob_harro_next_alarm") | as_datetime - timedelta(minutes=20) }}
what if a second alarm is set...
I do had some people saying that caused unwanted triggers
the sensor hops directly to the next, not triggering..?
Yep, I was just about to say that
and then turn true again later
so when 2 alarms are set it only triggers on the last one?
you're not making sense
ofcourse i dont
how can 1 entity have 2 alarms
at any given moment, it will have 1 alarm
so if you set it twice throughout the day, both will trigger unless you set it 1 minute apart
The problem with this sensor is that it changes to none or the next alarm before now() is rendered again
if it's a datetime sensor it shouldn't change to none
but, that could be built in for safety
Okay, sorry unavailable. It's indeed as_datetime which makes it none
ok well.... i cant even get a light to turn off when my alarm goes... lol
when no next alarm is set i get: TypeError: '>=' not supported between instances of 'datetime.datetime' and 'NoneType'
thats what you are talking about
i pasted this in dev tools so i can see the countdown to zero which works. But then it doesnt go TRUE
{{ now() >= states('sensor.mob_harro_next_alarm') | as_datetime }}```
hence my guinee pig light not turning off
hahahaha still no go..... man man man
could this be the problem for this solution? {{ now() >= states("sensor.mob_harro_next_alarm") | as_datetime }}
As soon as it should go to TRUE the sensor is reset to 24x60x60= 86400 seconds, hence its not triggering
in fact. dev tools trow an error for brief second and then showing 86400 again
so TRUE is never catched
So.... if i add a timedelta of at least a couple of seconds there is a timeframe where it IS true....
bingo
so waiting for that exact moment when 2 timestamps are the same is never catched indeed
It will throw an error every minute when there is no alarm set though
But even when it is set, i saw the error for that split second
how can i catch the error with {{ now() >= states("sensor.mob_harro_next_alarm") | as_datetime - timedelta(minutes=20) }} when no alarm is set?
{% set alarm = states('sensor.pixel_5_next_alarm') | as_datetime %}
{{ now() >= alarm - timedelta(minutes=20) if alarm else false }}
Replace with your own sensor
well my overengineered smartsocket to charge a mobile phone in the night is complete hahaha
evil Mandrak laugh
thank you both for the help
Yep
I am trying to have a template return only a specific object in a list.
I have this template
{{state_attr('sensor.nordpool_kwh_bergen_nok_5_096_025', 'raw_today') | sort(attribute='value') | map(attribute='start') | list}}
which gives this output: https://hastebin.com/awuyaruqol.json
How can I have the template return the first (or fifth) element in that list?
For context: here is the full output before my filters: https://hastebin.com/bugehodoza.yaml
fifth would be [4]
If you use first, make sure to use |default after
| first works, but I cannot get [x] to work? Where do use it? I only get TemplateSyntaxError: expected token 'name', got '['...
Gotta put the whole call in ()
Before using []
Or set your call equal to a variable, then use the []
I think this works as I intended... Let me know if this is gonna blow up in the future because of something I have not foreseen...
{{ ((state_attr('sensor.nordpool_kwh_bergen_nok_5_096_025', 'raw_today') | sort(attribute='value') | map(attribute='start') |list()) [3] |as_timestamp | timestamp_custom('%H') | int) == (now() | as_timestamp | timestamp_custom('%H') | int)}}
This lists all hours today and sorts them based on cost of electricity. It compares the current hour with the hour pulled from the list. I am planning to make maybe 10 of these template sensors to pull the 10 cheapest hours, trying to shift energy usage towards those hours....
Maybe a cleaner way to do this is not to make a bunch of template sensors, but check if the current hour is one of the first X objects in the list?
Any way to do that?
Thanks! But I wasnβt sure so I ended up asking it in here. Would love some help from anyone who might know anything about Template Locks. #1028765200540782633 message
This template
{{(state_attr('sensor.nordpool_kwh_bergen_nok_5_096_025', 'raw_today') | sort(attribute='value') | map(attribute='start') | list()) [0:2] }}
provides this output
[datetime.datetime(2022, 10, 10, 2, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), datetime.datetime(2022, 10, 10, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo'))]
How can I convert each of those items to a timestamp?
If I add a filter | as_timestamp I get an error saying that as_timestamp got an invalid input...
Hello,
I need a bit of help with a template, please.
I have the following code in my configuratoin.yaml file to change the values of a binary-sensor (water) to something readable:
template:
- binary_sensor:
- name: Grow Reservoir Status
icon: mdi:cup-water
state: >
{{ 'Reservoir Full' if is_state('binary_sensor.grow_reservoir_water_sensor', 'on') else 'Reservoir Empty' }}
- name: Grow Reservoir Status
When I check the statement in Developer Tools > Template the output is the desired result 'Reservoir Full' or 'Reservoir Empty', however when I add the template sensor to a dashboard I just get an 'On' or 'Off' output.
Also when I add the templated sensor to the dashboard, it reads as 'Off' when the physical sensor (binary_sensor.grow_reservoir_water_sensor) reads as 'On'
Any ideas, please? And thanks for any help offered...
@mortal harness You have created a template binary sensor. Binary sensor only have the states on/off, depending on if the template evaluates to true or false
Thanks so much, just changed it to -sensor: and it works as inteded. Thank you very much for the help. π
{{ (state_attr('sensor.nordpool_kwh_bergen_nok_5_096_025', 'raw_today') | sort(attribute='value') | map(attribute='start') | map('as_timestamp') | list) [0:2] }}
With auto entities I'm trying to list devices in an area then hopefully with a pop-up list the entities associated with the device.
Doesn't list anything but it says this template listens for 2ded089b802ac773ae109a297b171ae5 which is the device id of the device currently in the area
OK. Should I be able to use timestamp_custom() the same way?
If you first map it to a timestamp yes
Just tested it, this works: {{ [ now() ] | map('as_timestamp') | map('timestamp_custom', '%H:%M') | list }}
Very cool! π
Anyone have any ideas on this?
Not my area of expertice, but I beleive expand(area_devices()) will include any devices in a area that you have created. Unless you have created an area named Temperature Sensors I don't think that will give any output.
I did create an area called 'Temperature Sensors' it's tracking the device but not listing it.
And named it Temperature Sensors?
Yes
Result type: list
[]
This template listens for the following state changed events:
Entity: 2ded089b802ac773ae109a297b171ae5
That's the correct device id but nothing is shown in the list. I would want the device name of course but device id is a starting point hopefully.
@unreal beacon posted a code wall, it is moved here --> https://hastebin.com/rizugiquva
and what card would that be going in? IIRC there's no cards that display devices
Auto entities can? I think
More or less was hoping using the Id, we can get the entities associated with the device.
I don't know if this is fully possible. The idea would be to tap on a device a pop-up happens and the associated devices appear.
Rather than listing all of them all at once.
if you want entities from the device, just use area_entities
ok, you keep saying 'tap on the device'
so I keep asking you "what card can display a device"
and the answer is "No cards can display a device"
so, you can't even get step one of your 2 step process
Ok lol. I was hoping it could be possible.
To have a clean page where I tap to see entities associated to a device vs all device entities in an area being displayed all at once which gets cluttered fast.
Maybe a wth topic
How would I do this in a template though.
The link I provided?
Is there a card that shows a device? Thomas's auto-entities card can only use cards that exist. If there isn't a "display this device via the device_id" card, then nothing will work
I don't use devices, so I don't know the answer to that. There may be a card that displays devices.
I'd use the template in the Markdown card if I really wanted all the device entities listed together
Someone in here had something a while ago for getting the device ids from entities, but I never bothered with it as for me it makes more sense to grab all the temperature sensors and put them together regardless of the physical device involved
Yah, getting the device_id isn't hard, or attributes. But having a card display a device is where the 'barrier' is. Using a markdown card is a nice work around. Not sure if that would solve what dan is looking for though as it would be difficult to pair with auto-entities
and there's no tap action, so it wouldn't lead to his entities when clicked
He could use a custom button card that displays specific information, but that doesn't have access to jinja
so he'd have to build the logic from the auto-entities card
show your template developer tools
Any idea what the logic would entail for auto-entities
Nope, not sure if itβs possible
Interesting. Would be nice. The only reason I would do this is because I would rather have temperature and humidity in the same place for each device. Keeping it clean if I want to see a specific room I only will see that room not 30 rooms all at once.
new to templates (15 mins in)... I've worked out what sensors/values to compare. got a if/then template working in the dev template tool... but... not sure how to convert that to a condition in an automation... I assume I'll use template condition... just not sure of the template logic for it... :\
can someone offer assistance?
I'd like the condition to be:
outdoor temp > climate min temp
and outdoor temp < climate max temp
This is what I've got:
https://hastebin.com/uvecabeloj.java
Sounds like you need a simple comparison. Just don't forget to make sure it's an int: https://www.home-assistant.io/docs/configuration/templating/#important-template-rules
{{ states('sensor.outdoor_temperature') | int > states('sensor.climate_min_temp') | int }}
or something similar
This did it. π Thanks!
Followup question: should I create 2 conditions? One for Less than, and another for Greater than?
-or-
is there an easy way in the template to say less than this and greater than that?
based on this: https://www.home-assistant.io/docs/scripts/conditions/#template-condition
I'm guessing it's having 2 conditions rather than incorporating the 2 conditions in a single template.
Take a step back and explain what you're trying to do π
I'd like the condition to be:
outdoor temp > climate min temp
and outdoor temp < climate max temp
- My ecobee is in auto mode (with a heating setpoint, and cooling setpoint)
- If my front door is open, I'd like to notify someone only if:
-- the outdoor temp is outside of the range of setpoints
I think I may have it with: https://hastebin.com/enurivovag.yaml
thoughts?
no need for a time pattern trigger: https://paste.debian.net/1256591/
will that trigger after the door has been left open all day, and the temp dips down?
or, only at the single point that the door has been open for 1 min
this is something I get hung up on a lot...
essentially, I want to leave my door open while it's nice, and have a reminder to close it when it is no longer nice enough to leave it open
ah, i see
I think what you provided is good for accidentally leaving it open when it's not nice.
I am going to look into template triggers... π
yeah, one sec
trigger: outside temp moves outside of the "good range"
condition: door is open for 1 min
action: notify door should be shut
that will trigger when the door is open for one minute and the temp is outside of the range OR if the temp goes outside of the range and the door has already been open for at least a minute
you could also simplify it by making a template binary sensor that's on when the door is open and the temp is out of the ranges and set delay_on to 1 minute and use that as the trigger
You're awesome! I love having working examples to work with. π
yeah... I think I'm finally at the point I can start learning more about templates.
templating is nice
took me a while before it finally clicked, but it opened up many other possibilities when it did
I have always known it's more flexible than straight up automations... but, my phases of learning tend to be: 1) freak out 2) get overwhelmed 3) freak out again 4) start to understand
lol
Well, thank you for your help, and also to Rosemary Orchard.
Hello. I am wanting an automation to run while the word "ready" doesn't exist in a state field. I know the repeat function will run while it return true, so this is what I have for my repeat value_template: "{{ ('Ready ' in states('sensor.sub_alarm_panel_message') == false) }}"
However, it's not working. It doesn't repeat at all. Would that be the correct way of doing it?
I would use {{ not 'Ready' in states('sensor.sub_alarm_panel_message') }}
and what is your entire code for the repeat?
Hi, does anybody know how to count persons, who are "not_home"? The counter for persons at home works at me, not_home doesnt (I editted sensor.yaml)
petro answered: templates. "{{ states.person | selectattr('state','eq','not_home') | list | count }}", if you have questions -> templates
I inserted this:
{% set count = [states.person | selectattr('state','eq','not_home') | list | count %}
konfiguration invalid...
That's not what Petro gave you, why did you change {{ to {%?
how can I insert the code here? I changed to {{ and it is invalid
/config/sensor.yaml
Zaehler Persons away
number_persons_away:
friendly_name: 'Persons away'
value_template: >
{{ states.person | selectattr('state','eq','not_home') | list | count }}
do you use other zones besides home?
no. Status is home or not_home or something like unavailable
At the moment, my wife and me are "not_home"
if you're putting it in sensor.yaml, you're missing the header
- platform: template
sensors:
number_persons_away:
friendly_name: 'Persons away'
value_template: >
{{ states.person | selectattr('state','eq','not_home') | list | count }}
I will try, but number_persons_home works without header
platform: template starts with - platform: template
sensors:
Time
time_of_day:
then number_persons_home
\test
\test
`test
Β΄test
'i dont know how to insert code here
test
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), http://pastie.org/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
thank you
How do you have sensors.yaml included in configuration.yaml?
Yes, I am sure that this works. /config/configuration.yaml ```
Configure a default setup of Home Assistant (frontend, api, etc)
default_config:
Text to speech
tts:
- platform: google_translate
group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
sensor: !include sensor.yaml
...
is that right? I think so
That looks correct. Then you definitely need the header. Keep in mind, every platform: xxx is different so the yaml won't look the same as other platform: abcs
i.e. platform: template has different fields in relation to platform: tod
Thanks! I'll give it a try. And I also only want it to repeat a max of 20 tries... So, would I do:
{{ (not 'Ready' in states('sensor.sub_alarm_panel_message')) and repeat.index < 20 }}
Does that look correct?
personally, I think it reads better if you have
{{ 'Ready' not in states('sensor.sub_alarm_panel_message') and repeat.index < 20 }}
Oh! Ok. So don't need not at the beginning and that solves the whole line not being "not" π
the whole line wouldn't have been not
it would have only been the first condition
code has order of operations that are implied
Even if I didn't use the extra parenthesis around the first condition?
everything before the and is resolved before everything after the and is checked
Yep, even if you don't use the extra parenthesis
Gotcha! That's why I added the extra parenthesis is because I thought it would do the whole line π Learn something new every day π
personally, i'd also reverse those and's as well
if you're beyond 20, there's no reason to check if ready is in the state.
That makes sense π
if the first condition fails, the second condition is never checked
it works that way with or as well. If the first condition passes, the remaining arn't checked.
Good to know! Thanks for all the teaching π
Oh, and another quick question while I'm in the learning mood... What's the difference of using "value_template: >-" vs "value_template: >" I have seen it both ways...
the - removes whitespace at the start of your template when resolving the template.
it's 100% useless everywhere accept for markdown card. If you see people use it, they don't understand what it's doing. I exclusively use just >
because leading and trailing whitespace in templates is trimmed in every scenario except for the markdown card
Gotcha π Thank you!
np
Thank you. I got it working now, but I have several entities now. that are not in sensor.yaml. How can I delete them?
Not sure what you mean, delete them from the UI?
Sorry, I went to /config/entities
here, I filtered "persons"
And I have 5 ones there, 2 are wrong ("persons away") for example. Persons away is not in sensor.yaml
In sensor.yaml, i have "persons home", "persons not home" and "persons unknown"
How can I get rid of the entities, that are not any more in sensor.yaml and not used in the UI?
click on the (i) in develper tools > states and delete it from there
also accessible from the search in the top right
Sorry, I dont find it. I have developer tools, but there is no "i"
Aah I see. The entities can be deleted by (i) and the pen. My problem is, that this entitiy doesnt have the pen symbol
Hi - a question about selecting on state. I have a group of window sensors ("windows") and wish to display which are open, so "expand('binary_sensor.windows')" should give me a list of the object members, and then filter using selectattr to get states that are on. The problem then occurs when I try to use the "friendly_name" of the objects rather than the "entity_id". So for example:
{{ expand('binary_sensor.windows') | selectattr('state','eq','on') | list}}
gives
[<template TemplateState(<state binary_sensor.window_childrens_bedroom_l_iaszone=on; device_class=opening, friendly_name=Window Childrens Bedroom (L) Iaszone @ 2022-10-11T14:09:46.705967+01:00>)>, <template TemplateState(<state binary_sensor.window_master_bedroom_l_iaszone=on; device_class=opening, friendly_name=Window Master Bedroom (L) Iaszone @ 2022-10-11T13:29:43.166089+01:00>)>]
and so we get a list of entit id by using
{{ expand('binary_sensor.windows') | selectattr('state','eq','on') | map(attribute='entity_id') | list}}
['binary_sensor.window_childrens_bedroom_l_iaszone', 'binary_sensor.window_master_bedroom_l_iaszone']
but is I try to get the friendly name- which is listed in the template objects I get
{{ expand('binary_sensor.windows') | selectattr('state','eq','on') | map(attribute='friendly_name') | list}}
[Undefined, Undefined]
Any idea why one works and the other doesn't
And where would I go for documentation to understand such details
Yes, friendly_name is an attribute, so you need to use | map(attribute='attributes.friendly_name')
However, it's better to use | map(attribute='name')
@ thefes: Do you have another idea how to delete the entities?
there should alway be a Settings tab on each entity, although it might mention it can not be edited because there is no unique_id. The delete button should be on that screen
Thank you the "attributes.friendly_name" worked
'name' will also work
There is nΓΆ delete button. I will upload pics in a few minutes
If there is no delete button there, the sensor is somewhere in your configuration
no it isnt. The entities have "disappeared" now. It seems, that the unused (old) ones are deleted after a while
Another query - the functions regex_... - I cannot find any documentation on what type of regexes it uses? Neither https://www.home-assistant.io/docs/configuration/templating/ nor https://jinja.palletsprojects.com/en/latest/templates/ seem to define which sort?
what are the available types?
I just use "normal"/"standard" regex as documented everywhere
PERL type, ISO 1003.2, early unix
it uses Python re underneath
Which lib
re
it just passes it straight through
How do I make a documentation change request?
A link to the re library would help
I think I have put in a request for the documentation change (https://github.com/home-assistant/home-assistant.io/issues/24524)
You can edit it yourself and submit a PR
Good Evening, can sombody tell me whats wrong here?
https://dpaste.org/PLGcD
your indentation is messed up there, but that could be dpaste
is the state of either sensor actually "True", just like that?
The first sensor shows 2 h and the other the actual time
the indentation is ok in the yaml
no the sensor is false
you need to specify the actual state, then
if it isn't "True", then you're doing it wrong
you also haven't said what's wrong, so it's kind of a "where's waldo?" question
this kind of question makes me feel like I'm in a job interview
π
the issue is the first sensor shows the correct duration 2:30 and the other one just the actual time like 22:01
How would be the code for counting the time the sensor is true?
what you have there should do that if the state is really "True", just like that, which you haven't really answered
you've said "no the sensor is false"
and "sensor is true". Neither of which is "True"
ok
the sensor switches to true when the climate attribute is not idle
and the sensors show true when the climate is heating
the switching between the states and i want to count the time the climates are heating so i created following templates
I still don't think you've recognized the difference between "true" and "True"
you need to be precise if you want the right results
well for 1, the state isn't going to be True or False
unless that's under the sensor section
post a screenshot of the state in developer tools -> states
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
Ok, not sure why you wouldn't make those binary sensors.
so, what's the problem then? History stats not counting correctly?
yes
It's most likely due to you choosing poor state names
because of this
The Boolean That's Actually a Stringβ’οΈ
Right
whoa nice any suggestion `?
Make binary sensors?
ok i will try to look for it
nothing to look for
put it in the binary_sensor section instead of sensor section
copy/paste
ook
binary_sensor:
- platform: template
sensors:
hzbuero:
friendly_name: "BΓΌro heizt"
value_template: "{{ (state_attr('climate.heizung_buero', 'hvac_action')!= 'idle') }}"
you insert it into configuration.yaml, not sensor.yaml
Invalid config for [sensor.template]: [binary_sensor] is an invalid option for [sensor.template]. Check: sensor.template->binary_sensor. (See ?, line ?).
somehow this is messed up... i need to declare first?
You..put it under sensor
no copied it to configuration.yaml
uhm, how can we smarten this:```
state: >
{% if utcnow().hour - as_datetime( state_attr('sensor.energieprijs_uur_0','Timestamp')).hour ==0 %}
{{states('sensor.energieprijs_uur_0')}}
{% elif utcnow().hour - as_datetime( state_attr('sensor.energieprijs_uur_1','Timestamp')).hour ==0 %}
{{states('sensor.energieprijs_uur_1')}}
{% elif utcnow().hour - as_datetime( state_attr('sensor.energieprijs_uur_2','Timestamp')).hour ==0 %}
{{states('sensor.energieprijs_uur_2')}}
etcetc to 23....
its a sensor calculating the current hours energy price. and its completly verbose up to now, but I can not find the correct way of replacing the number in the uur_X
wait, it's as simple as```
state: >
{% set hour = now().hour %}
{{states('sensor.energieprijs_uur_'~hour)}}
what were they thinking.. completely threw me off.
another one then: we dont need defaults on average? state: > {% set ns = namespace(vandaag=[]) %} {% for dag in range(24) %} {% set ns.vandaag = ns.vandaag + [states('sensor.energieprijs_uur_'~dag)|float(0)]%} {% endfor %} {{ns.vandaag|average}}
final for in the same series of energy day prices: cant we use multiline template notation on the resource_template in a rest sensor: https://community.home-assistant.io/t/optimize-or-fix-this-rest-sensor/473647 ? I do believe its my first template in that integration, but it seems so unexpected. Multiline being a valid Yaml syntax?
You will always have a list of 24 items here, so no default for average is needed
Guess this is too early as I tried to find this, anybody set up a room presence detection with the iBeacon/BTProxy integration? Guess its going head to head with ESPresence. With that, was able to determine which ESP32 my phone was connected to, and thus the room was known.
I guess I have to create a sensor that read the state (home and not_home) and the attribute (source)
source is the room
if you have 4 rooms, it will be an if structure, I guess?
trying to get the below code to work in a Markdown Card.
it correctly lists the devices on my network & the IP address.
it doesn't format the output to fit in the table.
|Name | Ip Address |
|--- |---: |
{% for state in states.device_tracker %}
{% if state_attr(state.entity_id,'ip_address') != none %}
| {{ state.name }} | {{ state_attr(state.entity_id,'ip_address') }}|
{% endif %}
{% endfor %}
ok, managed to figure it out
|Name | Ip Address |
|----|----:|
|{% for state in states.device_tracker %} {%if state_attr(state.entity_id,'ip_address') !=None %} {{ state.name }}|{{ state_attr(state.entity_id,'ip_address') }} {% endif %}|
{% endfor %}
hey thanks, @mortal bear I was just going to post that
it works! except, I'm trying to filter out
just one device_tracker
@floral steeple posted a code wall, it is moved here --> https://hastebin.com/omukocitoj
the table works in your latest iteration, nice!
I thought putting this before your code, would filter out all other entities, but it does not
type: entity-filter
entities:
- entity: device_tracker.2686f39c_bada_4658_854a_a62e7e5e8b8d_1_0_2a2b
name: Android Phone
state_filter: - home
are you sure that the attribute is correct in state_attr(state.entity_id,'source')?
Yes, it reports correctly with source, which is the attribute for the device_tracker
From iBeacon
It seems however, to list all the entities that have source as an attribute, though
source in this case is the ESP32 board, in the room.
You need to use None instead of none
Or this
content: |
|Name | Location |
|--- |---: |
{% for state in states.device_tracker | selectattr('attributes.source', 'defined') %}
| {{ state.name }} | {{ state_attr(state.entity_id,'source') }}|
{% endfor %}
Rounding to fixed decimal for currency
Hey Guys, could somebody help me out on a Template Sensor please ? I want as example Sensor.X state value is above 0.1 else Sensor.Y state is 1, and when Sensor.X is above 0.1 and Sensor.Y is 0 to show an specific image in Lovelace for each function? Thank you
somebody have a template to convert internet speeds to human readable?
e.g. I have a trafficsensor reporting in kbit/s but doesn't make much sense to display 349073450 kbit/s in the frontend
divide by 1000 for Mb/s
divide by 1000000 for Gb/s
@coarse tiger ^
and if it's actually bits and not bytes, divide by 8 on top of that
ok then there's apparently no clever way π
dumb works, as always
{% set rate = states('sensor.fritz_box')|int(0) %}
{% if rate < 0 %}
0
{% elif rate > 1000 %}
{{ rate / 1000 }} mbit/s
{% elif rate > 1000000 %}
{{ rate / 1000000 }} gbit/s
{% else %}
{{ rate | round }} kbit/s
{% endif %}```
Just so you understand bits are not the same as bytes
and Gbs and Mbs the b stands for bytes
FYI there's a units conversion WTH that you might want to vote for, as this should be covered under it
all my internet speed related things go with bit (you order a 500mbit contract, you get something below in mbit, etc...)
but you are right, the sensor reports in bytes
Hi, after i've upgraded the homeassistant to the latest version some of my self made templates stopped working, i've got something like 2022-10-12 04:44:16.902 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template("{{ (states('sensor.ups_nominal_real_power')|int * states('sensor.ups_load')|int / 100) / 1000 }}")
may i know where can i find info about whats have been changed, that the templates where stopped working, thanks
Howdy, I am trying to develop a template to change my outdoor lighting based on the holiday season. So based on a date range I want to activate different scenes.
this is not helping really, how can I get the statistics back?
(I'd assume by setting a unit_of_measurement but that just gets appended in the UI afterwards I believe and also is dynamic in this case)
guess there is no easy solution to this other than the WTH FR
You can't if you have a dynamic unit of measurement. You have to convert it to a single unit
so go with mbits or gbits
not what you currently have
Neither 2663838 mbit or 0,00363663 mbit make it readable for humans but OK π
that damn thing broke on every month release, i'm giving up, better will move to some other home automation software
Then make one that has the units you want and use another for the statistics. You can run stats on a dynamic unit
Negging people into replying won't get you help
No one here owes you anything.
"Hey let me threaten to quit a software to a bunch of people who help others with the software"
π
that'll show 'em
Oh man, 1 less person to help, darn
well my week is ruined now
i wanted to dedicate it to helping that person but now I don't know what to do
this is de wey, thanks
thanks @marble jackal ! This works also! What would be the easiest way to display the state (home or not home), and when the state is home, to display the room, for example, source attribute right now is showing " esp32-bluetooth-proxy-5f189c" but a friendly name of "Living Room" could be more intuitive
replying to this code
You need some kind of mapping to map the source to the room then
thanks, I'll look into this. Cheers!
I am wondering if somebody has created a template sensor to help predict if car windows get frosted during the night, I could use the info to adjust the alarm clock time in the morning so I have some extra time to clean the windows of my car.
You'd need a history of frost from previous years
aka, doesn't exist in HA
FWIW farmers pay big bucks to know this info, i'm sure there's a history for your area somewhere
I can start building the history in influxdb for the temp, humi wind speed, cloud cover and dew-point sensor data.
This morning the windows were frozen with outside temp above 0 degreese C, so i know that its not a simple thing, was just wondering if maybe somebody else had looked into this problem and also does not like to clear the windows in a hurry because of not coming in late for work
Well your second hurdle is that you can't access history from templates
so even if you had the information, you'd need to come up with a way to get it into HA
You're probably better off getting a local weather station, like Ecowitt and then use ecowitt2mqtt integration
OR if you trust your local API weather, im sure there is a sensor for that
ill have a look at the ecowitt
that looks promising, have to check it out this weekend
ok I took a bit of different approach for my room presence sensor, I realized I actually don't need the state because if the attribute (source) is not available, then im not home or in the room
I don't know if the bot is going to chop this up, its 15 lines of code for a template sensor
so i'll paste it here https://dpaste.org/tjsGp
think this would work?
hmm, wonder if I should be using
is_device_attr(device_or_entity_id, attr_name, attr_value)
hello im in need of alittle assistance with a received MQTT message
{
"Id": "4a9bc0ea-5876-464c-a938-f832208005e5",
"Topic": "Gaming Room Temp",
"Title": "",
"Message": "",
"Data": [
{
"Name": "Gaming Room Temp",
"Id": "data\\temperatures\\5",
"Unit": "Β°C",
"Value": 23.39
}
]
}
all i want to display is the temperature value
currently config.yaml
sensor:
- name: "GamingRoomTemp"
unique_id: sensor_gamingroomtemp
state_topic: "Gaming Room Temp"
unit_of_measurement: 'Β°C'
value_template: '{{ value_json.temp }}'``` ^^^ without this line it Outputs
`{"Id":"4a9bc0ea-5876-464c-a938-f832208005e5","Topic":"Gaming Room Temp","Title":"","Message":"","Data":[{"Name":"Gaming Room Temp","Id":"data\\temperatures\\5","Unit":"Β°C","Value":23.39}]} Β°C`
`outputs: 0 Β°C`
im im 98% there i just dont understand the templates and the documentations is wild
Is there a template to make a sensor that is either home or away, but it's based on if 1 of a few location/proximity sensors are home or away?
like a binary sensor with a condition the HA App says I'm home, the network says my phone is connected, or possibly more?
You can create a group sensor, and define whether one is true or all is true for the sensor state
according to https://community.home-assistant.io/t/homeassistant-helpers-template-template-variable-warning-dict-object-has-no-element-0-when-rendering-value-json-0/303411/17 we need to also add |default to the value_template in these rest sensors. however, when I add that |default, it wont pass the config checker. value_template: "{{value_json[0]|default['TariffUsage']|float(0) + states('sensor.prijsopslag_energie')|float(0)}}" json_attributes_path: "$[0]"
is what I use now, and I dont really understand where the |default needs to be added after the 'value_json[0]' ...
to prevent:```
Logger: homeassistant.components.rest.sensor
Source: components/rest/sensor.py:170
Integration: RESTful (documentation, issues)
First occurred: 12:23:50 (24 occurrences)
Last logged: 12:23:50
JSON result was not a dictionary or list with 0th element a dictionary```
you need to add the default before you take the first item
{{ (value_json | default(['something']))[0] }}
Right. Thanks will do. Btw all 48 of them do show their value..
hmmm, does not help I am afraid..
I'm not using rest sensors myself, so I'm no expert on this, but to me it looks like the attriubute also tries to use the first item out of the value_json which will probably give similar issues if the provided value is empty
found it. its fares well on 0-23, but from 24 on it errors
and those are the values that are for the next day, and currently not available in the main data (that data is provided after 1600 )
value_template: "{{(value_json|default(['default']))[24]['TariffUsage']|float(0) + states('sensor.prijsopslag_energie')|float(0)}}"
json_attributes_path: "$[24]"
json_attributes: *attributes``` then throws the error
so a default is not sufficient....
Hmm, I would expect this to error after 0 (so already on [1]). Your default only has one item, so if value_json is not available your default will kick in
but in this case I assume there are 24 hours of data provided, so there are 24 items in the list
[24] is the 25th
Well, even more, there are 48β¦ today and tomorrow s prices. As said, tomorrows prices are only available after 16:00 hr
So not sure how to prevent that other than in the template. (We can not do something like a trigger template I guess. Would be cool though)
then you need to provide a default with 48 items.
Not sure if this most efficient, but it should work
{% set ns = namespace(default=[]) %}
{% for i in range(0,48) %}
{% set ns.default = ns.default + ['default'] %}
{% endfor %}
{{ (value_json | default(ns.default))[24] }}
Wow. Now thatβs a default filter π thanks and Iβll try when I get back! Will let you know here . CoolπΆοΈ
it's not
{{ (value_json | default(['default']*48))[24] }}
Right. Even better. Besides this template per sensor, I canβt stop figuring whether the whole rest sensor couldnβt be simplified.
Itβs a single resource with 48 verbose sensors right now . Couldnβt I write that as a βfor 0-47β loop somehow ?
Nope
post your yaml, I'm sure I could simplify it with anchors
it depends on how much redundancy there is
I want to see an example of that. I need to start using anchors more.
You can look at my setup for that
I use them ALOT
and I refactored scripts this weekend
Let me attach my github to my name
Ooh, excellent.
I shall enjoy perusing them. Though sometimes seeing a before and after is the most helpful, so I may have to check out your previous commits.
Ok, attached them to my name
Let me find a good example
This one is a complex one https://github.com/Petro31/home-assistant-config/blob/master/automation/frigate_notifications.yaml
but it's 5 automations
the take away is that you can use <<: &some_name to declare yaml that you want to reuse
and then to reuse all those fields <<: *some_name
@mighty ledge now that you are here, I'm having a strange problem with the media_content_type of a cast device
What's the problem?
{%- set ns = namespace(info=[]) %}
{%- for entity in expand('media_player.zolder_mini_martijn') %}
{%- set general = dict(media_content_type = state_attr('media_player.zolder_mini_martijn', 'media_content_type')) %}
{%- set ns.info = ns.info + [ general ] %}
{%- endfor %}
{{ ns.info }} # [{'media_content_type': <MediaType.MUSIC: 'music'>}]
{{ state_attr('media_player.zolder_mini_martijn', 'media_content_type') }} # music
{{ states.media_player.zolder_mini_martijn.attributes.media_content_type }} # music
{{ states.media_player.zolder_mini_martijn.attributes.get('media_content_type') }} # music
Iβve already anchored it π should be a community post, have to look it up
why do I get [{'media_content_type': <MediaType.MUSIC: 'music'>}] in the first version, and not [{'media_content_type', 'music'}]
I didn't have it on an older version of the cast integration (which I was running as custom component so I could keep my players as idle instead of off)
This is the resource ``` rest:
- resource_template: >
https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs?startTimestamp={{now().strftime('%Y-%m-%d')}}&endTimestamp={{(now()+ timedelta(days=2)).strftime('%Y-%m-%d')}}```
Ah, that's an enumeration
or enum in python
I ran into this recently
what's the name of <MediaType.MUSIC: 'music'>
variable name
media_content_type
I acutally use state_attr('media_player.zolder_mini_martijn', 'media_content_type') in this version
media_content_type.name
That used to be entity.attributes.media_content_id. I changed it to see if it helped
entity.attributes.media_content_id.name
if that doesn't work, let me know
I ran into this serializing MQTT payload recently
[{'media_content_type': Undefined}]
same
'' ~ entity.attributes.media_content_id
sorry, both name and value worked
I used id instead of type
ah
and then copied your version,. where you used my incorrect input
name gives MUSIC and value gives music
however, your last resort version will also work on older installations, so I might use that anyway
yes, that works as well
basically, you need to get it as a string
hmm, I actually use entity.attributes.get('media_content_type', 'no type')
'' ~ entity.attributes.get('media_content_type', 'no type') it is then
I have rhasspy setup and got it to report the date to me. How can i get it to tell me the date like october 13 2022? and not 13th of the 10th two thousand twenty two? sorry if this is an easy thing, i have just started with home assistant
how are you outputting the date right now?
if you want the year to be 20 22, then just put a space in the year
it is outputting as 13th of the 10th two thousand twenty two. I would like it to say it in the american format if possible. like Thursday October 13th 2022.
What is the code you are currently using to create this output?
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.
You lost me here, you are outputting the state of sensor.date is the state of that sensor 13th of the 10th two thousand twenty two?
sorry, this is like day 2 for me with home assistant. and the sensor does appear to be outputting as you said
You don't need that sensor
action:
- service: mqtt.publish
data:
topic: hermes/dialogueManager/endSession
payload_template: >-
{"sessionId": "{{ trigger.event.data._intent.sessionId }}", "text":
"Today is {{ now().strftime('%A %B %-d %Y') }}"}
it will output Today is Thursday 13 September 2022
I do
that works. now i just need to determine why its saying its the 10th lol
ah
It's fixed in the template above
you are the king of cool
usually people want it to read phonetically.... Today is Thursday, Septemper 22nd, 2022
but adding st nd rd th requires a bit more code
not too much
| ordinal
e.g. {{ 4 | ordinal }} -> 4th
Oh, okay, that's easy
yep, super easy
Is there a way to change the state "unavailable" to something else (ex: away)?
I have a HC-SR04 finding the "presence" of the car in the garage. But when the car it's out, the distance goes far beyond the range of the HC-SR04.
It sounds like you just need a simple template:
iif(is_state('sensor.car_in_garage', 'unavailable'), "away", states('sensor.car_in_garage'))
Or something similar
If you want a binary sensor instead that you'd need to tweak it
This template condition is currently true: {{ is_state_attr('light.mh1_light_group', 'rgb_color', (255, 251, 247)) }} -- how could I check a range on say the blue component so that the condition would be true between 240-255?
I'm having hard time building stateful automations as the read state attributes seem to be always off-by-one from those I have set earlier. Doesn't matter if it's done by rgb, xy or hs.
{% set t = now() %}
{"sessionId": "{{ trigger.event.data._intent.sessionId }}", "text":
"Today is {{ t.strftime('%A %B {0} %Y').format(t.day | ordinal) }}"}
oh wow, thank you!
Hello.
Is there anyone here who can help me with a "template" for wifi connection
how do you set up the group sensor so that it knows if all are true then X, if some is true then Y?
Working from memory here if you go to helpers and create a group I believe it's an option that you can turn on or off
Am I going about this right? I have 2 parts - one is an input helper if I am home or away and one input helper if my wife is home or away, I'd like a group that is "everyone is home" if both input helper's are home, or someone is home if only one of us is?
so I have 3 ways to tell if I'm home or not, 3 slightly different ways to see if she is
both toggle a drop down menu/input helper
i'd like the status of those helpers to be the "All are home" or "some are home" factors
I didn't see that last I checked, looking again!
Should be under group Behavior
Hi! I would like to create a template, that convert a percentage value to number. I would like to set a min max value (like min 30, max 45) and the percentage is 0-100%
any idea how to make it?
the percentage and the output number is a entity
That's just math
{% set min = 30 %}
{% set max = 45 %}
{% set percentage = 75 %}
{{ min + (max - min)*percentage/100 }}
replace 75 with states('some.entity') | float
back home (sorry bout that, my daughter had her MSc Econometrics graduation today, big party!). here's the code https://dpaste.org/GF6yM
note I still have the former default, and had tried both single and multi line notation. that all means nothing really, was just looking for a way to be more efficient. Maybe split the 2 days into separates? that way at least we would only have issues on the 'tomorrow's hours
Yeah, not much you can do with that
You could make it a template sensor using a trigger to cut it down but itβs not worth it
sorry, had a few typos there... this now works: https://dpaste.org/TXvzU and not sure yet when, but I guess the errors start at daybreak, when tomorrow is only available after 16:00..
what would that be like? trigger at time 16:00, and then...?
Put the result in a single sensor as an attribute, then use a trigger that updates based on the attribute. Then make variables that call out the index. Like I said, itβll cut it down but itβs not worth the effort
a yes, that is clever indeed! cool. and it would prevent all of these errors, I like that.... will see tomorrow. thx Petro πΆοΈ
I don't know anything about the mqtt integration. However, the template will need to navigate the JSON structure you're showing. The temperature value is the `Value` key in an object which is in the `Data` array. The template expression for this would look something like `value_json.Data[0].Value`.
Only in English. Ofc..
Morning, can anyone help me with a sensor template and default state?
I've got this template, but the sensor itself has a state where there it is empty, in this case it shows as unavailable, I want to swap that so unavailable = another name
- name: Heating System State
unique_id: heating_system_state
icon: mdi:thermostat-box
state: "{{ state_attr('climate.holly_house', 'preset_mode') }}"
stuck here.... trying to do:```
sensor:
- name: Energieprijzen
value_template: "ok"
json_attributes_path: "$.ArrayOfEnergyTariff"
and that does create the sensor, but is contains no attributes. also triedjson_attributes_path: "$"```If I want it to list the full ArrayOfEnergyTariff
based on resource_template:```
- resource_template: >
https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs?startTimestamp={{now().strftime('%Y-%m-%d')}}&endTimestamp={{(now()+ timedelta(days=2)).strftime('%Y-%m-%d')}}
translates to
https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs?startTimestamp=2022-10-14&endTimestamp=2022-10-16```do you have a suggestion how to get the attribute show that full array?
Hi, rest has a value_template for the state... is there also an option to use value_template for the json_attributes_path ? I need this as my file changes of content/structure each 5mins and the info I need may be on any index, I use the value_template to iterate through which works fine....but now I need also the attribs. If no template, can I posisbly pass on the index from the value_template to the path?
Hi there.
I have a question about using a blueprint and its probably more of a general understanding question. I have Home Assistant up and running and have a few devices which I happily use. Now I have a room where I need more than 1 motion sensor to cover the whole room.
Up until now I was using a blueprint that looks like it is in Home Assistant by default. It's called Motion-actived Light and is found at config/blueprints/homeassistant/motion_light.yaml (http://pastie.org/p/7dOLabVp5MyOG79HsFuvrJ).
It has been doing what I want until now ... Turning on a light when motion is detected and turn off light after motion sensor is clear for x seconds.
As said I now need 2 motion sensors. I though I just make a group. I created a Binary Sensor group and added the two motion sensors. Now I cannot use this group in the blueprint above. Just not showing up.
Now is it not showing up because the blueprint has a specific class for the motion_entity (domain is binary_sensor, device_class is motion) and the broup is just in the domain binary_sensor but does not have the proper device_class?
If this is correct. Should I copy this built in blueprint and create a new one without the device_class? Or do I need to do it differently?
Any tips appreciated. I haven't found anything specific to this via Google. If my Googling skills are lacking ... I'm happy to get a link where I can read more about it. Still new with blueprints.
From node red I get a timestamp that looks like this 1665755149166, HA recognise it as a number. How can I use it with as_timestamp?
{{ state_attr('sensor.node_red_test', 'timestamp') | timestamp_local }} renders a ValueError: Template error: timestamp_local got invalid input '1665755149166' when rendering template
Solved it:
{{ state_attr('sensor.node_red_test', 'timestamp')| multiply(0.001) | round(0) | timestamp_local }}
copy and modify is the way. Consider taking conversation to #blueprints
Is it possible to remove one entity_id from a group with the "Group: Remove" action or is it only for removing a group as whole?
Trying to create a light template that when brightness dimmed, it will warm the lights accordingly. This is what I got so far, nothing works except for turning it on and off.
Did you look at the Flux integration? Because that might solve your problem
Well, the flux integration is timed based, im trying to build something that I can manually control...
I think you'll need an integration (custom or native) rather than a template. I don't think you can do what you're trying to do with a template at all actually
Hmm alright thanks!
It's removing it as a whole
You can take the entire entity_id list, reject the one you don't need and use that to set the group
I've also seen a WTH requesting a service for it
This is what I have for that:
https://github.com/TheFes/HA-configuration/blob/main/include/automation/00 general/brightness_color-temp.yaml
It matches color_temp on a change of brightness, not the other way around
Thanks! How could I implement this rejection?
Would be helpful if the Set service would have an option to remove an entity just like it can be used to add one.
- alias: "Remove entity from group"
service: group.set
data:
object_id: some_group
name: "Group name"
icon: mdi:play-box
entities: >
{%- set g = 'group.some_group' %}
{%- set current = state_attr(g, 'entity_id') | default([], true) %}
{{ current | reject('eq', 'some.entity_id') | list }}
Ah, if it's an array, you have to use a command line sensor to get around it. @toxic dome posted something using a command line sensor on the forums a while back that circumvents the issue with rest attributes & a list coming from the endpoint
Thanks a lot!
Ah yea, train lines one. @floral shuttle take a look at this: https://community.home-assistant.io/t/how-to-extract-data-from-json-again/449271/22?u=centralcommand. Similar technique should work, basically use curl instead of a rest sensor and then have jq to wrap the response in an object
Actually that should probably be a WTH come to think of it
Thanks for this, I did it with automations instead with an input_number and created a light template with that input_number and it worked pretty well!
Itβs not hard to template that whole field. I looked into it
json_attributes? That would be nice
It should probably be a separate field, like attributes template. Mutually exclusive with json attributes.
Alternatively could stick a post processing template in between like Mqtt sensors have. Something that runs on the output before it gets handed to the state and attribute handlers
I didnβt want to do the PR because he would have to be deployed in six places
Example?
I'm thinking of Mqtt availability actually, my bad. Where the value is compared to payload_available or payload_not_available but value_template can modify it first
So I guess I don't have a good example of this. But was thinking of a field like output_template which modifies what actually comes from the rest API and sets value for the templates that follow. Idk if that's easier though
thanks for the answer. Sry for wrong channel. I though I selected blueprints. My bad.
any idea why this templete won't work for me anyone?
{{states.sensor|selectattr('attributes.device_class', '==', 'battery')|selectattr('attributes.unit_of_measurement', '==', '%')|list}}
Yes, you need to check if the attributes are defined
{{ states.sensor |selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'battery') |selectattr('attributes.unit_of_measurement', 'defined') | selectattr('attributes.unit_of_measurement', 'eq', '%') | list }}
is that a recent change? it used to work with the shorter line
And this will list the complete state objects, if you need entity_ids, you need to map those
Uhm, few months I guess
excellent, thanks
Does Somebody got a better method then the Statistics, HADailySensor etc to see Min and Max Temp of the Day (History not needed, and takes Data what is already there and not just starts when the sensor got created or resets itself by an restart)?
those are the best methods, especially if you want the value to survive restarts.
I would like to see which device an entity belongs to. When I tried it a year ago or so it was said you can't do that, but I am under the impression it is possible now.
The end game is to list all entities with state = unavailable, get the devices from that list and then remove the duplicates.
So instead of a list like "sensor.adguard_parental_control_blocked, sensor.adguard_safe_browsing_blocked, sensor.adguard_safe_searches_enforced, sensor.bw16a01_current, sensor.bw16a01_power_2, sensor.bw16a01_power, sensor.bw16a01_voltage" I would get "Adguard Home, StrΓΆm till fΓΆrstΓ€rkare i kΓΆk" (the device/integration names).
Since we got the "related device" now, I assume it is possible now. Any ideas how?
thanks petro
This has actually been possible for a long time, so whoever you asked just didn't know how to do it
{%- set devices = states | map(attribute='entity_id') | map('device_id') | unique | list %}
{%- set ns = namespace(items = []) %}
{%- for device in devices %}
{%- set unique_states = expand(device_entities(device)) | map(attribute='state') | unique | list %}
{%- if unique_states == ['unavailable'] %}
{%- set ns.items = ns.items + [ device_attr(device, 'name') ] %}
{%- endif %}
{%- endfor %}
{{ ns.items }}
that's if they are all unavailable
(all entities)
in the device
if yuou want devices where any entity is unavail..
{%- set ns = namespace(items = []) %}
{%- for device in states | selectattr('state','eq','unavailable') | map(attribute='entity_id') | map('device_id') | reject('none') | unique %}
{%- set ns.items = ns.items + [ device_attr(device, 'name') ] %}
{%- endfor %}
{{ ns.items }}
That is just awesome. Thanks!
hey all, im trying to create a trigger based on a temperature change, rather than an above or below
something like if the temperature drops by more than 10 degrees oC, this is the trigger, regardless of what the temperature is
create a template binary_sensor to represent that and use it as the trigger
or a state trigger and a template condition comparing the trigger.to_state.state and trigger.from_state.state
I'm not sure what kind of help you're looking for
ok this is great! Here's what I'm trying to solve. I have a clothes dryer automation, that starts a time and stops a time and then announces its done and provides an estimated time to completion.
Problem is because the dryer is electric and 240 V, I can't monitor the power consumption (at least not easily), so I simply bought a temperature sensor and placed it in the vent
it works, say if trigger to start is temp above 27oC, and trigger to end, temp is below 50oC
BUT sometimes, the temp drops in the beging, from say 52oC then to 48 oC
then goes back up and stays up
however, the dry has a cool down period, so it drops steadily from 60oC and then turns off at around 50oC
im trying to capture that 10oC drop from 60 to 50oC
binary_sensor:
- platform: trend
sensors:
temp_falling:
entity_id: sensor.outside_temperature
sample_duration: 7200
max_samples: 120
min_gradient: -0.0008
device_class: cold
this is the example from docs
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), http://pastie.org/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
what is min gradient?
min_gradient string (optional, default: 0.0)
The minimum rate at which the observed value must be changing for this sensor to switch on. The gradient is measured in sensor units per second.
just that
another paragraph there on it:
A trend line is then fitted to the available samples, and the gradient of this line is compared to min_gradient to determine the state of the trend sensor. The gradient is measured in sensor units per second - so if you want to know when the temperature is falling by 2 degrees per hour, use a gradient of (-2) / (60 x 60) = -0.00055
ok, it takes about 6 minutes for the temp to drop from 60 to about 50oC, and the sensor only updates every 61 to 76 seconds
duration: 360
based on your example and my data, gradient would be (-10)/(6*60)= 0.027
-0.027
I'm going dust off the old Ti-89 and do some high school math here. π
Hello, my name is Sebastian and I'm facing a problem that I can't solve myself because I don't have the right idea.
I have a heating valve (NC) that opens in 4 minutes when it gets power. When the current is gone, it closes again in 4 minutes.
I have a sensor for that valve that tells me "power on" and "power off". What I am missing is how to calculate the degree of opening of the valve from this "true" and "false" information in connection with the 4 minutes opening time.
Does anyone have experience with this, or has something similar already been implemented?
I would appreciate a tip on how to implement something like this. I'll be happy to fumble my way through it, but at the moment I don't have any idea where to start.
I suppose this is the operative part of your question, but I don't know what you actually want:
how to calculate the degree of opening of the valve from this "true" and "false" information
you want a binary_sensor that only reflects on or off if the valve is open or closed, taking into account the 4-minute delay?
the opening time of the valve is 4 minutes. So it takes 4 minutes until it is fully open. And if the power is gone, it takes up to 4 minutes to close it again. I want to calculate the degree of opering with that information. So if the power is on for 2 minutes, the template sensor should go linear from 0% to 50% in the two minutes, and then back to 0% in the next two minutes.
(Think of it as a garage door opener. I want to calculate the opening position of the door with the running time. The only difference is that the valve is auto-closing agian after the power is gone).
As I think of it, it needs to be a counter. I need to increment the counter by 0,0041666666666667 every second if the state of the binary sensor is on and decrement by the same value every second it the binary sensor is off. Don't go over 1, don't go under 0 and show that as "%".
You could do that, yes
Ok, will try.
hello
Does anyone know how to put a variable here {%set cons_price = 0.228080389 | float %}
in such a way that the price of "0.228080389" is {%set cons_price = variable | float %}
Where that variable is the value of this sensor "sensor.esios_pvpc" I am in the regulated market so I am interested in having that variable that varies as you know every hour and every day.
{% set cons_price = states('sensor.esios_pvpc') | float(default=0) %} probably
ok, tnks @rustic moat
I probe now , and it not work
{% set cons_price = states('sensor.esios_pvpc') | float(default=0) %}
that's how it would be done, so you'll have to expand on "it not work"
sorry, if i change this line , The sensor change a not available
sorry and thanks, i tried again, and now it's work fine
I have created a weather template and it works great as a card. Would anyone be able to help me figure out how to get that info to report to my rhasspy instance? I was able to figure out how to get it to report the temperature, but i am unsure how to add the forecast as an intent script. Any help would be super amazing.
I want to change the outcome of this sensor
{{ (states('sensor.solaredge_ac_power')) | float / 1000 | round(2) }}
5.465
to 5,5 but i have no idea how to accomplish this π Any help?
You are now rounding 1000
You need to use parenthesis to round the result of the calculation
Basically you need to move the ) you already have to after the 1000
And you need to use round(1) instead of round(2)
That did it π Thx @marble jackal
Can anyone help me template this. I want to do something like if sensor1 is less than sensor2 and sensor3, I can't work it out
sensor1 < sensor2 and sensor1 < sensor3
Or [ sensor1, sensor2, sensor3 ] | min == sensor1, but that will also be true is the states are equal to each other
I now see your post in #automations-archived You also need to convert the states to a number, as the string comparison "10" < "5" will result in true
As simple as that, I'm sure I tried just using 'and' but must of got something else wrong, thanks very much
i got confused and running around in circles. What is the the proper way to setup home not_home presence detection? I got multle device_tracker.xxxx i would like to combine to either a home/not_home sensor OR a binary OFF/On sensor. Any tips?
because old style grouping is just putting all device trackers entities in the config. But new style doesnt have that? only binary/fan/light etc
so do i first need to make a home/not_home into a binary on/off sensor for each device tracker and put those into a group then?
awesome_people:
name: "Awesome People"
entities:
- device_tracker.dad_smith
- device_tracker.mom_smith```
is this still valid or being phased out?
Still supported, but it's encouraged to move to the new style
but how.... bundle up multiple device_trackers to one single home/not_home ...?
i cant find a group in the helpers menu to bundle up multiple device trackers
i would like to bundle person.joe and a couple of device-trackers made with ping to a single entity.
in helper the input_number slider has no setting for steps of 0.5? or is their a otherway of doing it?
you can type whatever you want
but the slider only allows me to change in steps of 1
if i use ping as device tracker, why shoud i bother. I might as well make it a binary sensor straight away to be used as presence detection?
else its an extra step: having to template a ping device tracker home/nothome to binary anyway so it seems
correct me if im wrong
running around in circlesss....β»οΈ
Ohh wow, the column turn red for me when i type 0,5 and that got me to think its not accepting the value but it does when clicking update. Thanks!!
How can I add a template switch through the GUI? Or is it only possible through yaml files?
you can only do that by editing YAML
YAML? More like YUML amirite
I have a Multi meter sensor I want to export to a Google Sheet using template in the data field of an automation but I simply cannot get the "number" out (I try to show it in the Demo template) :
{{ States('sensor.mileage_sensor') | float(0) }} but 'States' is undefined
@ember wagon it's states(), so lowercase s
Thanks a lot
testing this kills my instance...... First had the top template (took a few seconds for it to return an output) then added the seconds and it is still spinning, and can not open any view.....
it iterates all states
it's going to be 'heavy'
yeah, heavy is ok. But this is not ok. It's still locked....
look at your logs
I can on my system
missed this before, so sorry. I had another go, because I was pointed to an XML to JSON converter (whihc does seem to work) but still endup here: https://community.home-assistant.io/t/struggling-with-restful-sensor/456515/11. Somehow the root of that resource outcome seems to be 'deeper' than I had hoped it to be?
also, I had a look at that train config, but wasnt successful in re-writing my resource rest sensor to that format
I told you it wasn't worth it
I pasted both in devtools > templates, and although a bit slow (like half a second or so) they load fine here
you have to make all separate trigger entities. Your config might be largely the same number of lines, but you'd only have to edit 1 template.
and, you'd still need to maintain indexes
TLDR: Not worth it
Hmm, I was a bit too soon, my HA is not responsive anymore
hehe, wait 5 minutes and it ll restarts....
trying ha core reboot from ssh, but that is processing already some time now
as said, I am mainly trying to prevent the errors, its not about making the config smaller
individually these templates render fine (first is a bit slower than the second), together in the dev tools templates is a no-go. btw, I now discover on the second template, that is returns devices that are disabled, or, at least not listed in my devices list. That means that the backend template engine still sees these devices. That seems unexpected..
nope, it's by design if the device is ever found again and you had settings associated with it.
delete the device (instead of disabling it) and it won't be in the registry
I have an integration (Greenley) that gives a sensor that gives me the total daily usage for the day before and a json (i assume) list of the past week or so. Is there anyway to convert this into a long term sensor so that i can track the energy usage over a longer period of time
no
Currently, there are issues related to past historical data being put into HA. So if you did make this sensor available in the energy tab, the data would be off by the offset presented in your sensor
i.e. it would be off by a day if it was yesterdays reading.
No it doesnβt need to be connected to the energy tab (currently it isnβt). I have my own energy dashboard based on a couple of sensors using apex charts. Also it doensβt need to work historically. Itβs fine if it starts recording today and keeps going forward
Then just use the rest sensor or command line sensor to get the data in
Ive checked, and it only listed the deletable ones, many non-available s can not be deleted, because somehow the integration (Zwave in this case) seems to provide them... which is nice.
1 ask: could a generic deselect be made for devices like: 'S1b7898d3b6995169C 0A98' ? its the new iBeacon adding countless numbers of them, and they can be left out of this template. Theyre all different, but all have that same format.
'e20a39f4-73f5-4bc4-1864-17d1ad07a962_14390_4928 BF3D', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_19899_45253 6848', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_28553_1869 942E', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_4280_54190 4E26', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_54087_18166 F99F', 'e20a39f4-73f5-4bc4-1864-17d1ad07a962_64939_32411 4A16', 'e2c56db5-dffb-48d2-b060-d0f5a71096e0_0_0 047D', 'e2c56db5-dffb-48d2-b060-d0f5a71096e0_0_0 A8BE', 'FM One 1DF2', 'N/G 3718', 'S004045e768eb6f4dC C079', 'S03181b8f78355fe7C BEC4', 'S08207288b7a9c3b1C 7A8E', 'S0aed85c7d2389efeC 1BB2', 'S148a80e3ccda0a8bC 9081', 'S1b44953c1369ed2bC A36E', 'S1b7898d3b6995169C 0A98', 'S1d5aeec4c46d00e4C 017B', 'S1db85daeccf8c99bC 52F5', 'S21296737cf94afa5C 0455', 'S282d1c03285b1515C 3CCB', 'S2f4f11eef8a6fc92C 53AF', 'S38cad119ce1bf536C 6DA9', 'S3f29ce079172f647C D463', 'S42d91114c625f57dC C566', 'S42f3df7c2906429eC 4895', 'S433830d79a4d7050C 1836', 'S467b41fad282209eC 8C7D', 'S46a05f68fa464ea6C D2F8', 'S5065772242e550dbC 3B85', 'S51b9b328b91f37faC D88C', 'S52e5ae6e3421bb24C 49ED', 'S52f1e90afdfa9744C 3AAB', 'S58613499bca50161C B0CC', 'S5ba9456074306d18C 6543', 'S674759cfd93190a6C B74C', 'S6d868b971490996dC D2D1', 'S6f5882d43c53dba8C 3F4A', 'S76a4a43f75359d6dC B0D9', 'S776c5be44a92ad49C 38F3', 'S793afd1c93410333C F8F1', 'S8d2f31624c12649fC FFA6', 'S8f4b1a9fcdba0cbcC 7E7B', 'S966f48237b39c82eC 3910', 'S9cbb50678687492aC 44A2', 'Sa0830c5e68ce1e07C 22CB', 'Sa1b7a71a16ba3776C 36B1', 'Sa4d8dc271f1aab5dC 248B', 'Sa782c856a9b0e0cfC C382', 'Sa8fb66b51b39f0e3C 4995', 'Sacbe70f70f5afe10C 95FD', 'Saf3a4f597f1dd28dC 0EC8', 'Sb0bd1432249097c8C 8474', 'Sb35d3b8190e670d6C 11BC', 'Sbb9ddbd23acf3941C AD64', 'Sbbad443d68604c82C C25D', 'Sbdfdaafe9308b12dC C739', etc etc
the ones that dont have that format standout immediately π
Is there documentation on how to do that?
Isnβt that whatβs already being done though? Itβs showing yesterdays data an updates once a day. How do make it so that it saves it for longer
Well so that i can create a graph (thatβs showing a months data) with it
if you want normal history graph, you have to increase your database collection period to beyond 10 days
but that will be for all of your history
Is that the norm for every sensor?
yep
And i canβt create a sensor that has a longer retention specifically?
nope
yep, use influx or something else
before you ask, no i don't know how to set that up
Yeah i was trying to avoid that. Since the integration somehow saves the last week i was hoping i could reuse that. But it seems to be too much work
$.ArrayOfEnergyTariff isn't the correct path based on that post if you want the list of energy tarriffs. The path you want is $.converted.ArrayOfEnergyTarriff. converted is the outermost object field, everything else is inside it.
I did try: - name: Energieprijzen value_template: "Ok" json_attributes_path: "$.converted.ArrayOfEnergyTariff" json_attributes: - EnergyTariff but figured the 'converted' bit was caused by the converter (...) and not part of the real outcome of the resource. It doesnt help. No matter what I enter there, it remains an empty list, until I start using the path '$[x]'
Does the API give you back xml or json?
XML I would think
just throw this is the browser: https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs?startTimestamp=2022-10-17&endTimestamp=2022-10-18
Oh. That's going to be extremely difficult to use then. Sorry I thought you had found some way to turn xml into json on the fly
You definitely cannot use a rest sensor with xml, that'll never work. You also can't use Jinja templates, they have no support for xml either.
The only way I can think of is a command line sensor that ssh's to another machine which has xq installed. Do the curl there and pass the response to xq
but this works perfectly:```
- name: Energieprijs uur 0
value_template: >
{{not important value}}
json_attributes_path: "$[0]"
json_attributes:
- TariffReturn
- TariffUsage
- Timestamp
does that at least make sense?
Oh. I'll be damned. Rest sensor converts xml to json. I totally forgot that
So it looks like HA uses xmltodict to do that looking at the code of the rest sensor (https://pypi.org/project/xmltodict/). So if debugging what's going on I would do the conversion with that library and not another tool
Dump the response into a file, read that file in Python and run that on it just like HA would, see what it looks like. Or make the API call from python if you prefer
Oh nvm you don't have to, just turn on debug level logging for homeassistant.components.rest.sensor. it logs exactly what the xml was converted to at debug level: https://github.com/home-assistant/core/blob/326a1b21ca204fd3c590d0e467a2be2caa57971f/homeassistant/components/rest/sensor.py#L144-L145
ok let me try that!
well, this is what is logged: 2022-10-17 17:32:51.405 DEBUG (MainThread) [homeassistant.components.rest.sensor] Data fetched from resource: [{"Timestamp":"2022-10-16T22:00:00+00:00","SupplierId":0,"TariffUsage":0.139857900000000000,"TariffReturn":0.12831},{"Timestamp":"2022-10-16T23:00:00+00:00","SupplierId":0,"TariffUsage":0.124706900000000000,"TariffReturn":0.11441},{"Timestamp":"2022-10-17T00:00:00+00:00","SupplierId":0,"TariffUsage":0.115158500000000000,"TariffReturn":0.10565},{"Timestamp":"2022-10-17T01:00:00+00:00","SupplierId":0,"TariffUsage":0.097707600000000000,"TariffReturn":0.08964},{"Timestamp":"2022-10-17T02:00:00+00:00","SupplierId":0,"TariffUsage":0.085270700000000000,"TariffReturn":0.07823},{"Timestamp":"2022-10-17T03:00:00+00:00","SupplierId":0,"TariffUsage":0.110449700000000000,"TariffReturn":0.10133},{"Timestamp":"2022-10-17T04:00:00+00:00","SupplierId":0,"TariffUsage":0.134080900000000000,"TariffReturn":0.12301},{"Timestamp":"2022-10-17T05:00:00+00:00","SupplierId":0,"TariffUsage":0.168045300000000000,"TariffReturn":0.15417},{"Timestamp":"2022-10-17T06:00:00+00:00","SupplierId":0,"TariffUsage":0.198837800000000000,"TariffReturn":0.18242},{"Timestamp":"2022-10-17T07:00:00+00:00","SupplierId":0,"TariffUsage":0.175599000000000000,"TariffReturn":0.16110},{"Timestamp":"2022-10-17T08:00:00+00:00","SupplierId":0,"TariffUsage":0.149112000000000000,"TariffReturn":0.13680},{"Timestamp":"2022-10-17T09:00:00+00:00","SupplierId":0,"TariffUsage":0.149820500000000000,"TariffReturn":0.13745},{"Timestamp":"2022-10-17T10:00:00+00:00","SupplierId":0,"TariffUsage":0.134091800000000000,"TariffReturn":0.12302},{"Timestamp":"2022-10-17T11:00:00+00:00","SupplierId":0,"TariffUsage":0.143956300000000000,"TariffReturn":0.13207},{"Timestamp":"2022-10-17T12:00:00+00:00","SupplierId":0,"TariffUsage":0.149624300000000000,"TariffReturn":0.13727},] etc etc
so it seems it does start at the [0] level, and not the ArrayOfEnergyTariff level.
its a nasty beast, I figure I have to forget about.
unless you'd think (with me) this is a bug, and I will file an issue...]
the 'JSON converted from XML' is not logged at all btw
What's there in the log is JSON
It's invalid JSON, presumably because we only have part of it, but it's JSON
@toxic dome I converted your message into a file since it's above 15 lines :+1:
Right. course you also lost the mention bot friend lol. @floral shuttle take a look at that output there. I hit the API in curl
You can see its actually returning JSON, not XML
The API appears to return the response in different formats depending on the headers passed in
Yea in Firefox I just used the console to see what it sends. Here's the Accept header browsers provide:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
curl on the other hand sends this:
Accept: */*
Haven't found where HA sets Accept but I would guess it lists XML after JSON since it prefers JSON. I think the API prefers to return JSON but returns XML if its the only one supported or preferred (like browsers specify)
Of course the JSON it does return is a top-level array which then can't be stuffed into an attribute. So @floral shuttle I guess this leaves you two options:
- Switch to a command line sensor and use this technique: https://community.home-assistant.io/t/how-to-extract-data-from-json-again/449271/22?u=centralcommand
- Set the
Acceptheader in the REST sensor (https://www.home-assistant.io/integrations/sensor.rest/#headers) to prefer XML over JSON and then do what what you're trying to do
I have an energy meter helper for my power meter reader (Rainforest Eagle 200), to give me daily usage (resets daily). I have a template to apply my power rate cost and spit out a daily usage cost. When the day rolled over this morning the template did 1 update ($0.02) and then stopped updating. I've restarted HA but no updates.
- platform: template
sensors:
daily_energy_cost:
# unit_of_measurement: '$'
friendly_name: 'Daily Energy Cost'
# icon: mdi:currency-usd
value_template: "${{ (states('sensor.daily_energy_usage') | float * 0.13609 ) | round(2) }}"
Ok let me take that back. So I was getting a line graph for that sensor last night and I left it open over night, which is where I saw the $0.02. Now have one of these graphs...
Ok now I'm getting both. https://imgur.com/a/qx0nrfh
ah I think I understand. Getting rid of unit_of_measurement and tossing in the dollar sign into the value_template was messing it up.
Next question is, how do I get HA to represent $ as a unit of measurement and have it shown before the value of a sensor?
I've tried both $ and USD for unit_of_measurement but both appear after the value.
You can't
But you can use custom cards to template how it's shown on your dashboard
But that's something for #frontend-archived
Is it possible to make a template sensor from the GUI?
No
Thanks
Is there a way to set a state value as an attribute at a certain time? I'd like to add an attribute to some of my sensors that stores a historical value so I can easily compare data. I have hourly, daily, and monthly sensors that I'd like to capture the last value before it resets and store it as that attribute. Is this possible?
no, you cannot programmatically add an attribute to an existing entity like that
you can create a template sensor that records the previous state
The sensors I'd like to add to are already template sensors.
I already have an attribute for kwh cost added to them
then you can make them trigger-based template sensors and use trigger.from_state.state one of the attributes
thx for your patience, but this is going nowhere. The header: settings does not make any difference, as they still are transformed to JSON. Ive tried all 3 xml options. The command_line has me guessing on all details. I cant find the correct syntax for either the command or the path/attributes... Trying all of this in the terminal, and it keeps throwing errors on parser near this and that, or no matches found ....
I lied, only some of them are. The others are utility_meter sensors. I'd have to convert those.
- trigger:
- platform: state
entity_id: input_number.foo
sensor:
- name: test
unique_id: test_sensor
state: "{{ trigger.to_state.state }}"
attributes:
old_value: "{{ trigger.from_state.state }}"
Strange. When I did this just now I got back this XML:
# curl -H'Accept: application/xml' https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs\?startTimestamp\=2022-10-17\&endTimestamp\=2022-10-18
<ArrayOfEnergyTariff xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/GreatValue.Common.Models.Tariffs"><EnergyTariff><SupplierId>0</SupplierId><TariffReturn>0.12831</TariffReturn><TariffUsage>0.139857900000000000</TariffUsage><Timestamp xmlns:d3p1="http://schemas.datacontract.org/2004/07/System"><d3p1:DateTime>2022-10-16T22:00:00Z</d3p1:DateTime><d3p1:OffsetMinutes>0</d3p1:OffsetMinutes></Timestamp></EnergyTariff><EnergyTariff><SupplierId>0</SupplierId><TariffReturn>0.11441</TariffReturn><TariffUsage>0.124706900000000000</TariffUsage><Timestamp xmlns:d3p1="http://schemas.datacontract.org/2004/07/System"><d3p1:DateTime>2022-10-16T23:00:00Z</d3p1:DateTime><d3p1:OffsetMinutes>0</d3p1:OffsetMinutes></Timestamp></EnergyTariff><EnergyTariff><SupplierId>0</SupplierId><TariffReturn>0.10565</TariffReturn><TariffUsage>0.115158500000000000</TariffUsage><Timestamp xmlns:d3p1="http://schemas.datacontract.org/2004/07/System"><d3p1:DateTime>2022-10-17T00:00:00Z</d3p1:DateTime><d3p1:OffsetMinutes>0</d3p1:OffsetMinutes></Timestamp></EnergyTariff><EnergyTariff><SupplierId>0</SupplierId><TariffReturn>0.08964</TariffReturn><TariffUsage>0.097707600000000000</TariffUsage><Timestamp xmlns:d3p1="http://schemas.datacontract.org/2004/07/System"><d3p1:DateTime>2022-10-17T01:00:00Z</d3p1:DateTime><d3p1:OffsetMinutes>0</d3p1:OffsetMinutes></Timestamp></EnergyTariff>...</ArrayOfEnergyTariff>
yes, me too π now let me try to template those timestamps to startTimestamp={{now().strftime('%Y-%m-%d')}}&endTimestamp={{(now()+ timedelta(days=1)).strftime('%Y-%m-%d')}}
btw, in a command_line sensor, what would be the path? Is there a special syntax to have it throw all of the ArrayOfEnergyTariff into the attribute?
sensor:
- platform: rest
name: Energy Tariffs
resource: "https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs"
value_template: "ignore me"
params:
startTimestamp: "2022-10-17"
endTimestamp: "2022-10-18"
headers:
Accept: "application/xml"
json_attributes_path: "$.ArrayOfEnergyTariff"
json_attributes:
- EnergyTariff
This just worked for me
@floral shuttle
o wow, bingo! Ive templated the timestamp to: params: startTimestamp: "{{now().strftime('%Y-%m-%d')}}" endTimestamp: "{{(now()+ timedelta(days=1)).strftime('%Y-%m-%d')}}" and now can do {{state_attr('sensor.energy_tariffs_rest','EnergyTariff')[23].TariffUsage}} πΆοΈ πΆοΈ
now only thing left is to find a an availability template for [24] to [47] ... and create that trigger template sensor to only trigger after 16:00 and condition on their existence...
this is huge! thank you so much.
np
honestly had no idea rest sensors worked on xml so that's cool in a pinch too. Plus it means xmltodict is available if necessary without sshing for xq
btw, as comand_line:```
- platform: command_line
unique_id: energieprijs_command_line
name: Energieprijs command
command: >-
curl -H'Accept: application/xml' https://mijn.easyenergy.com/nl/api/tariff/getapxtariffs\?startTimestamp={{now().strftime('%Y-%m-%d')}}&endTimestamp={{(now()+ timedelta(days=1)).strftime('%Y-%m-%d')}}
value_template: OK
json_attributes:- ArrayOfEnergyTariff``` it errors on not being able to parse as JSON, but I can see te correct Array being returned.
Unable to parse output as JSON: <ArrayOfEnergyTariff xmlns:i= etc etc
so its already in the command to use the xml, but it doesnt accept it just yet.
have you tried escaping the dollar sign?
\$
unit of measurement is nothing special, it's just a string according to here:
https://community.home-assistant.io/t/list-of-valid-unit-of-measurement-options/299209/4
It will show after the amount
Hey there. I have a value_template that is throwing a fit, so I'm guessing I am coding it wronge :(. I want it to only return true if ".." exists in states field... Here is what I have:
{% if states('input_text.bypassed_zones').count('..') = 1 %}
Can I count a text in the state? Am I doing it wrong?
I am using count because I am going to have it more complicated when all said and done. So, I really do want to count how many occurrences of ".."
{% set test = "foo...bar...petunia" %}
{{ test.count("..") > 0 }}
that results true
your template only returns true if it is exactly 1, in my example it is 2, so your version would return false
Oh, and you need to use ==, not =
Great π I actually wanted exactly one. I miss worded the question. Because then I am going to have another if >1 π
So was the real problem just because I didn't use == I wonder?
Yes
Perfect! Yep, I just tested it! Thank you!!!!
how does one use an availability template in a platform that errors with not supported. I.e.: https://www.home-assistant.io/integrations/imap/
how do you mean, what is the template which gives errors?
sorry trying to find a working code dump site
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.
value_template and availability are not supported for that sensor
I don't see senders in the docs as well
yeah, it's not an option
just looked at the code
you can use search
@tepid onyx you have to make a template sensor using the imap sensor
sensor:
β - platform: imap_email_content
name: "parcel_notify"
server: imap01.server
port: 993
username: parcel
password: pass
verify_ssl: false
search: FROM <yo@mumma.com>, SUBJECT <Parcel Notification>
Not sure the <> are needed
not really sure as well, just copying the example here π
I'd assume they are required
Hi Guys, I have a remotecontrolled light, which I can also toggle on/off via HASS. Unfortunately the on/off state is not reported, but HASS receives the remotecontrol command.
So I guess I would create a virtual switch, which controls the light, when used via HASS, but also gets changed, when the remote is uses. Is there a template for this or do I need to create one for myself.
Cant imagine this does not exist, but I absolutely do not know what to google π
sorry guys @marble jackal @mighty ledge , I pasted a link to the wrong integration. The correct is https://www.home-assistant.io/integrations/imap_email_content/
senders is a valid option. The code I pasted works fine just not with an availability sensor...
damn time difference
template:
- sensor:
- name: tesal-model-x-rated-range
unique_id: 3a33104e-42d7-4e4e-b705-38437556520c
unit_of_measurement: Km
state_class: measurement
state: >-
{{ ((states('sensor.sensor.tesla_rated_battery_range_km') | float - states('sensor.sensor.tesla_battery_level')) * 100) | round }}
I have made tis code but is shows up as unavailable
when i start a timer, can i trigger at a certain time?
I see idle/active etc, but not a time
dashbord entities timestamp to ddmmyyyy_hhmmss
You can send duration in the service call data
hey, I'm having a look at an example that looks like this label: '[[[ return states["sensor.lumi_lumi_weather_temperature"].state + "Β°C" ]]]'
why is he using [] and not {} ?
it's from a frontend card, and it's Javascript
End goal:
Price per month (nice to have is graphs for days as well. Not sure if graphs need daily entities or if they can use monthly. Without the energy dashboard.
What I have got:
- Nordpool entity for price per hour
- Power sensor that have 3 entities: Current power draw (W), current hour draw (kWh) and what i assume is daily power draw (kWH) seeing my price depends on the hour I need to look into current power or hour draw..
I'd like to use the entities in several cards so I'd like to move away from energy dashboard (which i know shows what i want to). Kind of lost what to Google, especially combining the hourly price with hourly usage and integral it. I understand I basically want to do what the energy dashboard already does (energy used + price entity)
Have a look at the utility meter
Utility meter in GUI only gives me the integral power usage. Cant use it to do power usage * current price
So i kinda assume I need my own integral template sensor in order to do that and then use several utility meters to reset it? But I'm quite lost for the first integral template.
Anyone know why my template is stating an error that no default was specified? It seems to run okay but gives: "Error evaluating 'template' trigger for 'HVAC Fan: living room and bedroom temp differ less than 4 deg then fan auto': ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ (states('sensor.motion_sensor_2_temperature') | float) - (states('sensor.t6_pro_z_wave_programmable_thermostat_air_temperature') | float) < 4 }}' but no default was specified"
one of your sensors has a state of "unavailable"
and you didn't provide a default
perhaps this will help (pinned in this channel): https://community.home-assistant.io/t/updating-templates-with-the-new-default-values-in-2021-10-x/346198
Thanks! This helps a lot!
template:
- sensor:
- name: tesal-model-x-rated-range
unique_id: 3a33104e-42d7-4e4e-b705-38437556520c
unit_of_measurement: Km
state_class: measurement
state: >-
{{ ((states('sensor.sensor.tesla_rated_battery_range_km') | float - states('sensor.sensor.tesla_battery_level')) * 100) | round }}
I have made tis code but is shows up as unavailable
I guess changing sensor.sensor.tesla_rated_battery_range_km and sensor.sensor.tesla_battery_level to
sensor.tesla_rated_battery_range_km and sensor.tesla_battery_level is a start.
Then testing the template in Dev Tools
I am trying to get tts to tell me the rain chance for the day. How would I get it to give me the actual percent? Right now i have it setup like this alias: weather test
description: ""
trigger:
- platform: event
event_type: rhasspy_Test
condition: []
action: - service: tts.google_cloud_say
data:
entity_id: media_player.livingroomtv
message: >-
{% set forecast = state_attr('weather.forecast_home', 'forecast')[0] %}
You can expect today to be {{forecast.condition}} with a high of
{{forecast.temperature}} and a low of {{forecast.templow}} and a
{{forecast.precipitation_probability}} percent chance of rain
mode: single
it only say "and a percent chance of rain" instead of like a zero percent chance of rain
and a {{forecast.precipitation_probability}} percent chance of rain
would become
{% iif forecast.precipitation_probability > 0, "and a {{forecast.precipitation_probability}} percent chance of rain", "" %}
Or something similar
oh ok
(iif is an immediate if: https://www.home-assistant.io/docs/configuration/templating/#immediate-if-iif)
thats is very helpful. thank you
You're welcome π
You could also map different %s to different words if you wanted, e.g. <5%, don't say anything, 5-30% low, 30-60% medium, and 60% high or similar π
oh cool
so i would just replace the line in my automation "and a {{forecast.precipitation_probability}} percent chance of rain"
With the iif example? Probably, though you can use the template editor to check what I wrote actually works
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
ok, when i put it into the template it say unknown tag iif
That's because I used {% instead of {{, etc π
{{ iif forecast.precipitation_probability > 0, "and a {{forecast.precipitation_probability}} percent chance of rain", "" }}
I dont know enough about all this to understand what the new error i'm getting means. "TemplateSyntaxError: expected token 'end of print statement', got 'forecast'"
iif can be used as function or filter, but not like this
It needs parenthesis
{{ iif(forecast.precipitation_probability > 0, "and a {{forecast.precipitation_probability}} percent chance of rain", "") }}
Yeah, I was just experimenting, it would probably just be easier to do:
{% if forecast.precipitation_probability > 0 %}and a {{forecast.precipitation_probability}} percent chance of rain{% endif %}
ok, i think i actually understand those examples!
That would also work
It also doesn't render the template within it in my testing
Basically you don't need to add > 0
If it's 0 it will return false
You can also use
{{ 'and a ' ~ forecast.precipitation_probability ~ }} 'percent chance of rain' if forecast.precipitation_probability }}
awesome! that last one seems to work perfectly
my wife loves it. thank you so much, you both helped me lear quite a lot
There's lots to learn when it comes to templates π
I am very quickly learning that. I know next to nothing about programming so I am slowly learning syntax and logic.
sensei is typing
Can I have a list from all the lights from the Integration 'WLED'?
{{ integration_entities('WLED') | select('search', 'light.') | list }}
This returns me the entities from a device named 'WLED' that's a member from the integration "WLED".
Am I understanding something wrong?
The following works for me: {{ integration_entities('wled') | select('search', '^light\.') |list}}
That returns entities from the WLED integration, not just the single device.
if you only want lights, you can use what slashback wrote, but you don't really need the .
{{ integration_entities('wled') | select('search', '^light') |list}}
the ^ means startswith