#templates-archived
1 messages ยท Page 114 of 1
than in the /config/sensors.yaml file I added the following line
- platform: template sensors: tl_mr6400_b_received_mb: friendly_name: MB Received value_template: "{{state_attr( 'sensor.tl_mr6400_b_received', 'state') }}" unit_of_measurement: MB
the new entity named tl_mr6400_b_received_mb is created but it would not display any value
I tried different value_template but everything gives me error except this one
{{ states( 'sensor.tl_mr6400_b_received') | int / 1000 }}
You're trying to get an attribute called 'state'. It doesn't exist.
State and attributes are different. They just live on the same 'object'.
You can also test things as you go. Look at
> Templates
There are examples in there and you can use it as a playground.
one last question, after saving the file I need to reload script and than restart hass?
Yes. But always check your config before you reload HA.
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
I tried using templates example and in there is was working but in the file is was not...
thank you i'll read that documentation
Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states( 'sensor.tl_mr6400_b_received') | int / 1000", None)])" in "/config/sensors.yaml", line 5, column 0
invalid key: "OrderedDict([("states( 'sensor.tl_mr6400_b_received') | int / 1000", None)])" in "/config/sensors.yaml", line 5, column 0
You still need to wrap it with quotes ๐
thank you mono..
ok I did it
value_template: "{{ (states( 'sensor.tl_mr6400_b_received') | float / 1000000) | round(2) }}"
thank you!!!
FYI you don't need to reboot ha. You can go in the Control Server screen and refresh the template entities
and to be accurate you should do /1024/1024instead of /1000000 ๐
Indeed, the source is in Kb/s but the template sensor is in Mb, you may change have to change to make it more consistent @cinder ore
you mean I need to call dev tools -> services -> homeassistant.update_entity ?
No. In the Control Server screen you have the possibility to update the configuration of some configuration elements. Template sensors is one of the elements you can refresh w/o a restart
I only have "Server Management -> Restart / Stop "
Go to your user profile in the bottom left and enable advanced mode.
ah ok thanks
Any templating wizards that know why the name_template does not parse in Lovelace but it does in the Templating Editor (I have the card-templater installed and working). I based this code on the examples on the card-templater Github ๐
`---
card:
entities:
- input_boolean.pvgrafiek
name_template: {{ "On" if states('input_boolean.pvgrafiek') == "on" else "Not One" }}
tap_action:
action: toggle
type: button
entities:
- input_boolean.pvgrafiek
type: "custom:card-templater"
`
(I want other text than On or Off, I just use this as a test-
Well that's invalid YAML, for a start.
You need to escape single line templates with quotes.
Doesn't matter, which is why I didn't specify.
But you'll also need to sort out the mixed quotes you're currently using ๐
so this is better? '{{ 'On' if states('input_boolean.pvgrafiek') == 'on' else 'Not One' }}'
Nope. Think about it... it'll read from left to right. When it sees the second quote, it means that string is finished.
The 'outside' quotes need to be different from the 'inside' quotes.
ow, ok
so line this? "{{ 'On' if states('input_boolean.pvgrafiek') == 'on' else 'Not One' }}"
like*
Ok, now it works, thank you for your help
I'm used to C and Java escaping/quotes and YAML requires different thinking ๐
@wispy bane and @deft timber , there should be a link to update the docs on github on the docs page. Please do if you notice a discrepancy
Is it possible to reference blueprint !input variables within templates? Or do you have to go a bit more long-winded and define them as variables first?
@hexed galleon you have to define a variable first
I want a REST sensor to provide the following in to sensors, how do I do this?
The first mnt_point -> free
The first mnt_point -> used
curl --x http://10.0.24.11:61208/api/3/fs [{"mnt_point": "/", "fs_type": "ext4", "free": 11258875904, "key": "mnt_point", "size": 15247720448, "percent": 22.8, "used": 3318775808, "device_name": "/dev/root"}, {"mnt_point": "/boot", "fs_type": "vfat", "free": 223278592, "key": "mnt_point", "size": 264289792, "percent": 15.5, "used": 41011200, "device_name": "/dev/mmcblk0p1"}] C:\Users\Administrator\Downloads\curl-7.74.0_2-win64-mingw\curl-7.74.0_2-win64-mingw\bin>
Define a restful sensor and in value_template:, set something like "{{ value_json[0].free }}" and another one with "{{ value_json[0].used }}" (assuming the order will always be the same in your json)
Thanks @deft timber ๐ It works.
Yeah, I can make two sensors like that.
But is there a way to do this with just one API-call? To reduce the API-traffic
Yes you can, and you can set the result of the call in the attributes of your sensor
Do you have a recipe for that?
you have to use https://www.home-assistant.io/integrations/rest/#json_attributes
thanks (Y)
Hello everyone, I need some help with manipulating dates in templates.
I have an initial date, say "2021-1-5 00:00:00". Now I would like to add datedelta(days=7) to it.
timedelta, sorry
And one (two) more questions @deft timber :P
- Can I in any way get attributes from both [0] and [1] in json_attributes, I guess not for what google tell, but is there a way or do I just need to make more calls then?
- Can give my attributes a custom attribut name?
Anyway, my working sensor:
- platform: rest resource: http://10.0.24.11:61208/api/3/fs name: Glances - DeCONZ - Disk - all value_template: '{{ value_json[0] }}' json_attributes: - free - used
I'm actually surprised your config works ๐ I would expect the json_attributes to use path from the result of the REST call, not from the value_template result, and thus I'm surprise that the path used for the json_attributes works...
so I can't answer you first question...
I don't think you can custom the attributes names
You'd have to use multiple sensors to have the freedom to name them all the way you want.
apparently, if you just set free as an attribute, HA will get the free of the first element of the collection. If you want the free of the second, you need to set json_attributes_path: '$[1]'
So the conclusion is indeed that you can't get the free from the first and the second element of the collection in the same sensor
@deft timber, can you give me the whole rest-sensor I need? I have tried all kinds of combinations, but whatever I do, If i use json_attributes_path in any way the entity vanish
This is what I used to test :
- platform: rest
resource: http://192.168.0.175/test.json
name: test json
value_template: '{{ "ok" }}'
json_attributes_path: '$[1]'
json_attributes:
- free
worked when I copyed that .. :P
I missed '{{ "ok" }}'
Can "ok" be a value, or just whatever I want? Else ok i ok
it is the value of your sensor, you can choose whatever you want. Hard code or get it from the json as you did.
Hi
Can someone point me to why this isn't this working:
service: rest_command.creeper_msg data: icon: ALARM msg: '{{ state_attr(''sensor.hd1913_last_notification'', ''android.text'') }}' val: '0'
It's just sending through the code of msg instead of fetching the text from last_notification?
Hm.. I saw another guy using it that way directly in his automation, so I tried to do the same.
But I guess, that's not possible?
But android.text is an attribute of last_notification?
Well, got it working in Templates using this code:
'{{ state_attr('sensor.hd1913_last_notification', 'android.text') }}'
Now it fetches what I want to, but how do I now get it into the actual automation?
Then the template is good, and you need to check your log file for any errors, also check the recipient of that REST command to see what it received
Well, I get a visual of what's recieved everytime I run it
I think it's sending the unevaluated template.
Exactly
Which suggests that service doesn't support templates. At least not via the Dev Tools.
Where are you trying it?
I use the REST command to send it to an arduino which outputs the text on an OLED so I can see it all time displaying what I just sent
In an automation in my service for a rest command
REST:
creeper_msg: url: "http://192.168.1.124:80/DisplayMessage?message={{ msg }}&icon={{ icon }}&value={{ val }}" method: POST payload: 'Testing it' verify_ssl: false
And it's when you use it as part of the automation that it doesn't work?
Action in automation:
service: rest_command.creeper_msg data: icon: ALARM msg: '{{ state_attr('sensor.hd1913_last_notification', 'android.text') }}' val: '0'
Triple backticks for better formatting ๐
No, icon and val works fine as intended. But the msg part just sends the unevaluated text as you said.
Ok ๐
data:
icon: ALARM
msg: '{{ state_attr('sensor.hd1913_last_notification', 'android.text') }}'
val: '0'```
Hmm. The docs don't describe POST requests.
Is it possible to use payload: instead of query params?
Well.. I guess that would need me to redo my Arduino code as well I'm guessing
Since that won't be sent the same way right?
It'll be different... but some middlewares interpret it the same. If you're coding everything from scratch, you'll have to handle that change.
Coding from scratch so... ๐
There's no way to make it work like I tried to you're guessing?
Just as a quick test, move those params into a payload and log out the request in your code.
If the template evaluates correctly, do it that way instead.
It's more common to have a request body with a POST than to have a string of query params anyway.
Will have to try it later on in that case since I need to reboot HA etc. to do change the payload.
Running off in like 3 min
But will take it into advice!
@haughty pond posted a code wall, it is moved here --> https://paste.ubuntu.com/p/5M4J3Z3Bjv/
You see how he uses it in his action?
Different integration, different rules.
I see...
It might appear on the surface that there's a common way to do things. Underneath, it's not that simple.
As it always is then. ๐
If you're comfortable with code, you can take a look at the Python code for the rest_command integration to see how it works.
Gotta run off, but I'll get back to trying later, thanks for your input.
@ivory delta , you there?
Got it working. Had to do this.
data:
icon: ALARM
val: '0'
data_template:
msg: '{{ state_attr(''sensor.hd1913_last_notification'', ''android.text'') }}'```
Oh, weird. Most integrations switched to not needing _template a while back.
Glad you solved it.
value_template: "{{ states('luxtronik.VV_aanvoer')|int - states('luxtronik.VV_retour')|int }}"
Can I make this float ? By simply replacing int with float?
The input values are xx,y
I don't what to lose the precision
Yes
if it doesn't work you maybe have to replace the ',' with a '.'
states('luxtronik.VV_aanvoer') |ย regex_replace(",", ".") | float
If it's already working with | int does that not mean it's already handling the comma? I've never tried these fancy European numbers.
Ah, it won't work with | int either ๐คฃ
Well it showed one crazy number, let's hope it doesn't do that again
It shows it american style by the way, with a .
I would need the regex to make it a , but idc
Hi all, if I were to create a template sensor using relative_time function, how would I get it to update? It seems to only update on HA start/restart. Here's my sensor format: "{{ relative_time(strptime(states.input_datetime.worm_timer.state, '%Y-%m-%d')) }}"
Templates update when any of the entities they reference update.
Well I guess if you use {% set dummy = now() %} you can force it to update every minute
Hey folks... Need some help. I copied some code from a forum post and adapted it for my own use. Here's what I have:
{% set ns = namespace(res=0) %} {% for light in state_attr('group.all_lights', 'entity_id') if is_state(light, 'on') %} {% set ns.res = ns.res + 1 %} {%endfor%} {{ ns.res +1 }} lights on | {% set ns = namespace(res=0) %} {% for light in state_attr('group.all_rooms', 'entity_id') if is_state(light, 'on') %} {% set ns.res = ns.res + 1 %} {%endfor%} {{ ns.res }} rooms
It works correctly except one weird quirk. I'm getting a bunch of extra spaces between the pipe and the number of rooms. This only seems to happen when I have more than one of these loops in a single template. Any help is appreciated.
hello, I cant find information about the related entities tab. am I somehow able to link two entities together so they appear in eatch others tab ?
Is there any way to get them to update on a fixed interval? That entity rarely updates.
Generally, don't tag people to ask for help - it comes across as bad manners, youโre demanding somebody answers you. Itโs different if youโre thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.
Similarly, please donโt DM (direct message) people asking for help. It also comes across as demanding, and means that others canโt learn from what you do.
Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).
Sorry, was a reply - not a tag. I just believe the reply function auto-tags people ๐ฆ
You can uncheck that option. Look, no ping.
Yeah, just saw that. TIL! Thanks ๐
To answer your question... this is a solution is once per minute is enough: #templates-archived message
If not, add the date time integration and decide for yourself how granular you need it by referencing one of the entities it creates in your template.
Same idea... something has to update for the template to be re-evaluated.
Thanks. Will take a look at both options.
what's wrong with this code? it's copied from the forum and should work, yet it doesn't and I don't see the minutes senor in my entities (the firbit sensor works) https://hastebin.com/hevujatoyi.yaml
hey how do i make a slider entity so i can set a slider on the front end that i can read back using node red
- platform: template
sensors:
zone_1_duration:
name: Zone 1 Manual Time
icon: mdi:timer-sand
initial: 30.00
min: 0
max: 55
step: 5
thats what i had but it wasnt working
#integrations-archived. What you want is documented here: https://www.home-assistant.io/integrations/input_number/
but then how would node red see that @hexed galleon
because AFAIK it needs to be an entity
@hollow sierra take the convo to #integrations-archived. And @hexed galleon is correct. Input number is what you need. There's also a #node-red-archived channel that can probably help you with everything you need.
Also, what y ou posted is not a template sensor. It's a mix of a template sensor and input_number, which is why it's not working. Most of those configuration fields you configured are not valid template sensor fields.
In fact, every field under zone_1_duration is incorrect
i took it from someone elses project
Why is this sensor showing
"322,80078125 MB" when i use round?
glances_deconz_ram_used_mb: friendly_name: "Glances - DeCONZ - RAM Used" unit_of_measurement: "MB" value_template: '{{ state_attr("sensor.glances_deconz_RAM", "used") | float / 1048576 | round(0) }}'
- platform: template btw
Order of operations:
1048576 | round(0)
You're rounding that, then dividing by the result.
You probably want this:
{{ (state_attr("sensor.glances_deconz_RAM", "used") | float / 1048576) | round(0) }}
Aha, so that is how i works, tanks.
hi ! ๐ hi this is a template sensor, i want to tell it if the temperature is above 27 for more then 2 hours that means its off.
{(states.sensor.H1.state) ) > 27 for more then 2 hours}} how to do this ? :)
unless automatons can change states then ill use numeric state automation
But you setup a sensor to monitor something and then use an automation to tell you when it goes above 27 for 2 hours
@nocturne chasm i want it to be an actual sensor..
@nocturne chasm how can i display it in lovlace with an icon if its an automation and i want to give it a couple of attributes
if the automation can change state.. then it changes everything
I don't know if you can do it with a single sensor. You could make a template binary sensor that tests if it's over 27, then wrap that in another sensor that checks that the last updated time of the first one is at least 2 hours.
If you're also going to use this information in any automations, I'd recommend having automations that toggle an input boolean after 2 hours, then just show the state of the input boolean (wrap this in a template sensor if you want to do something else with it).
First one doesn't even need to be a template, actually... https://www.home-assistant.io/integrations/threshold/
aha or maybe i can use automation and mark it as mqtt and send payloads to change ?
You don't need MQTT for this. Everything you described is inside HA.
threshold sensor also lets you use hysteresis so you can handle fluctuations.
true okey ill see what i can do thanks ๐
but threshold doesn't have time right ?
like more then 2 hours thingy ..
got it
๐
thanks
100%
btw i noticed there is time_window: 00:05:00
in the sample what is that ?
its not explained there
That's for another sensor. But now you're talking about #integrations-archived
yeah sorry
hey guys, i need help creating a template... anyone there?
Just ask your question...
There are over 6000 people online. I'm sure someone can answer once they know what you're asking.
I'm trying to get the battery level and turn into a sensor, how can i do that? I haven't done this in like 1 year now.
mac: 778BF410
device_class: door
timestamp: 2020-12-30T11:27:00.692000
rssi: -70
battery_level: 101
friendly_name: Nursery
If those are attributes of an entity, you just need to follow the really basic instructions here: https://www.home-assistant.io/docs/configuration/templating/#states
I was able to create the sensor, i just dont know to add the % sign
'''
sensor:
- platform: template
sensors:
nursery_door_battery:
value_template: "{{ state_attr('binary_sensor.wyzesense_778bf410', 'battery_level') }}"
'''
How do i add the % sign to the sensor?
"{{ state_attr('binary_sensor.wyzesense_778bf410', 'battery_level') }}%"?
Or just do it properly and learn how to customise entities with a unit of measurement.
thanks
With the help of the documentation i got my first template sensor to work
The Sensor returns Cal.Entries for garbage collections
Now i want to achieve, to change the day in the corresponding attribute to a different language.
I achieved with the help of the documentation the followinig solution. But i don't know, if there would be a better way? If Yes, please tell me :)
{% set day = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"] %}
{{day[as_timestamp(state_attr('sensor.ics_1', 'start'))-1 | timestamp_custom('%w', true) | int ]}}
okay, something went wrong.. i thought it works, but it does not.. i will look further into it
okay, at that point the -1 is the problem.. hm
perhaps anybody hast a small hint, where to look to further:
I can get this String Thursday, 07.01.2021
Or that String: 2021-01-07 00:07:00+01:00
I thought the second would be better, so i tried to work with Timestamp. But then its says its Friday. Which is wrong ๐
i want to use templates for severel button cards. like this here (https://github.com/matt8707/hass-config/issues/8). to do this I have to switch to yaml mode for lovelace? is it necessary? if i need to switch to yaml mode, then what about the resources that i added so far via gui? do i have to add them again?
- From the doc: "%w: Weekday as a decimal number [0(Sunday),6]." You're starting your array on Monday
|has priority over everything, so1 | timestamp_custom('%w', true) | intgets evaluated first. I don't think that's your goal
oh, starting from 0.. i didnt see that
now it works, but i dont know.. it feels a bit clunky in my eyes...
perhaps anybody has a further hints what i can optimize, before i use this for 20 Sensors :)
Startpoint is sensor.ics_1 which delivers a Timestamp in the following way: 2021-01-07 00:07:00+01:00
I want the weekday in German, so i build the following statement:
{% set day_array = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"] %}
{% set day = day_array[as_timestamp(state_attr('sensor.ics_1', 'start')) | timestamp_custom('%w', true) | int ] %}
{% set date = states('sensor.ics_1').split(',')[1] %}
{{ day + ',' + date}}
Output is now: Donnerstag, 07.01.2021
But i would like to get better and find the best way to get the desired result
Hi folks. Please forgive me as my Jinja2 skills are pretty amateur. Iโm wondering... Is there a way to concatenate the output of some function with additional text, and perform some logic on the final result?
Hereโs my use case:
I have a function that returns a number of occupied rooms. After that, I have added the word โ roomsโ. What Iโd like to be able to do (without additional conditional statements) is replace instances of โ1 roomsโ with โ1 roomโ.
Hereโs what my template looks sorta looks like:
{{ function that returns a number }} rooms | replace(โ1 roomsโ, โ1 roomโ)
If you already have something that returns a number, use the number to decide whether you use the plural version of the word.
Adding the word and then trying to manipulate it is overkill.
Right. Whatโs not obvious from my simplified example is that it sits within a larger structure of conditionals. I was hoping to keep that structure simple by not introducing more branches.
hi, I try to get google_say working with a template, but does not evaluate the template - based on the doc https://www.home-assistant.io/integrations/tts/ the data_template shall not be needed any more?!
without {{...}} it speaks the text fine.
entity_id: "media_player.mpd"
message: 'Temperatur betraegt {{ states.sensor.bb_aussen_temperatur.state }} Grad.'
cache: false
Any hints for me?
That's irrelevant. You can probably still do it in a single line, just don't do it backwards.
ohh - it seems that templates can not be used in the developer service page, - because i tried now to call the service via an automation, and now it works ๐
Sounds good. Can you give some advice how? Again, Iโm an amateur here.
Well if you share a valid template, I'm sure someone can help adjust it.
What you posted above isn't valid.
Fair enough. Here is the template I have:
{% set ns = namespace(res=0) %}{% for light in state_attr('group.all_rooms', 'entity_id') if is_state(light, 'on') %}{% set ns.res = ns.res + 1 %}{%endfor%}{{ ns.res }} rooms
{{ 'rooms' if my_num > 1 else 'room' }}
In this example, I have a group that represents the lights in each room. If one is on, I consider that room occupied. The code to count items from a group that are on is something I copied from a forum post.
phnx, king of templating ๐
I think I get it... Iโll give it a try. Thanks!
Could probably use something with expand and then maybe rejectattr to do it without a loop
Looking for some templating assistance with JSON. I have an MQTT topic that will contain messages formatted like the two examples below. I have an automation for the first that works fine in interpreting the JSON and acting upon it. But the second message causes a JSONDecodeError in the from_json filter which breaks the automation. I actually don't need the automation to do anything for the second type message, I just want it to fail silently. Any way to do this? I've tried eery combination of filter and formatting I can think of.
'{"message":{"id":"A3","unit":12,"state":"on"},"protocol":"clarus_switch","length":"A3","value":"A3","repeats":2,"status":2}'
'{"message":"{\"id\":\"A3\",\"unit\":12,\"off\":1}","protocol":"clarus_switch"}'
Gross double json
Agreed. Coming from a commercial product so can't be changed.
Ok... I think I am totally missing a few brain cells on templates.
I have a binary sensor (just a reed switch open/closed)
I want to give it a name, so I can add it to a card, and say open or closed instead of on/off
Am I just dreaming?
Hmm
There
Had to add an icon, and reload customizations.
And now to add a unique ID somehow to make it available to move to an area
Anyone wanna tell me how to do that? haha
Now I have the sensor all like I want, but i would rather have each of the sensors in the different rooms that they are actually in
Probably as simple as using the groups thing right?
If you're using a Lovelace-managed dash, take control and build it just the way you want ๐
That's just crazy talk! hahahahaha
Thank you @dreamy sinew Some of this stuff is super easy, then some is stupid complex. I get on thinking it's stupid complex when it's really easy sometimes.
Haha the only difference between the newbies and the greybeards is knowing which is which
fair enough. lol
how to use groups in automations ? do i need to specify that its the sates that am after ?
trigger:
- platform: numeric_state
entity_id: group.milkpots
above: 79.5
below: 100
sample of on entity in the group
{{states.sensor.rpot1.state}} is 29.687
what wrong have i done
ps actions and services work .. i just wanted to change it to groups instead of individuals
Hi guys, happy hollydays to begin with
I just added the 17track integration to my HA
for tracking orders
it creates a sensor.seventeentrack_package_12345678 for every order added in the website. (12345678 being the actual tracking number)
one of its attributes is 'info_text' which goes 'Out For Delivery' whenever an order is going to be delivered..
I'd like to create a binary_sensor or some sensor that changes to on whenever any of my orders are out for delivery, no matter the tracking number..
any help will be much appreciated
Hi guys, Trying to get my first template to work correctly. How can I correctly round this value to one decimal?
value_template: "{{ states('sensor.kitchen_sensor_temperature') | float +2 | round(1) }}"
Is it giving you more than 1 decimal place at the moment?
yes
as far as I'm reading online it rounds the +2
You need to force a different order by wrapping things in parentheses:
{{ (states('sensor.kitchen_sensor_temperature') | float + 2) | round(1) }}
That will round the result of the brackets instead of rounding the 2.
ok, will try it again, but before that gave me an error
If it gave you an error, you made a mistake. That will work.
Apparently.. I spent an hour finding a solution for an error that was caused by having platform: templates
๐คฆโโ๏ธ
Don't worry, it happens to all of us ๐
And yeah, it now works. Thank you!
If you ignore the sensor, you're basically just doing this:
{{ 1.9999 + 2 | round(1) }} # 3.9999000000000002
{{ (1.9999 + 2) | round(1) }} # 4.0
Floating point math is random.
Yeah, that part I understood.. I actually tried putting it in parentheses but must have misplaced them as I got the error
@random wing posted a code wall, it is moved here --> https://paste.ubuntu.com/p/9vDdJvFS9F/
@random wing Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
No need to post it again, it's all in the paste the bot made.
And rules are rules ๐คทโโ๏ธ
The issue will be that, despite you casting to an int, HA will then interpret the response from the template. It's likely casting it to another data type - integrations should do their own validation and cast if necessary.
This may have worked in the past (there was a change that allows templates to return native types) but there are edge cases where things break as a result.
Yes, this makes sense. The integration service call schema looks like this:
START_WATERING_SCHEMA = SERVICE_BASE_SCHEMA.extend(
{vol.Required(ATTR_MINUTES): cv.positive_int,}
)
Is it possible to have polymorphic schema?
Otherwise, how else can I validate the input?
Well that's a question for #devs_core-archived
End-user support up here. Dev support down in the dev channels ๐
ack
How can I create a delta t graph or bar view of existing data?
https://github.com/kalkih/mini-graph-card, but #frontend-archived for anything further
Hi, I'm trying to build a template trigger: "{{ now().strftime("%H:%M") == states.input_datetime.notificatie }}" but it doesn't trigger. Any idea what goes wrong in my thinking?
first of all, states.input_datetime.notificatie is an object, not a string
if you want the state of that entity, you should use states.input_datetime.notificatie.state, or better, states("input_datetime.notificatie")
furthermore, it is a datetime with hour only, you will have seconds also
so it will never match "%H:%M"
you need to format the input_datetime as well
Not sure if correct chat. I am trying to get the same graph in my Grafana as I can see it on generic thermostat. With one line as set temperature, second line as temperature and third line as value if heater was on. I am using influxdb. Any idea what data I should send to Influxdb and how to use it?
Thank you.
Thanks for your input. I will try that.
Hey there, I have a timer for 1200 seconds. Sadly, these seconds are translated to a %-H:%M:%S (maybe %-M , didn't tested) value and provided as an attribute within the timer entity (duration).
I'd like to create a template which converts that value back to seconds.
0:20:00 should be converted to 1200 but I did not come up with a solution using jinja. Any suggestions?
This might sound silly, but how can I create a switch that I can turn on and off and it doesnt do anything but just... report itself on or off
So an input boolean and then just use a switch to turn it on or off as necessary
Seems cumbersome
So you're deliberately doing something unusual and then complaining it's hard work? ๐ค
Maybe this will interest you: https://www.home-assistant.io/integrations/demo
And you'll want to head over to #integrations-archived for all of this. It's not related to templates.
He used 3 lines of whitespace for readability - and that got his post flagged ๐
2 lines for backtics, and 1 line for a thanks ๐คฃ - poor guy only wrote 11 lines!
I was tagged for that? ๐ค
@stone coral posted a code wall, it is moved here --> https://paste.ubuntu.com/p/B3FvxmmVgf/
Ah, goodie. Another one...
@stone coral Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
I seem to remember that the logs don't render the template. The actual call it's making will be rendered.
If you want to test this, post to somewhere you can see the request and see what you get at the other end.
Hi guys - happy new year!
I've got a question regarding variables and calculating:
I have an ESP sensor and want to create a variable with an offset value. Then I want to calculate the sum of both. At the moment I tried to "create" that offset variable in the config with
sensor:
- platform: template
sensors:
gasverbrauch_offset_eingabe:
value_template: "{{ states('gasverbrauch_offset_eingabe') | float }}"
but it seems it is not possible to calculate this variable + my sensor variable from ESP
@waxen knot 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://paste.ubuntu.com/ or https://www.hastebin.com/.
But gasverbrauch_offset_eingabe is not a valid entity.
why?
Check dev tool / states for it and you will see why.
hmm, looks ok for me:
Entitรคt Zustand Attribute
Entitรคten filtern
offset_ein
Zustรคnde filtern
Attribute filtern
sensor.gasverbrauch_offset_eingabe 10.00 unit_of_measurement: mยณ
friendly_name: gasverbrauch_offset_eingabe
Except that is not what you put in your template
? sorry I do not understand what you try to tell me
Your forgot the domain of sensor. in your template
value_template: "{{ states('sensor.gasverbrauch_offset_eingabe') | float }}"
gasverbrauch_offset_eingabe is your entity name. sensor.gasverbrauch_offset_eingabe is the entity ID.
Entity ID's always have a domain prefix.
ah, okay I understand - thanks a lot. But it is okay to create variables like that, isn't it? or is there a better way of doing this?
Variables? You're passing a string.
hmm ok.
I wanted to create a variable or something like this to be able to calculate in the next step. E.g. I get a value from on of my gas sensors and want to sum this value up with an offset value. And this offset value somehow needs to be created.
how many sensors?
1 sonsor
value_template: >
{% set sensors = expand('sensor.x', 'sensor.y', 'sensor.z') %}
{{ sensors | map(attribute='state') | map('float') | list | sum }}
okay I'll try to explain better:
I have one gas sensor which sends the actual consumption
And I want to have the real value of the gas counter displayed in ha.
so I thought it would be a good idea to have one variable where I could enter some kind of offset
and have another variable where this offset + the value of the gas sensor is summed up
that's the problem.
Ok, then you need to create an input_number to input a value.
then your template sensor would be:
sensor:
- platform: template
sensors:
adjusted_consumption:
value_template: "{{ states('input_number.xyz') | float + states('sensor.gasverbrauch_offset_eingabe') | float }}"
unit_of_measurement: mยณ
No, it's not hard, it's cumbersome. It's a lot of YAML to achieve a very simple desired end state.
I'd hardly call it a lot ๐คทโโ๏ธ
why do you need a switch? just keep it an input_boolean
ok, thank you. so is there a more elegant way?
What do you mean?
sorry forget it...
@mighty ledge as far as I can see my sensor.gasverbrauch_offset_eingabe looses his value after restarting HA. Is there a way to make this sensor remember his last value?
that depends on where that device comes from
it's not really a device it's just my calculation helper...
Post the code for it
you mean the code of the part of the configuration.yaml?
this is the configuration: https://paste.ubuntu.com/p/qyB4QY3m6M/
sensor.gasverbrauch is what I get from my ESP. All other "sensors" are just there for calculation and comfortable setting the offset after a power fail or something like that
@waxen knot Your template sensor is wrong for gasverbrauch_offset_eingabe
Itโs referencing itself. It will always be zero
ah I understand what you want to tell me :-), but how could I get this working otherwise? The sensor gasverbrauch_offset_eingabe was meant to be a quick way to manipulate it via developer tools after a power fail...
You need an input number. Your offset sensor should be adding some OTHER sensor inside the equation. Not itself.
Ask yourself this: What sensor am i offsetting? Then take that answer and use that in the offset sensor.
for example, if I wanted to create an offset sensor for 'sensor.abc'. Then I would use...
- platform: template
sensors:
offset_abc:
value_template: "{{ states('sensor.abc') | float + states('input_number.offset_abc') | float }}"
You will not be able to offset anything without adding an input number. Embrace it, don't fight it.
Ok I think I got it. I will have a deeper look at that. Thanks so much
Hey guys, I'd like to get a template values that gives "true" when any script is active, can we do that?
My objective is to show a conditional markdown with all the active scripts
{{ states.script | selectattr('state', 'eq', 'on') | list | length > 0 }}
Haven't tested but that's an idea
Can we put conditions like that into a conditional card?
I guess i'll create a sensor then, snif
It works! That was ez
Can we now do the same but when an automation is running? (not the state I mean, but when it has been triggered?)
nope
separate your action section from the automation into a script and you can, only if the script has a duration.
the calc will be on the script though, not the automation
Yeah sounds logic, but good idea anyway, i'll live without that option then xD
Another question, is there a way to stop all the scripts at once btw?
Unless creating a group with all the selected scripts in it?
yeah, script.turn_off and list all the entities in entity_id under data
all might even work
service: script.turn_off
entity_id: all
I needed a way to quickly change the value of that input boolean
That doesnโt make sense, they are essentially the same in that regard
What about an input boolean makes it so you canโt quickly change the value?
Well, I need a way to change the value quickly and easily. And I'm using a switch to do that.
But an input Boolean looks like a switch in the UI
So youโre either skipping some explanation or you havenโt tried it?
Never tried it. Didn't see any documentation that led me to believe it worked that way.
An input_boolean looks and acts like a switch in the UI
Thereโs no difference. It exists to do exactly what you want: a toggle that does nothing that you can build automations off of
Or a toggle to use in an automation, where you set the state
Configuring it is super simple and doesnโt require any yaml
Configurations -> helpers -> toggle. Name it and go.
Yeah, I just reconfigured it. Nice. That's exactly what I wanted.
I probably need to stop doing so much manual YAML work when HA does a lot of this stuff in the UI now
Hi. I've got two entities that give a currency so for example ยฃ60.52. I'm trying to combine them into a value template but struggling to get it right. The following code works fine and combines them but I want to add a ยฃ at the start and can't seem to get it working.
Working code {{ float(states.sensor.electricity_30_days_cost.state.strip("ยฃ"))+float((states.sensor.gas_30_days_cost.state.strip("ยฃ"))) }}
Non working code {{ "ยฃ%.2f"|format float(states.sensor.electricity_30_days_cost.state.strip("ยฃ"))+float((states.sensor.gas_30_days_cost.state.strip("ยฃ"))) }}
Figured it out {{ "ยฃ{:,.2f}".format(float(states.sensor.electricity_30_days_cost.state.strip("ยฃ"))+float((states.sensor.gas_30_days_cost.state.strip("ยฃ")))) }}
How do I do else if statements? I have this code and the parser just throws errors.
{% if is_state("binary_sensor.bg_sensor", "unavailable") %}
false
{% else if is_state("switch.gate_button", "unavailable") %}
false
{% else %}
true
{% endif %}
Replace your first else with elif
It's always elif if you want to check another condition and else for the default.
.jinja2 for more
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
Is there a way to convert seconds into %d %H:%M ? Like 360 = 6minutes ?
Looking for a way for an automation to call a script (with a parameter) on every entity in a group. Ie, if group has three entities, the script is called three times - with parameter set to each entity. I've figured out how to use expand to get the elements out of the group, but there doesn't seem to be a way to loop over service calls to repeatedly call the script.
@simple rune posted a code wall, it is moved here --> https://paste.ubuntu.com/p/ywJdNjKYYB/
@simple rune posted a code wall, it is moved here --> https://paste.ubuntu.com/p/r6qjmYbC45/
Hey guys,
i'm struggeling with an automatotion triggerded by a template (if-statement) depending on a sensor state. The sensor checks the difference between a local measured temperature and the one measured by my TRV. This sensor works so far. So I wrote a template which is checking if the temp-difference is in a given area. So if the difference sensor shows a "value between 0.4 and 50 OR over 50 and under 127.6" it shall trigger the automation (negative numbers are 128-x thats why I'm checking for < 127.4). It seems like the template triggers whenever it wants. Sometimes it works, atm the difference is 127.7 and the template says its true.
code can be seen above
How can I get the min state from today of an entity? I have been looking into min/max and statistics integrations, but none can provide me with the min from today specifically.
Hi all, does anyone has experience with template light integration? It seems that it has never been used because there are no post in the community
Never been used? ๐ค
And... it's an #integrations-archived. Start there unless your question is about the actual templates you're writing to make it work.
Well it seems so looking at the forum. I'm trying to make it works but my templates are somehow wrong.
For example set color:
set_color:
- service: light.turn_on
data_template:
entity_id: light.striscia_led_cucina_rgb
rgb_color: "{{ rgb_color }}"
- service: light.turn_off
data_template:
entity_id: light.striscia_led_cucina_bianco
none for dictionary value @plucky token ['rgb']
I will move to integration to see if I understand well it and the come back here
so
This is the bit you're stuck at:
color_template template (optional, default: optimistic)
Defines a template to get the color of the light. Must render a tuple (hue, saturation)
You need a template that does that. Not RGB. Hue and saturation.
uhm, so how to convert RGB in hue???
hue saturation could be HS value in dev tools states?
If you have it there already, sure. Maybe there's no need to convert.
So you just want a template like the one in the docs that returns a tuple.
color_template: "({{states('input_number.h_input') | int}}, {{states('input_number.s_input') | int}})"
Adjust that to read from attributes instead if it's not coming from a state.
ok now status is reported correctly. Thank you but I still have issue to set_color service. Here's my code I already changed based on your feedback:
set_color:
- service: light.turn_on
data_template:
entity_id: light.striscia_led_cucina_rgb
hs_color: "{{ hs_color }}"
why it doesn't work either?
What doesn't work? Is there an error?
yes. When I try to change color from ui I see an error message: None for dictionary value @ data['hs_color']
I want to list all entities that has numeric state less specified in the input.
I'm using this code. But it looks like it compares not by numbers but by strings:
{{
expand('group.batteries')
| selectattr(
'state' ,
'<=',
states('input_number.battery_low_level')
)
| map(attribute='name')
| join('\n')
}}
Is there a way to create such "oneliner" that makes the comparison bu numbers?
@muted knoll see if the loop/int technique from pnbruckner helps? -- https://community.home-assistant.io/t/jinja-template-sensor-question/133698/11
{% for i in expand('group.batteries') %}
{% if (i.state|int) <= (states('input_number.battery_low_level')|int) %}
{{ i.name }}
{% endif %}
{% endfor %}
this does what I need. But I want to learn how to do the same thing without loop but with chained filters
so this automatino should turn the light off if the input boolean is off, but it doesn't seem to work. any thoughts? https://www.codepile.net/pile/gnRMepZQ
(it used to work with the data template but when i added the service template, it stopped working as intended)
How do I save a template to an automation? When I save it it changes to [object, object] and doesn't work
@ebon jewel Please DO NOT cross post. Read the channel description, post it and wait for folks to respond.
@ancient kelp , if you are using the UI automation editor more than likely, 1) your template is not correct or 2) you are trying to add a template that the UI automations editor canโt handle.
how long is it acceptable to wait before crossposting? activity on some of these groups can be slow and take hours. and what would be more appropriate for a template automation question? template or automation?
Is there a way to keep a sensor value from the previous day and then subtract todayโs value from it to get the difference?
You can look into history_stats.
perhaps you can setup an automation that saves that value to some helper object to persist the value
how to use groups in automations ? do i need to specify that its the sates that am after ?
trigger:
- platform: numeric_state
entity_id: group.milkpots
above: 79.5
below: 100
sample of on entity in the group
is 29.687
what wrong have i done
ps actions and services work .. i just wanted to change it to groups instead of individuals
Hi, folks!
I get this error from my script:
Error executing script. Unexpected error for call_service at pos 1: Template rendered invalid service:
This is the script:
- service: >
{% if is_state('input_boolean.in_bed', 'on') %}
script.goodmorning
{% else %}
script.goodnight
{% endif %}
... which would fire script.goodmorning if still in bed.
- service: >
{% if is_state('binary_sensor.dark_inside', 'on') %}
script.lys_grunnbelysning_on
{% endif %}
Why does this last script (I assume) fail?
I might have found a solution why the error is thrown here:
https://community.home-assistant.io/t/script-service-template-throws-error/192994/10
.. so I need to include an {% else %} here to avoid the error it seems, right?
Hi! My dishwasher has a entity called "sensor.diskmaskin_remaining_program_time" and state is "2021-01-03T10:19:05.176532+00:00" when a program is running. I want to make a template that shows remaining time in Hours & minutes(1h 34min) or %H:%M:%S ๐ i only know this template:
"{{ as_timestamp(states('sensor.diskmaskin_remaining_program_time'))|timestamp_custom('%H:%M') }}" what is only showing what time program is done, not countdown ๐
and google did not help me much
Hi, Iโm trying to setup a light template and this set_color doesnโt works. Can someone please support me?
set_color:
- service: light.turn_on
data_template:
entity_id: light.striscia_led_cucina_rgb
hs_color: "{{ hs_color }}"
Is there a way to get a return "true" when a variable is undefined? like {{ trigger.entity_id is not defined }}
@kindred arrow, do you have a scenario where trigger.entity_id is undefined? From my point of view, it should not be possible
if you want to determine if a state is undefined for instance, just test if it is equal to the string undefined
Actually my full condition is {{ trigger.entity_id == 'switch.chauffage' or trigger.entity_id == 'script.timer_chauffage' or trigger.entity_id is undefined }}
It works just perfectly fine when defined
But i'd like the condition to be true also when not defined
(To be triggered manually)
I'll try and let you know, was on it already aha
I made a little test and is undefined is supposed to work...
{% set a = {} %}
{{ a.b is undefined }}
returns True
Yeah, tried it {{ trigger.entity_id is undefined or trigger.entity_id == 'switch.chauffage' or trigger.entity_id == 'script.timer_chauffage' }} but gives the same message Error during template condition: UndefinedError: 'trigger' is undefined
ok it is trigger that is undefined, not trigger.entity_id
try {{ trigger is undefined or trigger.entity_id == 'switch.chauffage' or trigger.entity_id == 'script.timer_chauffage' }}
@silver pewter did you looked at relative_time?
@earnest cosmos Yes if you don't have an else, the template may return nothing, and HA won't like that. If you want you can include the service call in a choose statement, that way nothing will be called if your condition is not met
@fossil hearth I don't think you can do that, i.e. having a group of numeric entities and have a group state that reflect somehow the numeric value of your group
@gleaming goblet posted a code wall, it is moved here --> https://paste.ubuntu.com/p/3W9kPgprP7/
Found the issue ๐ a . in the {% endif %} ...
I've been fiddling around for a good while now and I think I'm missing something big time. There has to be an easier way to get minutes until HH:MM when 'HH:MM' is provided by a sensor. The day should be the current date, don't care about overlapping at midnight. Can someone help me out?
I have made a sensor like this below, it is formated just like my others, but the sensor don't exist, not even after reboot. Anyone know why?
- platform: rest
resource: http://10.0.24.11:61208/api/3/processlist/name/deCONZ
name: Glances - DeCONZ - CPU - Process - deCONZ
value_template: '{{ "ok" }}'
No entity is generated
Hi guys
how does this template: {{states.sensor.inbox.attributes.data[0].received}}
translate to the format {{state_attr('sensor.inbox', 'data', ... )}} ?
thanks in advanced
I have been able to get this: {{state_attr('sensor.inbox', 'data')[0].received }}
but is there a better way?
Hi. I have this one to select the second process, and it works:
- platform: rest resource: http://10.0.24.11:61208/api/3/processlist name: Glances - DeCONZ - CPU - Processes value_template: '{{ "ok" }}' json_attributes_path: '$[1]' json_attributes: - name - status - username
But I want to select the process by Name and not by order (because that can change)
But no mater what I test I cant find a way.
How to use JSONPath: https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html
There are examples there on how to test for specific values of nested properties.
@cedar wigeon โ๏ธ
Something like this should work: $..[?(@.name=="DeCONZ")]
You can put your JSON and your JSONPath into this tool for testing: http://jsonpath.herokuapp.com/
How should I change this template to become the numeric values 0 and 1 instead of on and off?
https://hastebin.com/iwamobiquk.less
Does that currently output a string or something?
{{ 1 if is_state('binary_sensor.vibration', 'on') else 0 | int }}
maybe that, Idk
I figured it'd bbe an int already though
outputs a boolean
I meant the template you had above
not sure, it outputs this in history graph: https://imgur.com/a/D96sefX
dev tools
Yes, sorry, result type is a string
What should the output be? I'm still getting a string and the same graph
@wary helm you need a unit_of_measurement
without it, sensors are always treated as strings, regardless of what the template returns
if you add a unit_of_measurement, it knows the sensor is numerical. Also, you'll have to wait for the database to purge out the 'non-unit_of_measurement' state changes in order for the change to take effect.
After reading some things on internet i created a sensor for lights that are currently on but i also read that is a resource hog. How can i make this code less resource consuming is there a written guide?
- platform: template
sensors:
current_kitchen_lights_on:
friendly_name: Number of kitchen lights on
unit_of_measurement: 'on'
value_template: >
{% set lights = [
states.light.hue_light_kitchen_ceiling_1,
.Etc..,
] %}
{{ lights | selectattr('state','eq','on') | list | count }}
it's not resource consuming, people exaggerate. If you define the list in the template, it's minimal. If you iterate all the state objects on every state change, it's a hog. What you have there is fine.
good to know about why it was string petro, thanks
Hi!
quick noob question if I may - would this trigger work if states have slightly different formatting? https://paste.ubuntu.com/p/chmJQhN59s/
it should read as HH:MM == HH:MM:SS
or should I reformat one to unify them?
I mean just the part before adding the offset (forgot to delete that in example)
It is the good way
oh thanks
Thank you petro, I've added a unit_of_measurement. Any idea how long it might take before the databases purges out the non-unit of measurement state?
Any ideas why this trigger doesnt work? https://pastebin.com/wSDh7gW7
If I test that in template editor it returns true. but the automation doesnt trigger at that time. (it seems to be triggered by just changing the time (from before now to after now)๐คฆโโ๏ธ )
Usually 24 hours
Templates need to resolve true after being false. If you restart at a time where itโs just true it wonโt trigger. Set the trigger time for 2 minutes out after a restart. Also you donโt need to wrap the states in as_timestamp.
Thanks! But without as_timestamp theose did not turn out to be true as time returns in HH:MM format but the input has :SS also
@brave raven posted a code wall, it is moved here --> https://paste.ubuntu.com/p/gHyqFDXGJc/
Hi, i'm trying to create an icon change on a sensor template. it keeps registering new sensor as unknown. I searched on the templates pages and tried a few things without success. Can someone assist and have a look over my code to see what i'm missing
the code is in the link https://paste.ubuntu.com/p/gHyqFDXGJc/
@brave raven posted a code wall, it is moved here --> https://paste.ubuntu.com/p/cX2sGmjmvN/
the Error in the log file is https://paste.ubuntu.com/p/cX2sGmjmvN/
Solved it ๐
Can anyone tell me if there's a way to truncate object id please? So for example I have an input_number.l_temp_evening that I want to use to change the target temperature of a climate.l_temp, using
entity_id: 'climate.{{trigger.to_state.object_id}}'
so I want to remove the _evening from the object id of the trigger entity (I have an input_number.l_temp that I use to set the temperature at a different time of the day, which is why I don't want to change the name of anything). I'm not sure if this is the correct section, or if this makes sense!
then only compare it to the first 5 characters. [:5]
Seems like the entity doesn't have the attribute watts. Take a screenshot of the entity in the developer tools -> states page.
trigger.to_state.object_id.split('_')[:-1] | join('_')
Thanks @mighty ledge I solved it with the below code
@brave raven posted a code wall, it is moved here --> https://paste.ubuntu.com/p/y83Kpm8vGy/
no
that has to be done at the UI level
in lovelace, and you'll need a custom card
if you're referencing a fan, there's already plenty of solutions, look on the forum.
typically they use the custom button card
aha, thank you very much ๐
fyi, it's not easy
there may be other solutions, you can also ask over in #frontend-archived
What a legend! Thanks very much ๐
How can I convert {{state_attr('sensor.text_weather_swe', 'icon')}} to Javascript template? I can't figure it out
Here is my shot [[[ states.sensor.text_weather_swe.attributes["icon"] ]]]
I suggest you try #frontend-archived
Can I stick multiple actions in a switch template?
yes
Rad. Thank you.
Finally got a projector that has an integration. Getting rid of my Logitech Harmony hub.
You don't like the ass backward API that harmony offers?
It did its job years ago, now not so much.
I wish they would update it
I still can't believe they only tell you the activity name, not what devices & commands are mapped to each activity
makes it a fucking useless api
@limpid fractal posted a code wall, it is moved here --> https://paste.ubuntu.com/p/q5xsnjy8Zr/
Can someone help me with a condition in a script, details are posted above
you probably should use a yaml condition rather than a template condition.
If your template is not true then it is leaving nothing in the call
Hi, i wonder if someone can help me, i have this perfect motion light automation that just works perfectly:
https://paste.ubuntu.com/p/27BbXNnk2X/
I then tried doing more or less the same, with some heating when windows open and closes.
https://paste.ubuntu.com/p/6ybCZrG9GW/
But that don't work at all, although the same actions work in another automation
You have a lot of stuff for me to look through there. Have you tried throwing your templates in the dev editor and making sure all of the outputs look proper?
dev tools*
Also, does it trigger and fail to call action or does it never trigger?
it does trigger, it seems as i can see it in the logbook, okay then it's properly the script
which is this one:
https://paste.ubuntu.com/p/KZKpRgsKgZ/
which works here:
https://paste.ubuntu.com/p/rcxRRhhpgn/
Did you check output of templates?
hmm yeah that gives me a trigger undefiende...
I meant the temperature and set_now templates you have
maybe that is what you meant too
yes that also gives me a trigger undefined.
ah okay i just need to give it the trigger entity, and yes then it works.
and now i tested the whole automation in the out and it seems to work.
hmmm i think i maybe found it give me 2 min.
hmm okay no that was not it.... i thought i was because the template actaully outputted severals lines, so i made the template into one line, but that didn't help.....
one interesting thing is that logbook it seems like it turns of the script again.
https://paste.ubuntu.com/p/yQnpqnYkgW/
ah nevermind the other one also does that.
okay if i only have the first with the entity_id and hardcode the rest then it works as soon as i add another it fails..
it was the " that was the error...
I hope I'm in the right place. I've just flashed openmqttGateway to an 8266 and I'm trying to get the templating for an RF plug formatted in HA. So far all I can do is get HA to send "ON" or "OFF" no matter what I set as command_on_template. It also doesn't register the json payload coming from the module.
ok, I got it to turn on after some tinkering and reading the project's forum some more. Now I need it to actually stay on in HA when I turn it on via the UI or the plugs' remote.
Is there documentation on how you need to format a template with device class timestamp to be formatted properly in different browsers? I have one that displays fine in Safari and Chrome but in the silk browser on my Fire Tablet it just shows the date instead of "18 minutes ago" or whatever it should be
Oh wait - it might just be the entity card that isn't displaying it correctly
Hey
I think this might be a very newbish question, I want to format a sensor, I found that I should write some template thing.
When I try it out in the developer tools, template section I got the formatting to work, but where should I put this code more permanently ?
you have to create a template sensor
and is that just in the configuration.yml?
ok thanks ๐
Any way I can convert an array of byte values (e.g. [12,34,56,78]) to a numeric value? I have an mqtt sensor which sends data that way.
hm... wonder if something like value[3] + value[2] * 255, ... will work
what's the best value to return for a numerical template sensor before its dependent entities are ready?
or can i just return nothing?
@glossy viper #frontend-archived message
ty ...i'm making some progress. Made that template (not sure is correct) , but i wanted to be displayed for each of the entities. https://pastebin.ubuntu.com/p/NYgnvX2ntv/
my drive is 100% so i can't save edits in my configuration.yaml, so I can't implement the purge-db that way.
How can I run a manual purge?
call the recorder.purge service
however, it is probably easier to delete e.g., the homeassistant.log file to create a littlebit of quick space (so you get room to figure out what is going on)
help, but I don't have access with samba, and my vscode plugin is saying read-only.
I am running the VMDK in esxi
You can remove files using vscode as well?
you can select remove, but don't look like I have rights
Sounds odd, sorry not sure how to help at this point.
running the service might help, or else get into the system by terminal to clean up some space
hmm. I did a reboot, and I can no access trough samba, and have deleted the db and log, but the web gui say "Unable to connect to Home Assistant"
Ensure it is started, when running out of disk space
systems will act weird and will fail at starting parts
another try. hope this time it is the right place. ๐
this is my solution to find devices which are offline (state=='off'). it is rather rudimentary that is why i tried to add a check on the device_class attribute which should be 'connectivity', but this is not working. any hint?
{% set e = states.binary_sensor | selectattr("state", "in", ["unavailable", "unknown", "off"]) %}
{%- for state in e -%}
{%- if state.entity_id.startswith("binary_sensor.l") %}
{%- if state.entity_id.endswith("status") %}
{#- {%- if state.name | selectattr("device_class", "is", "connectivity") %} #}
- {{ state.entity_id }}
{#- {%- endif -%} #}
{%- endif -%}
{%- endif -%}
{%- endfor %}
you do a state.name before the selectattr, state.name is a string, it has no attribute
why don't you simply do is_state_attr(state, "device_class", "connectivity") ?
is available for me also ?
https://pastebin.ubuntu.com/p/pq4gybvNDm/
value_template: "{{ state_attr('usgs_earthquakes_feed', 'time') }}" - value returned is "unknown"
usgs_earthquakes_feed is not a valid entity id
is a feed type...but i don't know how to make templates
@glossy viper an entity_id will have a period in it somewhere, in your case it probably should be something like {{ state_attr('geo_location.usgs_earthquakes_feed', 'time') }}
still unknown status
what does it tell you in the template editor?
- platform: template
sensors:
shake_time:
friendly_name: "Earthquake time"
value_template: "{{ state_attr('geo_location.usgs_earthquakes_feed', 'time') }}"
all good (already restarted)
so it's all good or it isn't working
oh...in developer tools
- platform: template
sensors:
shake_time:
friendly_name: "Earthquake time"
value_template: "None"
This template listens for the following state changed events:
Entity: geo_location.usgs_earthquakes_feed
all good - syntax i meant
but value_template returned is none ๐ฆ
does the entity under developer tools > states show anything? more to the point, has there been any earthquakes for it to report?
yeah ok so i just went and setup this component and holy lol, think i need to dial back the settings a bit
i have 9000+ entities added as a result
i put the card and the sensor which is radius 1000 km from my home
if u want to catch the same earthquake your radius should include croatia ๐
ok so this component turns out to be pretty awful
instead of creating an entity that has a list of events under it, it creates a new entity for every event. this isn't going to be fun to deal with.
{{ states.geo_location | list }} will show you a bit of what's going on
ok. i will put instead of time in template sensor to see what i can get straight in the card
So you can fake that, by creating an helper
and next an automation that triggers on such an event and populates the helper
that way, you'll end up with an helper entity that has the last received event
was trying to figure out how to sort by time, but that's another easy solution
too advanced for me i guess. only 2 months of ha
might not work on startup, depending on the order that things are populated
barely have one input boolean to stop notification to my phone
@glossy viper are you trying to find the latest earthquake? If so...
value_template: >
{% set quakes = states.geo_location | selectattr('attributes.source', 'eq', 'usgs_earthquakes_feed') %}
{% set latest = quakes | map(attribute='attributes.time') | list | max %}
{% set latest = quakes | selectattr('attributes.time','eq', latest) | first %}
then from there you just gotta decide what piece of info you want
{{ latest.state }} or {{ latest.name }}
or if you want the entity_id ... {{ latest.entity_id }}
I imagined that once with the earthquake i can see as a secondary info time. I know that i can see the time if i click on card and see more attributes, but i wanted to see directly from viewing, not by one. click. i thought it was simplier, but i guess sometimes things can be simple only in my mind
just went home....will try now. thank you for your time, no matter if works or not.
You can get attributes via templates too...
I suggested a template sensor already.
Use petro's template and then build on it. You want to get time, do something like {{ latest.attributes.time }}
i need an example to understand like petro did....i'm too old to think myself for first step. then i can manage by myself...but the first step is the biggest for me ๐
i'll try to do with time
template editor, break it, fix it
Result type: string
{value_template: >
This template listens for the following state changed events:
Domain: geo_location
i'm on a good way?
and no time around earthquakes ๐ฆ
is there a better way to count all input* helpers together than counting them individually and adding them up?
cos for individual counts I have e.g. {{states.input_boolean | count }}, but I'd rather have all types together
and all I can think is to do that for each and add them up after
Match their names against a regex and then count.
Something like this:
{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list }}
is regex the * thing? ๐
No, that's an asterix.
I'm really bad with templates haha
lol
RegEx = regular expressions. It's a powerful syntax that allows you to query text for patterns.
This is my first time seeing regex ๐
Let me try with your examples. Let's see
www.regex101.com for a brief intro and an interactive playground.
You REALLY don't want to see my template sensors lol
i do ..maybe i will guess what to do for me ๐
i put the answer as u can see in pastebin, but i didn't get it
The template wasn't complete because I have no idea what you wanted, that's why I wrote all the sentences after the template describing what you can do to grab info out of it.
๐คทโโ๏ธ
I told him what to do next. He clearly didn't read my message at all.
He pasted yours without edits and expected it to work.
i said that i don't have experience with template and need help building that
Between petro's example and the extra line I gave you, that's literally the full answer.
I don't know how much more help you need other than someone writing it for you.
Here we go... just to end this conversation:
value_template: >
{% set quakes = states.geo_location | selectattr('attributes.source', 'eq', 'usgs_earthquakes_feed') %}
{% set latest = quakes | map(attribute='attributes.time') | list | max %}
{% set latest = quakes | selectattr('attributes.time','eq', latest) | first %}
{{ latest.attributes.time }}```
(assuming `time` is the name of the attribute you want)
what does that mean from hassbot, lol
It means my first paste had incorrect indentation and therefore wasn't valid YAML.
ahh
It doesn't check edits, so it'll still have an x.
thanks
i know that i have put your patience to the max mono, but without understanding what represents first line is an trial & error in a loop for me
but someday i hope i can deliver a beer for the guys helping me
Get the feed (from the attribute usgs_earthquakes_feed)
{% set quakes = states.geo_location | selectattr('attributes.source', 'eq', 'usgs_earthquakes_feed') %}
Sort by time, newest first
{% set latest = quakes | map(attribute='attributes.time') | list | max %}
Get the most recent item in the feed
{% set latest = quakes | selectattr('attributes.time','eq', latest) | first %}
From the most recent item, show the time
{{ latest.attributes.time }}
Do template definitions still need to be manually put into the config.yaml or has something been added to do it from the HA frontend? Running version 2021.1.0
So creating a custom sensor from an entity attribute..
I have it working this way, but just making sure I am not missing something..
Well creating sensors is a YAML thing, so the answer is to still do it in YAML.
Thanks.. Just making sure I wasn't missing something where the config could be put in via a web based window. Something like when you create a custom resource for lovelace there is the "gui" interface for adding it.. Hope that just made sense..
Playing around with what you gave me I also ended up getting it to count every single entity id. Probably not the way to do it but I'll use that too since I got it now
Only issue with counting the helpers I realised I have a few automations with the word "input" in and it's now counting these as well
I'm just using it twice to subtract automations with input in the name
(states | map(attribute="entity_id") | map('regex_search','automation.*input') | select('true') | list | count) }}
You only need it once, just fix the regex.
Really quick guess: map('regex_search','input_.*\..*'). Gives me a sensible count.
I haven't verified the entity names it returns to check.
input_.*\..* means input_ followed by any number of characters, followed by a . followed by any number of characters.
And since there should only be one . in an entity ID, that should match all inputs.
I knew it was that but I had to chance, but I was just staring at it to work out what to do with it
RegEx looks like some arcane wizardry at first glance but it's quite logical. It's just a PITA to come up with expressions if you're new to it.
For the longest time, I could read a ton of them but not write any ๐คฃ
regex101.com will help you understand it. You can plug in examples in the 'test' pane and see which things match and which don't.
regex101 is a blessing
I went there but it confused me on how i should use it
on the top I put the regex and underneath the potential matches?
Like that
Any test string that's highlighted is a match (and will also appear on the right). Top right is a breakdown of your regex.
it has globbal on by default on the site so you can put a list and compare the list being hihglighted
Ah I see. I was putting more in there and likely was failing because of it
Bottom right is the quick reference. It explains most of the common syntax.
Ah I see now
You can get fancy and give alternates too. Here's an example where I only care about input_number or input_boolean: http://prntscr.com/wijdcg
So | means or ?
Yup
It's all in the reference in the bottom right.
Here's a fun one. This is the official regex to validate if an email address is valid:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
did you see the explanation at the top right too? It breaks down the regex inputed
I was just adding . to see the explanation of that haha
Just now
๐ค
That regex is bugged though. It allows some illegal email addresses ๐คฃ
Shows how tricky regex gets when you do more complex stuff.
Anyway... does the one I gave you work for your inputs, Thanasis?
A so in your input_.* it's not . then * it's the whole thing .* that means something if I'm getting that right
Yeah yeah works exactly like it should ๐ฏ
Read it in steps...
input_ the literal string 'input_'
.* any number of any character
\. the character '.' (needs a backslash as an escape character because . has special meaning)
.* any number of any character
I only new of * meaning anything which is why I got so confused when I saw .*
Another way to solve your problem of it matching 'input' in the entity name of an ID would be to anchor the regex to the start of the string: ^input_.*
That would do:
^ match from start of line
input_ match the literal string 'input_'
.* any number of any character
Should also work for you, just another way of doing the same thing. Might even be quicker but we're talking fractions of milliseconds for simple stuff like this.
Even just ^input gives me the same
Compared to what i had with subtracting them ๐
What is the meaning of select being true/false ?
| map('regex_search', 'pattern') is running a test against each item and will return true/false for each item... but you still get back a result for every item (that's what maps do).
oh, my b
You then run a | select('true') to filter out the ones that don't match that test.
if you remove the end bits of the template pipe by pipe, you can see what is going on
It's like when you see people do massive multi-line templates where each line is a step in a bigger process... pipes are the same thing on one line.
Ah I also see the point the moment you completely remove it. Give you eveything
yee, you get a fat list of true/false and then we filter out only true before count
And like I said earlier, it took me ages to learn this kinda stuff. I'm a software engineer and I still don't grasp this stuff immediately ๐คฃ
And when you mix 6 different libraries, all sorts of fun
Yeah I've hardly played with templates so haven't had time to really understand them yet
@ivory delta so if you're a Biologist likely decades then hahahah
They're one of the harder bits of HA but they're so powerful once you learn them.
If you are ever messing with templates that require events, you can throw in a json object and parse it as an obj so you can sort the other templating based off of the event
they can be super powerful
but can also be really obnoxious ๐
do they go nuclear @dreamy sinew ?
datetimes in templates make me want to commit sudoku
I have no idea what you're saying ๐
I think he means like this:
{## Imitate available variables: ##}
{% set value_json = {"sensors":{"28-00000b988fef":"42.312","28-00000b98f5e6":"51.937","28-00000b9905e1":"39.062","28-00000b9920f3":"39.062","28-00000b994f64":"37.625","28-00000b9951c4":"37.812","28-00000b996c8c":"38.0","28-00000b99a737":"33.687","28-00000b99a884":"33.25","28-00000b99b4f0":"38.937","28-00000b99f29e":"37.75","28-00000b99fa3c":"34.187","28-00000b9a170e":"36.562","28-00000b9a1ca5":"37.75","28-00000b9a2529":"32.375","28-00000b9a3025":"40.187","28-00000b9a444d":"42.125","28-00000b9a4668":"41.312"}} %}
The temperature is {{ value_json["sensors"]["28-00000b988fef"] }}```
Pretend you have a JSON coming in but just mock the data so you can play around.
One of these days I'll finish with my gitignore file and upload my config to github. I'll send a link to my templates 


In something like a REST sensor, you'll have value_json coming in... but you don't want to have to reload your sensor every time you want to test a change.
Aaaah so I set up a fake sensor state so it parses in the template and I get an output ?
I'm so glad the Template dev tool now retains your previous templates. I'm using mine as a kind of respository of examples I want to refer back to or share with people ๐คฃ
Yeah, same idea with those too, BuSheeZy.
I do that too
Mock the data, then experiment with the mock.
but does it not clear once you restart?
So I just went to it to do all these templates now and I knew I had left there templates from last time but I had the default one
You want some real helpful templates? How about knowing which room/house/floor/whatever something is assigned to?
{{ states | selectattr('attributes.room', 'equalto', 'study') | list }}```
So like I had left things from e.g. a week ago
I customised some entities to have the attribute 'room' with a value assigned to it ๐ฅ
So you give them like both floor and room for example to filter even more?
You can give them whatever you want.
https://share.busheezy.dev/rUaaqu/yaml I love being able to do this. This is when a fake trigger obj and be nice if it's json or sumtin
Let's say you have tons of media players and you want to easily identify which ones are TV's/sticks and which are audio-only.
I also don't get that haha
It's likely my 1h of sleep and amount of work currently stored in my head
I am not doing any parsing here, but this type of trigger is just what I meant
where you wouldn't be able to get that info in your tempalte editor so you make a pseudo one for toying with
snag it out of your mqtt stuff and then make it into a template obj
Ah so you publish to that topic yourself?
yes
as soon as an mqtt event comes in, it immediately goes back out and I could do stuff with the data all within that piece right there
with templates
But your trigger mqtt is an actuall sensor you have and you have that published to a fake one? or confusing myseld now?
these are two diy devices. co2 sensor that I output to a separate 7 segment display that isn't a sensor.
co2 sensor is logged but rather than doing an automation based off of state, I just do 'er with the mqtt trigger
7 seg is not a sensor or anything, just sending data to it for no reason
I should have just had a good example because this is not ๐
Throwing me right in the deep ๐
Imagine I have a json packet coming in and I only want to log one of the attributes as an entity. I can make a template out of that for sure and it will always have its state in HA. Maybe I have another attribute in a json packet and I don't want to log its state at all or store it as an entity at all, I can just use the template to get the trigger.packet and immediately forward it off somewhere else without having to make automations based off an entities state.
I am too afraid to read back that sentence, I typed for a long time without a period, I think
https://www.home-assistant.io/docs/automation/templating/#mqtt these are template values you can get with mqtt for example
there has to be a good example on there too but I am a lazy person atm
oh, lots of stuffs
That is making some sense to me actually ๐
@ivory pawn posted a code wall, it is moved here --> https://paste.ubuntu.com/p/9gtbfXXFDp/
you are trying to pass data through the topic?
Hello all, can someone help me with yaml automation and mqtt ?
How do I change the code so that the last variable X (varX) in the trigger topic is also passed to the data template ?
initial_state: True
trigger:
- platform: mqtt
topic: 'A/states/B/C/varX'
action:
- service: mqtt.publish
data_template:
topic: 'A/B/C/varX'
payload_template: '{{ trigger.payload }}' ```
At the moment I am having to treat each varX as fixed by writing a seperate trigger and action automation for know values of varX.
@timid osprey thanks but it doesn't pass yaml . error : expected <block end>, but found '<scalar>'
@timid osprey thanks ... ill try to understand the link and try it out.
Just to be sure, i'm trying to take any mqtt topic starting with A/states/B/C/ and forward it to A/B/C/ but preserving whatever comes after C in the state topic. Or in another way I want to take out only the '/states' part of an mqtt topic before forwarding.
topic: 'A/B/C/{{ trigger.topic | regex_findall_index('.*/(.*)') }}'
``` isnt accepted by HA config check and brings up an error. Can you please help me correct this? Thanks
@timid osprey thanks .. this worked topic: "A/B/C/'{{ trigger.topic | regex_findall_index('.*/(.*)') }}'"
however, it still needs the trigger topic to have pre defined (static) values for varX, otherwise the template topic doesn't have this value to copy. any ideas?
solved with split . thanks
https://www.reddit.com/r/homeassistant/comments/ksx8su/please_help_me_to_make_a_simple_card_sensor_out/
do i need templating to accomplish this?
i read over the templating page and went to the test tester in developer tools, but i can't figure out how to manipulate mqtt string data in there.
@bright quarry What I would do is create an MQTT sensor by door/window sensor, and in the value_template: attribute put something like:
name: my_entity_id
value_template: >
{% if value_json.device = "device_id" %}
value_json.state
{% else %}
{{ states("sensor.my_entity_id") }}
{% endif %}
json_attributes_template: "{{ {'time': value_json.time, 'extradata': value_json.extradata} | tojson }}"
and put the time & extradata in the attributes
what it does is that it updated the state of the sensor if the device matches the device id of that door/window (1P7T3), and if gets the existing state of the sensor if the device id does not match the device id of that door/window
you will have to add the same logic in json_attributes_template
name: my_entity_id
value_template: >
{% if value_json.device = "device_id" %}
value_json.state
{% else %}
{{ states("sensor.my_entity_id") }}
{% endif %}
json_attributes_template: >
{% if value_json.device = "device_id" %}
{{ {'time': value_json.time, 'extradata': value_json.extradata} | tojson }}"
{% else %}
{{ {'time': state_attr("sensor.my_entity_id", "time"), 'extradata': state_attr("sensor.my_entity_id", "extradata")} | tojson }}"
{% endif %}
I have a broken HassOS installation, I can't login to the web-gui, but I can log into the CLI with root, and access the root system
I want to copy out my configuration and start ower. How can I enable SSH or SFTP so I can copy my config? I have samba enabled but I don't remember my credentials
wrong place to post I se
I got this template to change temperature on ac when outside temperature is under 5. How can i get it to change to 14 when temperature outside is still under 5 but electricity price is "VERY_EXPENCIVE"? https://pastebin.ubuntu.com/p/gXQFRhS7Vr/
@deft timber where do those go? configuration.yaml and somewhere else? i tried the first code block in configuration.yaml and got a syntax error, maybe my indentation was wrong.
Hello I have weird situation that my wait template is not quite working as expected
timeout: '00:00:10'
continue_on_timeout: 'true' ```
its skipping this condition
and automatically returns the scene before for the media player\
data:
entity_id: scene.before```
so, basically I can hear my tts, but in the middle of a sentence, it set my scene like before (changes the channel)
so, do you have maybe better solution how to stop script (to wait) for my tts its finished and then proceed further?
Yes, in the configuration.yaml:
sensor:
- platform: mqtt
name: your sensor
state_topic: Simplisafe
value_template: ...
json_attributes_template: ...
still no bueno.
change value_json.state whith {{ value_json.state }} and the = with ==
how do i use it after that? i added a sensor but nothing happens.
should i have double == on both value_template and json_attributes_template ?
Yes
Then create a sensor by door/window
changing the device_id
and don't forget to change sensor.my_entity_id with the actual id of your sensor
the one you are defining
sensor.simplisafe_sensor in your case
like..cover?
oh. you mean create a sensor for each door/window and specify it's device_id? in configuration.yaml?
yes
The input of the Solar pannels from brand 'SMA' are connected with modbus.
If the sun is gone i get the lowest possible number because the readings are 'unknown' .
Trying to fix this with a template but its not working.๐ซ
https://hastebin.com/ipoloketuy.yaml sensor.yaml file
https://imgur.com/a/AQELToP
Working on this for 1 week now. Anny suggestions ?
So you want to use the value of sensor.sma_pac unless it's unavailable, in which case you want to have 0?
I don't know if there's a better way but this should work:
{{ 0 if states('sensor.sma_pac') == 'unknown' else states('sensor.sma_pac') }}
@spring zenith
Thats exactly what i would like. yes
If it returns a numerical value, you could probably just cast to an int too, since 'unknown' will cast to 0.
{{ states('sensor.sma_pac') | int }}
yeah, if its always a number you can just cast to int. Anything that is NaN gets dumped to 0
Looks neater too, even if it leaves you wondering how it cast a string ๐
It's handy. I only just thought to try it.
was gonna suggest it but you were faster
lol
Also strange that i cant find 'sma_ppv_incl_0' and not 'sma_pac_incl_0' back in HA
Nothing changed.
https://imgur.com/a/ma8voHq
Is my code correct ?
https://hastebin.com/nemuwisoci.yaml
Need 2 go. @ivory delta @dreamy sinew Thanks in advance.
For me... you both are pros ๐
trying to wrap my head around condition template condition shorthand. not clear why this is not working https://hastebin.com/boqitihiyi.less
it's not clear to me why condition: works and conditions: does not
ยฏ_(ใ)_/ยฏ
oh, it this the intersection of boolean testing?
bother
ok, this works but it's a lot visually..... condition: condition: or conditions: - "{{ state_attr('light.desk', 'brightness') < 51 }}" - "{{ is_state('light.desk', 'off') }}"
this is better? condition: "{{ state_attr('light.desk', 'brightness') < 51 or is_state('light.desk', 'off' }}"
The latter is a slight more efficient from the code part of things
as it just checks 1 condition
instead of rendering 2 templates
however, that is micro optimization, readability is generally more important I would say
You can alternatively format it like so:
condition: >
{{
state_attr('light.desk', 'brightness') < 51
or is_state('light.desk', 'off'
}}
oh that's nice
I'm using scrape that is ending up with value == "Docker Registry Browser ยท Version 1.3.5 (59abbda)". In Dev Tools/Template, if I do something like this:
{% set val = 'Docker Registry Browser ยท Version 1.3.5 (59abbda)' %}
{{ val | regex_replace('^Docker Registry Browser . Version ([0-9.]+) .*$', '\\1') }}
it works great.
But in sensors.yaml, this returns the whole string:
value_template: >-
{{ value | regex_replace(find='^Docker Registry Browser . Version ([0-9.]+) .*$', replace='\\1') }}
Any ideas?
using the word condition three times felt like i was doing it all wrong
Nah, it was fine, depends on the use case
for example
you could have used
condition:
condition: or
conditions:
- condition: numeric-state
entity_id: light.desk
attribute: brightness
below: 51
- condition: state
entity_id: light.desk
state: "off"
or a combination of any ๐
Conditional conditions conditional conditions condition condition conditional conditions.
Templates are generally less efficient for the system
using native available stuff is generally a tad faster
and now the zha attached ge link bulbs i'm using behind my monitor follow the brightness of my hue bulbs down to a point and then just turn off. https://hastebin.com/usikutofub.yaml
@hexed wing If you're replying to my issue, I'm not sure what you're suggesting. Is there a better way to get that information (just the version number) into a sensor?
I was not
oh... ok. good. Because I wasn't sure what to do with it. ๐
FWIW: changing my code to this:
value_template: >-
{{ value | regex_findall_index(find=' Version ([0-9.]+) ', index=0) }}
fixed it
Is there a way in templating to get the devices/entities of an area? I need it in a blueprint where it has a target selector and I want to check in a loop for every item of an area/devices/entities (the things a target selector can give) in an automation if it has a kind of attribute. For devices and entities the loop is straight forward, but not for area. Didnt find much about areas in the docs (especially for templates). Only found that theres an "expand" for groups, but I need it for an area or a way to convert an area to a group and filter these.
I don't know about for areas but you could set custom attributes on entities to designate which 'area' they're in and do something like this:
{{ states | selectattr('attributes.room', 'equalto', 'study') | list }}
Thanks for the effort but I think it doesnt suit in my usecase. Because its for a blueprint I want it to work right away. If the user has to set costum things to each entity of an area, he could also just create a group and use the group. Avoiding to have making group and making it easy to use with a target selector is my motivation for such a messy solution for this blueprint. Targets are great for services, but messy in templating I think
Can I get the state of an entity from a specific time?
@deft timber i can't figure out how to make a sensor with device_id. can you help? ;/
I have a sensor that shows used time time in seconds, how can I edit it so it displays hours/minutes/seconds , with no limits on the hours (so values like 10.000 hours should be possible)
The examples i found online seem to limit the hours to 24 or 99
What kind of sensor?
My heat pump has a thermal unit it reports time used in seconds, so i added that as a sensor configuration but seconds aren't as easy to read as hours minutes seconds
Id copy a test configuration but the file editing add on doesn't support text selection or copy/paste sub menus on android
I tried this but it gives an error
can not read a block mapping entry; a multiline key may not be an implicit key at line 128, column 30:
{%- set map = {'Week': (seconds / 604800) % 604800,
^
Could you describe what your problem is and show me what you have so far?
Without seeing the whole thing, I have no idea what's wrong there.
Del.dog shows the entire sensor entry
D'oh. I missed that ๐ What happens when you put that into Dev Tools > Templates?
Is there any way to remove that sample template besides holding backspace for each line individually
The value template stuff is calculated in the Dev tools template
And shows the sensor entries as plain text
Are you asking me how to edit files? That depends on your editor and is something the internet can tell you.
And if you just want hours, minutes, seconds, this is what you're after:
{%- set map = {
'Hour': (seconds / 3600),
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}```
178 Hours, 6 Minutes, and 40 Seconds
@deft timber https://pastebin.com/F1a82gDZ
dunno how to parse # bathroom window sensor. dunno what to give it for a platform name or what else to put there to make it work.
No in Dev tools - templates
Highlight the text with your cursor, then press backspace? ๐ค
Yeah it stops every line
I have to manually click the line above to delete that, and the one above
Then you / your device / your browser is the problem.
And so forth 24 times
Ahh so it's a compatibility issue with chrome on android
Can I use this code outside if a template?
That code is a template. I don't know what you mean by 'outside of a template'
And editing code on a mobile phone is ๐คข
Use a real editor...
On a real computer ๐
Not sure if this is the right place, but.... anyone know how to convert a binary_sensor to a value, like 0 or 1?
I don't think you understand what I proposed.
- You have to replace the "device_id" of the mqtt sensor with 1P7T3
- You have to delete your template sensor
- You have to duplicate the mqtt, to make one by window/door, replacing each time the device id
I was hoping to use it directly in the sensor definition instead of creating a new sensor under template
Hey guys, what am I doing wrong here?
Solution: use media_player.play_media !
- service: media_player.media_play
data:
entity_id: media_player.spotify
media_content_type: playlist
media_content_id: >
{ 'spotify:playlist:23kjh45hk23jh345jh123k' }
(template shortened)
It logs testscript: Error executing script. Invalid data for call_service at pos 1: extra keys not allowed @ data['media_content_type'] ๐คทโโ๏ธ
I also don't understand why it rants about content_type instead of content_id
Try it without media_content_type
@deft timber ok, i fixed it. the sensor card i added in the ui doesn't really show anything besides a count every time the window is open/closed, though.
my original message data was here for reference; https://www.reddit.com/r/homeassistant/comments/ksx8su/please_help_me_to_make_a_simple_card_sensor_out/
thanks mono, thought that wasnt it, I was the problem.
Its media_player.play_media, not media_player.media_play ๐คฆ ๐คฆ
Ah, yes... media_play and media_pause are for the currently playing media. play_media is 'go play this thing'.
The names aren't ideal ๐
Is there any way within a template to figure out if the current system's location calls for units in ยฐC or ยฐF? Like, I want to literally send a string ยฐC if the current locale calls for ยฐC.
your temperature sensor for your wather integration has a attribute "unit_of_measurement". So you can determine from your weather.home which comes right out of the box in HA what the unit is
annoyingly, the two that i'm using currently (met.no and nws) don't seem to have that
you dont have to search for the sensor which is created by the weather-home
That's the stock met.no provider that is selected by default when deploying a new hass installation
oh I see the sensor i have is from my open weather map integration, sorry ๐
the nws sensor (really good if you're in the US) similarly doesn't offer unit_of_measurement
Yeah okay if you have the open weather map integration my way will work. I think there is no easy solution for that except comparing the location with ''closest'
and some example coordinates for regions with fahrenheit and celius
One would imagine that since the NWS is based in the US, it would always surface data in imperial. No need to figure out which region you're asking for data from.
so my problem is... this is being developed as part of my HASP project, which means the template is going to land on other people's system, and i don't know ahead of time which weather providers they will have installed or which region they are in
i could create some if-else monstrosity to check each provider and make a guess, which would be great right up until one of them changes and then all my users have a broke config