#templates-archived
1 messages · Page 160 of 1
And suggestion: use the template below, it will filter out sensors which do not have a correct value, making sure you don't get an incorrect result because the float function defaults to 0
{% set hum = [ 'sensor.living_room_humidity', 'sensor.kitchen_humidity', 'sensor.office_humidity', 'sensor.master_bathroom_humidity', 'sensor.guest_bathroom_humidity' ] %}
{{ expand(hum) | selectattr('state', 'is_number') | map('float') | average }}
using float without a default (or other safeguard) will cause errors in the near future
Is it possible to say is a number < 69 in this list?
{{ (state_attr('weather.openweathermap', 'forecast') |
map(attribute="temperature") | list)[0:16] }}
@silent vector You want to check if any of those numbers is below 69?
{{ (state_attr('weather.openweathermap', 'forecast') | map(attribute="temperature") | list)[0:16] | select('<', 69) | list | count > 0 }}
Yes that's what I wanted to do. Thank you.
For some reason this template is not working. In the logbook I can see the variable entity_id did go to paused.
- wait_for_trigger:
- platform: template
value_template: '{{ is_state(''entity_id'', ''idle'') or is_state(''entity_id'', ''paused'') }}'
If I used a fixed entity_id (not a variable) it works. But when using the variable it doesn't. The script is getting the variable from a service call and evaluates Correctly in other areas of the script.
don't put entity_id in quotes, it's a variable not a string
if you put quotes around a word in templates, you're literally turning that word into the letters it represents.
Whoops, that fixed it.
for example, if a variable named foo contains the phrase "Hello", when you access it, you'd just use {{ foo }} and the template will return "Hello". However, if you put foo in quotes {{ 'foo' }} the template will return the literal letters foo
I understand now. Thank you for the explanation.
Just saying hello buddy. You guys have helped me a lot I'm appreciative. I've been lurking for months. Understand this is not a chat channel.
There's #the-water-cooler for chatting
Understood. Thanks fes
Oh thank you. Is there a place you can suggest so I can learn more about the templating system? I looked over the official docs and got a little confused...
There are a number of pinned posts here in this channel
otherwise, just start using them, ask for advice once in a while and learn while doing 🙂
@mighty ledge you did help me awhile ago with my rest api sensor for mygekko for the template switch. I need to convert this now into an restful api item but not sure how to map the api url accordingly. could you please help me taking a lot at that?
How to match a light MQTT json response in a state_value_template?
Cant get the following to work:
state_value_template: "{% if value_json.val == false %} off {% elif value == true %} on {% endif %}"
Response topic:'''{
"ctime" : "2022-05-16T16:53:32+0200",
"props" : { },
"serv" : "out_lvl_switch",
"tags" : [ ],
"type" : "evt.binary.report",
"val" : false,
"val_t" : "bool"
}
I am trying to understand the relationship between resource: http://192.168.1.12/status.xml and json_attributes_path: "$.response.system" from this example: https://www.home-assistant.io/integrations/rest
My rest sensor currently uses resource: https://live.my-gekko.com/api/v1/var/lights/status am I correct to assume my new resource: would be resource: https://live.my-gekko.com/api/v1/var/ and my json_attributes_path would be $.lights.status ? I tried it out but it didn't work
dumb question, where would i place it in my template? just replace the value_template stuff? also do i need to do 2 seperate platform: template entries for my sensors?
Yes, that would replace the template you posted
And you can define multiple sensors under platform: template. However, that is the legacy format
Hi, i got an automation with a wait_for_trigger action. Any way to check if that trigger has fired? I want to do further actions if that happens and also if not.
yes, if a trigger fired, there will be a wait.trigger object
Sounds like what I'm looking for. Any docs for that?
Awesome. Thanks for that.
So this will work?
{{ 'Ladeautomation' if is_state('wait.trigger','none') else 'ACHTUNG' }}
what is the updated format?
It's in the link right under my post 🤨
also is there supposed to be an extra comma in here? im not to sure what the format is
not that I see
sorry, i thought you mean the link had the older format.
okay. code serve was yelling about it. i will try it
It has both
What do you mean with an extra comma, where would that be?
i have no idea, i just know the studio code server is yelling about it
i have the message end of the stream or a document separator is expected missed comma between flow collection entries`
oh i guess i had the formatting messed up
sorry
im dumb
i can't get the template to work. it just returns 0....
is it because in the object the state is <state sensor.master_bathroom_humidity=52.1; and when we map it to float its turning to 0 because of all strings?
{% set hum = [ 'sensor.living_room_humidity',
'sensor.kitchen_humidity',
'sensor.office_humidity',
'sensor.master_bathroom_humidity',
'sensor.guest_bathroom_humidity' ] %}
{{ expand(hum) }}
{{ expand(hum) | selectattr('state', 'is_number') | map('float') | average }}
np. you're helping me
that extra {{ expand(hum) }} is me trying to figure things out
{% set hum = [ 'sensor.living_room_humidity', 'sensor.kitchen_humidity', 'sensor.office_humidity', 'sensor.master_bathroom_humidity', 'sensor.guest_bathroom_humidity' ] %}
{{ expand(hum) | selectattr('state', 'is_number') | map(attribute='state') | map('float') | average }}
That is what it should be
yay
I forgot to select the states
Jep
i am trying to convert to the new format
https://www.codepile.net/pile/nra40XgE
but when HA starts it says that config is invalid
Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 11)
Hello. How can I get a list of the entity-ids of lights in a group?
the code editor is also saying i am missing property platform
If you are talking about a Home Assistant light group, they are listed in an attribute called entity_id
Did you put the code in sensor.yaml?
ya
Awesome. Thank you.
That's not the right place, it belongs to the template integration, not the sensor integration
wait, does it need to be sensor.yaml? in my configuratoin.yaml i have
sensor: !include sensors.yaml
now i am confused....
it sounds like i can put it in either on? just need to format it differently depending on where i put it?
These new format template sensors belong to the template integration
The legacy format belongs to the sensor integration
what should my configuration.yaml file look like for that? have a template: !include template.yaml?
Yes
Or put it directly in configuration.yaml
But I would go for the separate file
okay
so i ahve the template file. i just renamed my sensors.yaml to that
same format, but now it says property template is not allowed. i assume it is safe to delete it?
Remove the first line with template:
You already have that in configuration.yaml
And remove two spaces of every other line 😅
so is everything going to move over to the template ?
No, there are a lot of other sensor types which will stay under sensor
For example the workday sensor
Other sensor platforms
for what i was doing, does it matter where i put it?
Well the new format supports some new stuff, like state_class which is used for long term statistics
I don't know if you want to keep track of this average humidity, not creating a sensor which allows you to look back at the humidity for a longer period would be easier with the new format
And I don't know if they are planning to remove the old format in the future
I've been wondering about new format vs old. I have mixture of both and would be a big job to migrate. Can't imagine that removing the old would go down well with the user base.
is there a place that compares the old and the new ?
I did it after support for the new format was added to packages. It was mostly find and replace honestly. The only tricky bit is if you have a lot of places where what you had put for the entity ID and the friendly name don't match. I really didn't care enough about my UI to battle with that so I just changed name to be something that slugifies to the right ID in all cases. If that name really bothered me then I changed it in the UI (since I add unique ID to everything I can) but most of the time it was good enough and my only priority was that automations kept working
I guess the one thing that could get weird is if you used a lot of friendly_name_template. Technically that's still supported since name allows you to provide a template but I have no idea what the entity ID would be in that case. I would guess you are pretty much required to add a unique_ID in that case so the entity ID can be changed in the UI. Otherwise the entity ID would either be the slugified template or the slugified value of that template at the time the template sensor was added to HA, both of those options are bad IMO (slugified template is pretty ugly, slugified value of the template is even worse since it changes). I've never used that option before so I don't know what happens there.
But yea other then that :%s/value_template:/state: and :%s/_template:/: does most of it
Fair comments but I’d guess the vast majority just copy stuff and hack it together to get things working without understanding it. I’m probably in that category but have been working to try and improve my knowledge.
well I will say I think you'll find the new structure definitely provides vast room for improvement. Trigger template entities are pretty game-changing if you take the time to figure them out. Like I basically don't have automations that change helpers anymore (maybe one? its very rare for me now). Instead I refactored all of those helpers to be trigger template entities
So like to give an example I had an input_select I used for my sleep tracker. When a webhook comes in from sleep as android it set the select to the current value from the app. When I changed the value another automation then fired a notification command to start/stop/pause the sleep tracker. Now both of those automations are gone, its a single trigger template select. The webhook trigger sets its state and any time its changed (whether in an automation or somewhere else) it fires the select_option service
I did that kind of stuff all over. Major reduction in both helpers and automations. Kind of complicated YAML but at least everything about those sensors (setting the state and what happens when it changes) is all in one place
Don’t migrate over then, no reason to
Speaking from experience, I’d only get worried if all template integrations swap to the new style
And right now we are 30/70 new vs old
And it’s been this way for 6 months with no movement
Expect all new template integrations to follow the new style and expect added features to only get added to the new style
And by features I mean yaml configuration features, not the jinja templates themselves
Will add migration to my list of things to do. All my recent work is in Template:
i'm in a new place and kinda wanna make sure i d
ont need to rewrite anything in the next year or so
I'd just keep doing that and convert whenever you see something that helps reduce an existing template
converting might just help you learn then
the only "drastic" change is friendly_name_template doesn't really have a 1 to 1 conversion in combination with unique_id. You might have to edit your entity_id's afterward in that situation.
Hi everyone, can you guys help me with a template?
Here's the problem, my NAS server send it back to me the amount of free disc. But, sometimes it send it in M,G,T(Mega, Giga, Tera). For example, if i request my 1 HD, the answer will be 160G. And if i do the same request for the 2 HD, the answer will be 3.6T.
How can i template that? I tried the {{ value.replace('G','') }}, but i can only replace 1 information for time. I need all data in G, to do so, i need to multiply when the value is in T for 1000, do nothing when is in G, and divide by 1000 when is in M.
My code so far:
- platform: snmp
name: 'Free space NAS'
host: 192.168.68.107
baseoid: 1.3.6.1.4.1.5127.1.1.1.8.1.9.1.5.1
community: 'public'
version: "2c"
value_template: "{{ value.replace('G','') }}"
unit_of_measurement: "GB"
accept_errors: true
scan_interval: 300
You’ll have to search for each character and then covert the value for each one you find
Tb would need to be multiplied by 1000 to get gb, where GB would just need to strip the units
You’ll need an if case for each conversion
i really dont know how to do that, im really stupid for templating
Basically if GB in value, then strip the gb and output the value. If TB in value, strip the TB and multiply by 1000
Well I’m on mobile so I won’t be able to write it out
the way it's now its working only for the G units
You should try starting with a basic if statement inside the template editor
because it dont need any conversion, just the removal of the letter G
{% set value = "1.3T" %}
{% set size = value[:-1]|float %}
{% set unit = value[-1] %}
{% set size = size * 1000 if unit == 'T' else size %}
{% set size = size / 1000 if unit == 'M' else size %}
{{ size ~ 'G' }}
Damn, you guys are awesome, ill try out, thanks
@lucid bramble posted a code wall, it is moved here --> https://hastebin.com/riwihaqilo
@lucid bramble posted a code wall, it is moved here --> https://hastebin.com/exabofower
@lucid bramble posted a code wall, it is moved here --> https://hastebin.com/ukaxeyowob
Not sure how to post the code 😦 keeps being moved to hastebin
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Ok so let me try again.
Need some guidance on creating a condition in an automation.
Scenario is :
Have Zone `"Home"
Have Zone B which is about 2 mins from Home
Want to have a condition where I only want the automation to trigger when User A enters Zone B but hasn't been home for more than 15 mins that way it won't trigger when Zone B is entered when coming from home.
- condition: state
entity_id: person.usera
state: not_home
for:
hours: 0
minutes: 15
seconds: 0```
The complete code is here: https://dpaste.org/hQ4Ck
This conditon doesn't seem to work
Loving the new iif
your syntax is wrong. Did you run a config check?
you have a condition sitting within a trigger
The other issue is that it will never be true, since the trigger is entering a zone. You cannot both be in not_home for 15 minutes at the same time that you just entered zone.b
one way to do this sort of thing is to create a template binary_sensor that reflects what you care about, and use that in the test
Maybe my statement wasn't clear.
Zone Home ----> 2 mins to Zone Portal/Gate ----> Outside
I'd like to have a notification when User comes back home and arrives at the Portal Zone
or you can simply use a state trigger with from: 'not_home' and to: zone.b
ok, and you'll be "not_home" between home and zone.b
Yeah but that will get it triggered when it leaves home as the Portal Zone is 2 mins away from home. I thought of having the Portal Zone overlap with home but don't find this clean
exactly
so I wanted to make sure you were not home of at least 10 mins
which would mean you are coming from the other side of the gate
I would use a template binary_sensor with {{ is_state('person.b', 'not_home') }} with a delay_on: '00:15:00' and delay_off: '00:02:00' or whatever makes snese
so it turns on when the test is true for 15 minutes and turns off when it's not true for at least 2 minutes. that way, it will be "on" when coming from outside and "off" when coming from home
Hum.. ok not being the best in templating I'm not sure how to fully get this one done but l'll try to figure it out. But I understand the idea. So the condition would be the binary sensor state
yes, specifically that it's "on"
I think I got it: Will have to check the next time the user comes back :
- binary_sensor:
name: "User Outside"
state: "{{ is_state('person.user','not_home')}}"
delay_on: '00:15:00'
delay_off: '00:05:00'
You may want to tune delay_off in case the user comes home and then goes right out again. I thought you cared about entering zone.b, in which case it could be 30s
You just want it to be on long enough for the zone trigger, but to turn off as soon as possible after that
I have a shelly dimmer that is reporting itself to home assistant as a light. I can see the attribute of brightness (79) but I want brightness_pct, but I can't seem to pull that value in a template. Am I calling it incorrectly or do I need to figure out a conversion from brightness to pct on my own as a template sensor?
If i call the brightness {{ state_attr('light.t2_humidifier_level', 'brightness') }} I get 79, if I add _pct I get "none"
I can just make a template sensor that divides brightness by 2.55 I just don't know if there is a way already possible
What attributes does it have? It's not just a matter of adding _pct, but that it actually has the attribute
it does not have the brightness_pct attribute
so I just made a template sensor for it with brightness/2.5 | round (0) and looks all good
is there a way to template a light into a "switch"
i have a nice switch group that I want to turn this "light" on/off with but can't because one it's not a switch
oh nevermind i know what I should do
i'll make a template switch that turns the light off and on
I can call a light.turn_on inside a template switch right?
yes, that's possible
hi, I have a binary sensor that shows up as unknown and I don't know why
- binary_sensor:
- name: "Outside cold"
delay_off: "36:00:00"
state: >
{{ state_attr('weather.home','temperature') < 11 }}
- name: "Outside cold"
I also had delay_on: "36:00:00" but I took it out hoping that was the cause it kept showing up as unknown
and still no dice
What does the template show in
> templates
state: >
False
nevermind, I went around it: took out the delay off as well and just made an input helper using that for the offset
okay
but thanks for your help, TIL I can check templates using that tool!
How do you set this input_boolean now?
I don't think that will work reliably with a period that long. If you reboot in that period it won't work anymore, I just tested that with a light and a for of 5 minutes
That does seem to make sense but I think I had it like this before and it worked
What would you recommend instead?
What is your goal with this sensor?
I need help with the state_value_template. I cant figure out why its not working. 😦
state_value_template:
"{% if value_json.val == false %} off {% elif value == true %} on {% endif %}"
Response topic:
{
"ctime" : "2022-05-16T16:53:32+0200",
"props" : { },
"serv" : "out_lvl_switch",
"tags" : [ ],
"type" : "evt.binary.report",
"val" : false,
"val_t" : "bool"
}
@wooden tusk To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
"{{ value_json.val }}"
Tried that too but is not working. I then thought the problem were the true vs on.
it's for having all the heating automations in my house to switch off once a certain outside temp is achieved anually. So far, below 11*C with an offset of 36 hours seems to do the trick
What is the template going into?
Mqtt light
conversely all the cooling elements automations get turned on when my 'outside heat' sensor is triggered. This way, I don't have to mind climate all around the year
And what do the docs say for expected payloads for on or off?
ON or OFF
Change payload_on: true and payload_off: false and that template I wrote above will work
I’ll test! Thank you so much!
It’s just strange because the command topic works. How come i need to define the payload_on/off to true/false?
Because the docs say they default to ON and OFF
Just tested and the entity is still unknown. The payload now only carries True or false.
light:
- platform: mqtt
name: "Storage Roof"
state_topic: "pt:j1/mt:evt/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
command_topic: "pt:j1/mt:cmd/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
payload_on: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":true,"val_t":"bool"}'
payload_off: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":false,"val_t":"bool"}'
state_value_template: "{{ value_json.val }}"
payload_on: true
payload_off: false
qos: 2```
So no template?
You have it defined twice too
Gimme a minute and I’ll review the docs again
@wooden tusk are you sure your command topic matches your state topic?
also, are you sure that in order to turn the light on, you need to have '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":false,"val_t":"bool"}'?
The only difference is the "mt/evt" vs the "mt/cmd" part
Ok, but you're 100% sure you need the entire payload to be that whole mess?
Not sure, found the example in the MQTT Futurehome
I can try wo the whole part. Then just keep the "Val" attribute
Hi to all :-),
wouldn't anyone advise how to make a "light" entity usage chart? Respectively, how many hours a day is it on? 🙂
#integrations-archived , ask about history stats
Ok, thanks 🙂
At a bare minimum, I would expect this to work:
light:
- platform: mqtt
name: "Storage Roof"
state_topic: "pt:j1/mt:evt/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
command_topic: "pt:j1/mt:cmd/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
payload_on: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":true,"val_t":"bool"}'
payload_off: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":false,"val_t":"bool"}'
state_value_template: "{{ value_json.val }}"
qos: 2
assuming that your json in the topic is what you posted above
worse case, if that doesn't work then this might work
light:
- platform: mqtt
name: "Storage Roof"
state_topic: "pt:j1/mt:evt/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
command_topic: "pt:j1/mt:cmd/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
payload_on: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":true,"val_t":"bool"}'
payload_off: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":false,"val_t":"bool"}'
state_value_template: "{{ 'on' if value_json.val else 'off' }}"
qos: 2
however you might need to go the json configuration route due to your complex payloads
light:
- platform: mqtt
name: "Storage Roof"
schema: template
state_topic: "pt:j1/mt:evt/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
command_topic: "pt:j1/mt:cmd/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
command_on_template: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":true,"val_t":"bool"}'
command_off_template: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":false,"val_t":"bool"}'
state_value_template: "{{ 'on' if value_json.val else 'off' }}"
qos: 2
Thanks! Im testing now
Tried the first: The state value is not working, but the command is.
did you try the last one?
that's the one I think you need
So no conditional check against true/false in the state_value_tamplate?
did you look at the 3rd one I posted? It has the true/false check...
{{ 'on' if value_json.val else 'off' }}"
yes, but the if conditional is not validated against anything
yes it is?
value_json.val returns true or false
you don't need to say if value_json.val == True, that's implied
Sweet!
When adding schema template the configuration fails, the payload_on is not allowed
that would be something for #integrations-archived
moved to integrations
Just copy and paste what I wrote. The fields are completely differnt
It seems like the state_value_template is not valid
how so? did you copy/paste the entire configuration?
instead of modifying what you had
yes, should it be state_template instead?
state_value_template is not in the doc
For schema template
it should be whatever the docs say
It is in the docs in this example: https://www.home-assistant.io/integrations/light.mqtt/#brightness-and-rgb-support
which is state_topic
"The system cannot restart because the configuration is not valid: Invalid config for [light.mqtt]: [state_value_template] is an invalid option for [light.mqtt]. Check: light.mqtt->state_value_template. (See ?, line ?)."
light:
- platform: mqtt
name: "Storage Roof"
schema: template
state_topic: "pt:j1/mt:evt/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
command_topic: "pt:j1/mt:cmd/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:6_0"
command_on_template: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":true,"val_t":"bool"}'
command_off_template: '{"props":{},"serv":"out_lvl_switch","tags":[],"type":"cmd.binary.set","uid":"b1045ae0-d2bc-11ec-901b-194ce6613fff","val":false,"val_t":"bool"}'
state_template: "{{ 'on' if value_json.val else 'off' }}"
qos: 2
that's not for schema: template
Yeah, I was not reading properly 🙂
state_template works for the schema. Restarting now
it's a shitty document
Boom! It works! 🙂
👍
So happy with your patience! Thanks alot!
Can the value of an input_number's minimum and maximum value be an "entity" ?
seems not:
min float REQUIRED
Minimum value.max float REQUIRED
Maximum value.
so following up on this: #automations-archived message
the context id is different every time, so i can use the user id to say assume that if the user id is none, it was triggered by an automation or a service, but if i want to use the context id, id need to have the automation save the context id to an input_text and check against that, or is there a simpler way to do the latter?
thanks @inner mesa
@inner mesa out of curiosity if a template value/entity value could have been put in that box, what would the documentation say instead? (because its possible to read that as you must give it something, as opposed to reading it as you must give it an integer).
it would say "Template" if it supported a template, which is a way to provide the value of an input_number, but I don't know if there's a consistent way to specify just an entity
hey so I want to create a sensor whose value contains the sum of all entities of domain power that contain the string "Home-NAS". how would I select the entities by name?
current "code" in configuration.yaml
sensor:
- platform: template
sensors:
Home-NAS_Power:
friendly_name: "Home-NAS Power Consumption"
unit_of_measurement: 'W'
value_template:
Hey folks.
The following trigger has stopped working since I updated to 2022.5 a few days ago. Can anyone point me in the right direction as to why?
trigger:
- platform: template
value_template: >-
{{ now().strftime('%a %h %d %H:%M %Z %Y') ==
(((state_attr('sensor.phil_s_mi_a1_next_alarm', 'Time in Milliseconds') |
int / 1000) - 30 * 60 ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}
nothing about that in the changelogs on github?
also what was your previous version?
and have you tried "disassembling" the template step by step in the developer tools "template" tab? you should find where it goes wrong
Try:
{{ now() >= as_datetime('sensor.phil_s_mi_a1_next_alarm') - timedelta(minutes = 30) }}
That will work way better as your string comparison
It can for a template number.
What is the domain power? Are you sure they are not sensors?
its all sensors but they are of device class power I read that here https://www.home-assistant.io/integrations/sensor/
You said domain, not device_class
still relatively new but slowly getting the hang of that weird yaml system with pseudo code
{{ states.sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'power') | selectattr('name', 'search', 'Home-NAS') | map(attribute='state') | select('is_number') | map('float') | sum }}
wait I can just search for name
damn okay thanks I will try this!
ok actually I made a mistake and they dont have the attr device_class but instead the attribute "level_2" which needs to equal 'Power'.
HA doesnt accept anthing else than "name" in selectattr() tho?
(selectattr('attributes.level_2', 'eq', 'Powers')
->
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'level_2')
you need to add selectattr('attributes.level2', 'defined')|
no wait I think I mis-explained it
my sensors have something along the lines of these attributes (OpenHardwareMonitor integration)
Level 0: HOME-NAS-1903
Level 1: Intel Core i7-4790K
Level 2: Powers
Name: CPU Cores
Minimal value: 3.4
Maximum value: 75.6
I need to select all sensors of them that have "Powers" as level_2
you need to figure out the actual attribute name
but it only lets me put in 'name' as a selector
you can put anything as the selector
I used device_class didn't I?
apparently not : UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'level_2'
Just replace it with the attribute you need to check on
is that the actual attribute name?
To me, it seems suspect seeing that you listed it as Level 1 above
And if it is, Rob already mentioned how to prevent this error, and I put it on the right place in my template
so which is it, level_1 or Level 1
developer tools shows me
level_0: HOME-NAS-1903
level_1: Intel Core i7-4790K
level_2: Powers
name: CPU Cores
minimal_value: 3.4
maximum_value: 75.6
unit_of_measurement: W
friendly_name: HOME-NAS-1903 Intel Core i7-4790K Powers CPU Cores
ok, so it's level_1 and doing what rob said, but changing the attribute from device_class to level_1 will work
Okay, then just adjust the template I proposed (and corrected) accordingly
{{ states.sensor | selectattr('attributes.level_2', 'defined') | selectattr('attributes.level_2', 'search', 'Power') | selectattr('name', 'search', 'Home-NAS') | map(attribute='state') | select('is_number') | map('float') | sum }}```
but according to your stuff, that won't work either
OHH now I get it I need to check if it has said attribute first
You need to keep in mind that these filters are case sensative
since everything has 'name' you dont need to for 'name'
thanks a bunch!
is there also case insensitive search?
name, state and entity_id are not attributes, so that is why attributes. is not needed there
No, rejectattr()
ahh thanks!
this and something with a placeholder? or match not entire words?
i.E. I want to exclude sensors with a Name containing either Core or Cores
didnt work for me for some reason
The name shown here containing Core is an attribute
The name which is not an attribute will be the same as the attribute friendly_name
I just figured it out I need to use attributes.name so it works reliably
thank you all I now have accurate power consumption tracking for my PCs without needing seperate hardware!!
well I think I still have one issue:
VS Code editor complains that my multiline doublequoted string needs to be sufficiently indented..
.share the code of the template sensor
Hmm, bot down? Use a code sharing site like dpaste.org or codepile.net
https://imgur.com/a/kZOCj5F
what would be the correct indentation for this?
ohh I just tried a screenshot and uploaded it to imgur since this channel doesnt allow them
is this okay tho?
why would you send a picture of text instead of just sending the text?
hassbot always screws up my messages along with the code but I'll do
Use the multiline format for a multiline template :)
@warm heron posted a code wall, it is moved here --> https://hastebin.com/adejacamiz
value_template: >
{{
states.sensor
| selectattr('attributes.level_0', 'defined') | selectattr('attributes.level_0', 'search', 'NAS')
| selectattr('attributes.level_2', 'defined') | selectattr('attributes.level_2', 'search', 'Powers')
| rejectattr('attributes.name', 'search', '#')
| rejectattr('attributes.name', 'search', 'Core')
| rejectattr('attributes.name', 'search', 'Graphics')
| map(attribute='state') | map('float') | sum
}}
And your template should be intended, so your gaming power sensor needs more indentation
thanks! now it seems to work!
now I just gotta dynamically create attributes dynamically so I can
- see which sensors are being collected and
- use the sensor in more ways reliably
hmm so could I have code in my custom_sensors.yaml that creates a sensor for each of the openhardwaremonitor integrations configured?
more or less having a template at the
platform: template
sensors:
level?
something along the lines of this logic:
foreach (host in platform(openhardwaremonitor)) {
sensors.add(
PC_Nr:
foreach (item in List[CPU, GPU, DRAM, Motherboard, PSU].defined("Powers")) {
item: getHighestNum()
}
)
}
where item would be the according abbreviation for the hardware type
@marble jackal @warm heron Sorry for not replying earlier, I had to go afk for a few hours.
@marble jackal This doesn't appear like it will work as the following resolves to "None" in the developer tools template checker.
{{ as_datetime('sensor.phil_s_mi_a1_next_alarm') }}
@warm heron I was on 2022.4 previously. I have tried to "disassemble" the template. I must be missing something.
e.g.
now().strftime('%a %h %d %H:%M %Z %Y') =
- {{ now().strftime('%a %h %d %H:%M %Z %Y') }}
Alarm 'Time in Milliseconds' formatted to match now():
- {{ ((state_attr('sensor.phil_s_mi_a1_next_alarm', 'Time in Milliseconds') | int / 1000) | timestamp_custom('%a %h %d %H:%M %Z %Y')) }}
Alarm milliseconds formatted minus 30 minutes:
- {{ (((state_attr('sensor.phil_s_mi_a1_next_alarm', 'Time in Milliseconds') | int / 1000) - 30 * 60 ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}
Gives me:
now().strftime('%a %h %d %H:%M %Z %Y') =
- Tue May 17 22:55 BST 2022
Alarm 'Time in Milliseconds' formatted to match now():
- Wed May 18 08:00 BST 2022
Alarm milliseconds formatted minus 30 minutes:
- Wed May 18 07:30 BST 2022
@marble jackal Just realised that you probably meant to include states in there. Like this?
{{ as_datetime(states('sensor.phil_s_mi_a1_next_alarm')) }}
Yes I'm going to try this for tomorrow morning:
{{ now() >= as_datetime(states('sensor.phil_s_mi_a1_next_alarm')) - timedelta(minutes = 30) }}
Hello, can somebody tell me how to change the end of this template to check if the sensor's last date was > 24 hours ago please? {{ now().timestamp() > state_attr('sensor.weather_station_last_rain', 'timestamp')|float(0) }}
the date/timestamp comes over like this: May 17, 2022, 5:50 PM
Hello, I do have template switches with on / off actions in place to control my lights. Now I would like to add blinds that have a state between 0 and 100%, how can create a template supporting this?
the example only lists on/off state but I need to specifiy state in percent
use service: cover.open_cover and service: cover.close_cover
@modern sluice : {{ (as_timestamp(now())-as_timestamp(states.sensor.weather_station_last_rain.last_changed)) | int > 86400 }}
thank you, that's what I didn't know (how it needed to be converted)
Yes, correct. I forget to include states()
Can anyone tell me whats wrong with the |selectattr('attributes.brightness', '>=', 254) part of the code?
data:
brightness_pct: '{{ states(''input_number.home_lights_brightness'') }}'
target:
entity_id: >-
{{ states.light|selectattr('state', 'eq',
'on')|selectattr('attributes.brightness', '>=', 254)|rejectattr('object_id',
'search', 'office_play_light_bar_top')|rejectattr('object_id', 'search',
'office_play_light_bar_bottom')|map(attribute='entity_id')|list }}
What is probably wrong, is that there are lights which don't have the brightness attribute even when they are on
For example lights converted from a switch
ah that makes sense
And why not search for office_play_light_bar_. You'll hit two birds with one stone then
Select on brightness being defined instead of the lights being on
good idea!
They will be on anyway when brightness is defined
what do you mean?
selectattr('attributes.brightness', 'defined')
Lights which are off don't have a brightness attribute
So you will filter out the lights which are off and the lights for which the brightness can't be set in one go
'search', 'office_play_light_bar_top')|rejectattr('object_id', 'search',
'office_play_light_bar_bottom')|map(attribute='entity_id')|list }}```
You are still doing two searches which can be combined in one
{{ states.light|selectattr('attributes.brightness', 'defined')|selectattr('attributes.brightness', '>=', 254)|rejectattr('object_id', 'search', 'office_play_light_bar_')|map(attribute='entity_id')|list }}
Looks good, does it work in
> template?
it does but I still get an error when I run it in an automation
service: light.turn_on
data:
brightness_pct: '{{ states(''input_number.home_lights_brightness'') }}'
target:
entity_id: '{{ states.light|selectattr('attributes.brightness', 'defined')|selectattr('attributes.brightness', '>=', 254)|rejectattr('object_id', 'search', 'office_play_light_bar_')|map(attribute='entity_id')|list }}'
Error rendering service target template: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'brightness'
shows up as:
"light.kitchen_back",
"light.kitchen_centre",
"light.kitchen_front",
"light.living_room_back_left",
"light.living_room_back_right",
"light.office_front",
"light.office_play_light_bar_bottom"
]```
which are all hue lights..
Are you sure you reloaded the automation?
The bottom one should have been filtered out though
thank you, looking at this now
Hey,
Im trying to create a "device" from MTQQ information, that gets total energy used (Electricity), but its not showing up in the energi dasbhard?
- platform: mqtt
state_topic: "heater/18760NE2240322014631/EnergyTotal"
unique_id: "EnergyTotal"
name: "Energy Total"
device_class: energy
state_class: total_increasing
unit_of_measurement : kWh
Does it show the correct state in
> states?
The site that communicates with xml tells me to import the unit_status value into ha, how should I write grep?
Can you help me with a personal chat? I can't attach a picture...
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
use link above to share images
I just joined so I don't have the authority. How can I get the authority?
you'll never get image athority
0 people can post images
use the link above to share images
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
read hassbot
@dusky jacinth are you going to ask your question and use imgur or give up?
Why do you have to use impgur?
it's the rules...
read hassbot
are you completely ignoring the bot post above?
click the imgur link and post the image, it's not hard
Thanks
giving up it i see
I'm sorry that I didn't say anything, but I'm Korean, so when interpreting English, you said it could be interpreted differently from your intention, and it's a rule, but post the picture as soon as I sign up for the discode? There's no such thing in the notice And if I have to post a picture, you have to explain what picture I have to post And there's no part to upload even if you go into the website. How would I understand if you leave out all the descriptive words and just tell me what's not in the notice?
You cannot post images. No one can post images.
You have to use an Image sharing website.
Then you post a link to the website with the image here.
Read this ⬇️
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
Like this https://imgur.com/a/oYtHhDL
Thank you.
The site that communicates with xml tells me to import the unit_status value into ha, how should I write grep?
Thank you
Is there a way to return a list of full state objects for all the entities in an area? {{ area_entities('kitchen') }} returns a list of entity_ids.
Ultimately, trying to find all the entity's in an area that match a specific device_class
expand() will do exactly what you want
{{ expand(area_entities('kitchen')) }}
Thanks @marble jackal
{{ area_entities('kitchen') | expand | selectattr('device_class', 'eq', 'temperature') | list }}
That should be right? But I get an error
UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'device_class'
Filter on those entities which have a device_class attribute first
selectattr('attributes.device_class', 'defined')
And device_class is an attribute, so what to have now won't work
Hey, i have issue with RestAPI Sensor. I create temperature sensor with API provide by memmert (it's incubator in RJ45) but when create the sensor this returns "unknown". Do you any solution ?
@nimble copper and what do you want as result, because now you will get a list with state objects
Not with any further information.
.share your current configuration
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
look integration channel
You want help right? Now I have to go looking in another channel for the information I would need to assist you? That's a bit strange isn't it?
Yes need help, I didn't mean to make a duplicate post
https://dpaste.org/xyFBH Configuration.yaml
https://dpaste.org/BOUtp API Webpage
the api just returns "Temp1Read": 37.0, ?
remove ?Temp1Read and post what that looks like
Not Found. But i have this page
With this
wait 2 sec ..
https://dpaste.org/iWweO "commands.cgi"
and you're sure there's no { or } before or after those chucks when you go to those URLs?
no this API is very very bad
ok
keep your tempread url
and use this template
value_template: "{{ value.split(':')[-1].split(',')[0].strip() }}"
this would also work
value_template: "{{ ('{{{0}}}'.format(value.replace(',')) | to_json).Temp1Read }}"
no, use the ?Temp1Read= one
this would also work
value_template: "{{ value.replace('"Temp1Read": ', '').replace(',','') }}"
https://dpaste.org/1OKUV Configuration.yaml it's ok ?
ok
yes
value_template: >
{{ value.replace('"Temp1Read": ', '').replace(',','') }}
ok x)
sorry
no worry
that should work even with no response
ok i restart hass
I LOVE YOU ❤️
It's Work
Now that I get the temperature, how set type of device ?
Add a unit of measurement an device class to temperature
thanks for help 🙂
value_template: >
{{ value.replace('"Temp1Read": ', '').replace(',','') }}. How close ">"
i want to create a template sensor which should be the number of seconds between the last two events of another sensor
or to turn it slightly around.. each time a switch is triggered, i want to record the number of seconds since the last time it run into a template sensor
The multiline part is closed when you enter a new key in the dict
something like:
template:
- trigger:
platform: state
entity_id: switch.fr_table_lamp
sensor:
- name: seconds_later
state: "{{ (now()|as_timestamp - trigger.from_state.last_changed|as_timestamp)|round(1) }}"
Okay Thanks
I have made a simple template that rounds the value of a zigbee temp sensor. But because I'm using zigbee2mqtt the sensor reports unknown for the first few seconds after a HA reboot. Because of this the template drops to 0. How can this be solved?
{{ states('sensor.beneden_temp') | float | round(1)}}
Isn't really a big issue when just viewing the state. But when viewing the history it's not that great
The site that communicates with xml tells me to import the unit_status value into ha, how should I write grep?
Hi, I'm looking for a way to display the list of all my lights in state on. That's doable. But I'd like to exclude all lights which already belong to a light group. Is that possible?
Sure, should be able to add rejectattr('entity_id', 'in', expand('light.whatever'))
but if you have multiple light groups that'll get expensive quick
Thanks, but I don't want to specify the group, since I have many. I'd like to reject an entity that belongs to any group.
You can make a list of all entities in light groups and use that instead, but I can't type it on my phone
The basic idea is to start with states.light, filter for entities that have an entity_id attribute, expand them, and set a variable to the result
You mean I compute all light entities in lights groups then reject entities in that list
I think I got it
I'm trying to set the list of all lights except the ones in groups, I use that:
{% set lights_in_groups = states.light | selectattr('attributes.entity_id', 'defined') | expand | map(attribute='name') | list %}
lights_in_groups {{ lights_in_groups }}
{% set all_lights_except_in_groups = states.light | rejectattr('attributes.entity_id', 'defined') | reject('in', expand(lights_in_groups)) | expand | map(attribute='name') | list %}
all_lights_except_in_groups {{ all_lights_except_in_groups }}
But the all_lights_except_in_groups continues to include lights in groups. What's wrong with my template please?
you keep using expand
you just need
{{ states.light | rejectattr('attributes.entity_id', 'defined') | map(attribute='entity_id') | list }}
states.light does not need to be expanded
yeah, that's better 🙂
That will give me the list of all the lights which are not groups, right?
right
But from this list, I'd like to reject all the lights which are in the list lights_in_groups, so I need to add an | reject('in', lights_in_groups) | right?
Yes that what I'm doing, but the result keep containing the items from the previous list
did you copy exactly what I wrote?
Yeah
and is your previous template correct that you're comparing it to?
But you agree that this template gives the list of all lights which are not groups. What I'm looking for is the list of all lights excluding the ones which belong to groups
That single line will return a list of entity_id's that are not groups
do you have a template that gets entities that are in groups?
and is it correct
Yes
post it
Here it is: {% set lights_in_groups = states.light | selectattr('attributes.entity_id', 'defined') | expand | map(attribute='entity_id') | list %}
you're still expanding
yeah, that's not doing what you think it's doing
If I don't expand, I have only the list of the light groups
right, but you can't concatentate lists like that
I obtain a unique list this way
it's only giving you the last iteration
Sorry, I'm a little bit lost
yes, that's what I'm trying to tell you
do you want entities that are in light groups?
{{ states.light|rejectattr('entity_id', 'in', expand(light_groups)|map(attribute='entity_id')|list }}
Okay, thanks a lot guys. So I was using expand the wrong way
2 edits for better variable names
still not sure why you're expanding in that phnx
{{ states.light|selectattr('attributes.entity_id', 'defined')|map(attribute='attributes.entity_id')|map('list')|sum(start=[]) }}
{% set entities_in_groups = expand(states.light | selectattr('attributes.entity_id', 'defined') | map(attribute='entity_id') | list) %}
{{ states.light | rejectattr('attributes.entity_id', 'defined') | rejectattr('entity_id', 'in', entities_in_groups) | map(attribute='entity_id') | list }}
yes, but he wants a list of lights that aren't in groups
right, reject all of those
so he needs the second line, where he rejects the groups themselves, and the group contents
so you have to expand what is in the group
ah, I assumed line 1 did that, i'd just do it there
{% set entities_in_groups = expand(states.light | selectattr('attributes.entity_id', 'defined') | map(attribute='entity_id') | list) | map(attribute='entity_id') | list %}
{{ states.light | rejectattr('attributes.entity_id', 'defined') | rejectattr('entity_id', 'in', entities_in_groups) | map(attribute='entity_id') | list }}
also, this doesn't work:
{{ [[1,2], [2], [3,4]]|map('list')|list }}
you still get the list of lists which i'm not sure expand would be happy with that
that's why I did this: #templates-archived message
Okay, because I was testing and it was not working.
Thanks guys.
oh neat. didn't know sum worked that way
that works fine with expand
lol, yep I get it
seems suboptimal to expand only to just get the list of entity_ids again
But it's pretty powerful
I love these discussions that I start and where I'm lost after some posts of people helping me 😄
usually the OP is long gone by now 🙂
it's just rabble at this point
That won't be polite 😉
Yeah sure, but I'm trying to understand what you're saying but things are going too fast for my slow brain
this beats remote debugging of somebody's network/DNS issues any day of the week and twice on Sunday
sometimes it helps me solve my own problems (although my own templates are usually much simpler) or provides ideas for useful enhancements
I forgot about sum on lists
{% set eig = states.light | selectattr('attributes.entity_id', 'defined') | map(attribute='attributes.entity_id') | sum(start=[]) | unique | list %}
that's probably the shortest way to get entities in groups
non-repeating entities if you have nested groups
without the map('list') it complained about adding tuples and lists
working for me 🤷♂️
I don't have light groups though
I wonder if their entity_id list is a tuple
neither do I. I was working with regular groups
this is what I was using:
{{ states.group|selectattr('attributes.entity_id', 'defined')|map(attribute='attributes.entity_id')|sum(start=[]) }}
TypeError: can only concatenate list (not "tuple") to list
ooooh
let me try that
Hah
so light-groups are lists
group-groups are tuples
ffs
really, yeah
{% set eig = states.group | selectattr('attributes.entity_id', 'defined') | map(attribute='attributes.entity_id') | sum(start=()) | unique | list %}
change your start to a tuple and it works
without mapping to a list
yeah, that's the syntax that I forgot about
FYI, it's really odd that jinja allows you to add tuples
it's annoying because it shows up with [] looking like a list in the template editor
well I guess it's not odd, python allows it too
I must be remembering C#
The template resolver turns tuples into lists
3. Profit
comma separated string, lists, tuples -> lists
{{ "'x','y'" }}
try that
it's clearly 'x','y' and it should be a string
if you want to get around the template resolver....
{% set x = "'x','y'" %}
{{ {'ret': x } }}
force it into a dictionary, and it won't type the values
this is how you can cheat the system
because you can template the entire data section and force your will on any field without it typing the field
I have the following sequence in a script. The If-then will not evaluate to True. My (not shown), else condition always executes. I've tried a template condition form as well as the short form. Note: repeat.item.code has the correct non-x value.```sequence:
- if:
- "{{ repeat.item.code }} != 'x' }}"
then: - service: shell_command.irsend
data:
code: "{{ repeat.item.code }}" - service: notify.persistent_notification
data:
message: "Processed code -{{ repeat.item.code }}-"
- "{{ repeat.item.code }} != 'x' }}"
Is there a form that works?
Is there a way to filter a list of entities and remove any that don't have an area_id?
I think it'll work with that change, but you may need to use - condition: "{{ xxx }}"
Sigh, thanks. I've got passed in variables on the brain and poor eyesight it seems
IT WORKS
I thought that I could make something out of this, but have failed: https://www.home-assistant.io/docs/configuration/templating/#areas
perhaps someone smarter than me can figure it out
I will go sit in the corner now
I thought the same thing. I thought something like this might work select('area_id', 'ne', 'None')
Alas, it does not.
Hi all. Is there a tool to debug templates other than the template evaluation tool in the front-end? That tool goes a long way but it doesn’t help as much when template errors creep up due to the way scripts and automations are called (e.g. when I’ve messed something up about the context, like not quite setting a for: loop that invokes a template up correctly)
Even a way to do a crude “print” statement to a log from inside of a template would go a long way.
you can log the contents of a template with a persistent_notification, or system_log. I do it all the time
you can also review the trace for the automation or script
I just figured out the former; it’s slightly more laborious but gets the job done. Thank you. How do I do the latter? I wasn’t aware of tracing
Oh man. I’ve only been working on this platform for a month and didn’t know. This could be game changing :). Thank you!
it's pretty darn great. it'll show you the value of variables, state changes, etc.
if you're editing automations in YAML by hand, just make sure you add an id: tag to them so they will record trace info
actually, says that in the docs:
Automations created in YAML must have an id assigned in order for debugging traces to be stored.
Thank you. Already figured out the problem via the ol’ “print debug” method. Now assigning id: to all the automations.
can this be added in the UI or do i have to do this in the yaml?
No, template sensors have to be created in yaml
Hello, how can I split the 100.00 out of this value attribute? it's a range from 0 to 100 with two decimals, so it can be multiple digits long or not:
"0;100.00;;0;90"
{% set value = "0;100.00;;0;90" %}
{{ value.split(';')[1] }}
thank you, can you explain the second row to me please so I do also understand it and not just copy it?
i want to take today's weather and embed that as a SVG or something on an image
split() will break up a string on whatever you specify into a list. result would be ["0", "100.00", "", "0", "90"]
you can access values in a list by its index starting with 0
[1] pulls out the 2nd value
what if i'm only interested in the last time it went on.. not necessarily all status changes?
thank you, this is really helpful to me
only open question I have for now is that I still need someone to explain json_attributes_path from https://www.home-assistant.io/integrations/rest/ to me
it's not mentioned in the descriptions
to get the template switch to actually work 🙂
Create a trigger-based template sensor that looks for that and track the last_updated time for that
"looks for that"? how? 🙂
i did this: https://bpa.st/OG3Q
so that should only trigger when the switch goes from off to on, but the problem is still the state
trigger.from_state.last_changed.. how can i filter that to only include the "on" state?
or maybe this will work.. look at the second to last change
you mean filter out the from_state if it's on? Your trigger is already doing that
@mighty ledge glad to see you! any chance you can take a minute and look at my Q above? you helped me last time so well on the rest topic
what's the question
I would like to move my rest sensors to https://www.home-assistant.io/integrations/rest/ but I don't understand how json_attributes_path works
I would like to understand how to split resource: https://live.my-gekko.com/api/v1/var/lights/status&username=1&key=2 into the resource + json attributes path
I tried all the versions I could think of but was unsuccesful
and I did not find documentation on that topic
because my template switches will require multiple sensors from the same endpoint and this does not work with the rest sensors
I can't view the resource, but json attributes path is a json path
"item0": {
"name": "BB 1",
"page": "EG",
"sumstate": {
"value": "state[0=Off|1=OnImpulse|2=OnPermanent]; sum[0=Ok|1=ManualOff|2=ManualOn|3=Locked|4=Alarm]",
"type": "STRING",
"permission": "READ",
"index": 250000
it won't be covered in HA's documentation because it's not an HA thing, it's a a json path. It's universal in many packages/languages
this is the output I am getting for above
I see
so lights.item0.sumstate.value would be a json path then?
post the full json
ok
so the root query
I would like to differentiate json paths for blinds and lights but I am not sure how to translate that from resource to resource + json path
@tawny kernel posted a code wall, it is moved here --> https://hastebin.com/nudiqabuma
but that's what the API is giving me
yeah but it seems like you're not copying and pasting the entire json
I am
oh great
Paste your json on the left, but it has to be valid
then you play with the path until it's correct
https://www.my-gekko.com/files/ombis/3014/EN_TUT_Query API.pdf here is the API doc
you can see example outputs that are the same as the one I pasted
and use $.a.b as the path, you'll get
[
2
]
as the result
well it says it's not
that's what I'm trying to tell you
can you copy the result from YOUR endpoint
not from that doc
I did
this is copied from my endpoint
I only changed username and key for privacy reasons
can send you a screenshot of the api output in the browser if you want
so I guess the way the API works is not compatible with the rest integration?
is there any other way to achieve this?
are you getting information when you just don't provide a path?
you said you were accessing this in other ways right?
yes, in a browser
but from hA?
and it's also working with the restful sensor integration
yes
you helped me getting this working
it's in template switches with rest sensors
ok, then it's valid json
not sure why it's not copying correctly from your endpoint
ok, i got it working with https://live.my-gekko.com/api/v1/var/status&username=1&key=2
maybe that's the root key I need
ok, the tool says:
[
"$['lights']"
]
would be the path for lights
I have $.lights
but typically, you'd want to select the light that matters to you
i'm not sure if the order changes
[
"$['lights']['item0']['sumstate']['value']"
]
is the output I get to come down to the value I need
do I need to convert that into $.lights etc? because when I do that the json says no match
for the json attribute path
yes, but json_attributes_path is for all attributes
you can't have it point at a non-dictionary
it cannot end in value, it has to end at sumstate
then you'll get 4 attributes if you specify them in json attributes: value, type, permission, index
can I still add &username=1&key=2 somehjow to this?
because the path explorer doesn't care about auth but I need to auth against that API
tried with username and password fields but it didn't like it
🤷♂️ how did you do it in the other sensors?
sensor:
- platform: rest
name: lights endpoint
resource: https://live.my-gekko.com/api/v1/var/lights/status?username=1&key2
json_attributes:
- item8
- item10
- item12
this way
but I can have only one sensor per endpoint here and I do need multiple that's why I am trying to switch it over
all you need is the ?username=... after whatever you're accessing
in the attributes or in the attributes_path ?
ohhhhhh
that makes sense
let me test this but if this works, one of the attributes will be "value"
is there a way to get back to "item8" as a value or do i need to specifiy this for every single sensor?
you specify the path and the atttributes you want to extract
there's no way around that
Error fetching data: https://live.my-gekko.com/api/v1/var/lights/status?username=1&key2 failed with All connection attempts failed
same url works in the browser
it should be working if it works in the browser with the username and pw
makes sense, why can't the path be value or sumstate though so I can extract all light items directly from there?
yepp, that was on me, fixed. connection succesful, no contents yet though
"JSON result was not a dictionary or list with 0th element a dictionary"
is now in the logs, so we are one step further, thanks already again for your great guidance
Yeah, but i want the last time it was on
json_attributes_path: "&.lights.item0.sumstate"
json_attributes:
- "value"
- "type"
- "permission"
- "index"
is that I have
this is what you meant, isn't it?
yes
still getting "JSON result was not a dictionary or list with 0th element a dictionary" on it
is there a way to debug why?
whats your url
works in browser
shows json
I copy the json into jsonpath.com
filter for lights.item0.sumstate
and get positive result
path output is [
"$['lights']['item0']['sumstate']"
]
it should be working then
any way to figure out why it isn't?
it's telling you that sumstate is not a dictionary
but it is
so, either your config is wrong or your url is wrong or something between there
if you can hit the endpoint in a browser and see the response, then take said response and plop it in with the path tester, and the path points to your data, then you should get data back.
yes that part works
[
{
"value": "0;;;0"
}
]
path view [
"$['lights']['item0']['sumstate']"
]
I literally click the link in the code
your output should be
[
{
"value": "state[0=Off|1=On]; dimValue[%]; RGBcolor[24Bit]; sum[0=Ok|1=ManualOff|2=ManualOn|3=Locked|4=Alarm]",
"type": "STRING",
"permission": "READ",
"index": 100000
}
]
that's the view without /status in there but that didn't work in the json explorer
let me retry without status
you then asked how we did it for the other sensos and that had the status in the url
I can't see your URL or your endpoint, so you're driving the sitauation here. If this was an endpoint that was accessible from the internet I could give you better pointers.. sorry.
JSON result was not a dictionary or list with 0th element a dictionary
same error
fair point, did DM you full output for both
can you access that?
sry give me a min
sure
not implying any expectations on timing or anything at all, just want to ensure you have what you ask for
HAH
I got that to work
i found this https://github.com/home-assistant/core/issues/41753
changed attribute_path to: json_attributes_path: "$['lights']['item0']['sumstate']"
and it's now filled with the 4 attributes you said
so is it working then?
I think it is
this is fantastic
thank you so much for your help again
my offer for a virtual drink still stands and is obviously doubled now
my missing piece was the username in the resource and understand that json_attributes_path properly
you did explain this and this path utility is really helpful
and I think I can replace the sensors with this
you are the best!
np
I am serious, let me know how I can thank you best for this!
My profile has a link to my patrons page if you're interested. Optional of course
btdt
so based on this success, I got outlets and switches to work, now working on blinds. I am using template cover and reading in the current position of the cover in percent, i.e. 100. template cover seems to expect another input though, am I using the wrong type or do I need to convert it somehow?
Received invalid cover is_on state: 100.0 for entity cover.garage_door. Expected: open, opening, closed, closing, true, false
this is the value template I currently use to get that:
value_template: "{{ state_attr('sensor.blinds_endpoint', 'item8').sumstate.value.split(';')[1] }}"
ok, I switched it to position_template, that seems to work, the slider is appearing
what I don't get from the documentation though, what do I need todo to make the slider actually work to set the position?
You use the set_position action section to call whatever service you want.
I have a template sensor that should trigger every time a state goes into on and that then should update the sensor with the number of seconds since the last time the state went into on. I have this half-way done, the problem is that i get the last time the state change regardless if it was on or off.
I'm just interested in the ons
Trying to create a Template for grabbing every 2 hours from the Hourly forecast in order to combine it with the weather-chart-card that I am using:
https://github.com/Yevgenium/weather-chart-card
This forecast shows 7 forecast in its graph, and the simplest way to extend this is to make it check against a every other hour forecast instead Hourly.
I am struggling getting the template made to grab every other forecast object however.
Any suggestions or help with how to grab "every other" item in the forecast array?
If it can be made simpler that this, that would be great:
{{
state_attr('weather.home_hourly','forecast')[0],
state_attr('weather.home_hourly','forecast')[2],
state_attr('weather.home_hourly','forecast')[4],
state_attr('weather.home_hourly','forecast')[6]
}}
I'm trying to filter out all entities that have an area_name of None or System. Not sure what I need to change after != to make this statement work?
for sensor in sensors if area_name(sensor) != (none and 'System') -- this doesn't work.
Something like this maybe?
{%- set ns = namespace(forecast=[]) %}
{%- for forecast in state_attr('weather.home_hourly','forecast') %}
{%- if loop.index is odd %}
{%- set ns.forecast = ns.forecast + [ forecast ] %}
{%- endif %}
{%- endfor %}
{{ ns.forecast }}
Truly magical. Exactly what I was looking for. Huge thanks.
{% for sensor in sensors if not area_name(sensor) in [ none, 'System' ] %}
Anyone here knows of there is a way to get the value of the card type: energy-grid-neutrality-gauge as a template?
I could do it with math function, but I also cannot find a way to get sensor.energy_consumption_tarif_1's difference since midnight
ok, how can I feed the slider value I select back into the API call setting the position? is there a variable I can feed into the API call?
I basically call blind1?position=xx% how do I feed the slider position into xx ?
Yes the position variable
so this includes the togo position in % automatically?
The set_posion action section where you can put service calls has the pre defined variable position that contains the current slider value.
ahh very nice
thank you. and I guess I can just put the variable into the api call or do I need todo some kind of conversion to have this in percent?
It’s 0 to 100
fantastic, thank you
Np
seeing this all coming together and making this whole automation stuff work thanks to HA is really great, Kudos to all the folks buiilding this!
blinds are working now!
👍
only thing missing is the icon template. this seems to be a syntax error, what do I need to change?
{% if {{ state_attr('sensor.blinds_endpoint', 'item9').sumstate.value.split(';')[1] |float }} < 90 % }
{{ }} and {% %} should only be at the beginning or end of a jinja line
they should not be nested
post your entire config
ah I copied that over from the position template
ok one mom
position template is working, I can use the slider now thanks to you
so icon_template is the only thing left
Can I just use the position variable for the icon template as well?
guess that would make it easier
ok, all you need to do is remove the {{ }} inside the {% %} in your first line
so it looks like this? {% if state_attr('sensor.blinds_endpoint', 'item9').sumstate.value.split(';')[1] |float < 90 % }
Invalid config for [cover.template]: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['covers']['bb_gross']['icon_template']
ah I guess I might need to remove the last space between % and }
YEPP, that did the trick
thank you again
is there an easy way to add the slider directly to the lovelace view? it only adds up/down/stop for now
I only see the slider when I click on the element, not on the default cardf
but this is all working, really incredible
covers don't have sliders
if you want to make a slider, you have to make an template number or use automations to have a input_number move your cover with an automation
but I have the position slider once I click on the element?
what's the difference
@scarlet sapphire Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
o_O
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
use those
the more info page has more controls, the only way to expose them as a separate entity is to do what I said previously
ok, I don't want to expose them as seperate entity, just add it to the default view, is that possible?
(together with the other controls)
template:
- number:
- unique_id: bbgross_number
name: Rollo BB grob
state: "{{ state_attr('sensor.blinds_endpoint', 'item9').sumstate.value.split(';')[1] |float }}"
set_value:
- service: rest_command.blinds_item9_position
data_template:
position: "{{ value }}"
- service: homeassistant.update_entity
entity_id: sensor.blinds_endpoint
min: 0
max: 100
step: 1
exactly the same concept as your template cover
I will check it out, thank you. with a seperate entity, I have no way to sort it together with the cover entity on lovelace views though, do I?
you can put it in the same area
ok, thanks. will tune the frontend aspect later, having blinds working now at the same time is opening up so many opportunities, automatic control based on sun etc, I will focus on that for now. thanks again for your detailed explanations!
it says "incorrect type, expected strings" for min/max there
putting it in "" for now to see if that works
is there a way i can get a sensor that gives me the number of seconds between each "on" for a state?
yes, pretty much exactly the same
but i don't see a solution there?
a template sensor will do that
i'm not interested in the number of times it has run the last hour
i'm interested in the number of seconds between each "on"
well, how? 🙂
i have the following template:
it works, with this, thanks again petro!
- trigger:
platform: state
entity_id: switch.pumpe_teknisk_rom
sensor:
- name: pump_interval
state: "{{ (now()|as_timestamp - trigger.from_state.last_changed|as_timestamp)|round(1) }}"
the problem is that this gives me every state change.. i'm only interested in the state change where the state is "on"
template:
- trigger:
- platform: state
entity_id: xyz.abc
from: 'off'
to: 'on'
sensor:
- name: foo
state: >
{% if this is defined and this is not none %}
{{ (this.last_updated - trigger.to_state.last_updated).seconds / 3600 }}
{% else %}
None
{% endif %}
device_class: duration
unit_of_measuremeht: h
you might need to make 2 triggers templates sensors.
one that detects off to on, and another that detects on to off.
that woudl be...
but i'm not interested in the time between last off and last on
i'm interested in the time between last on and current on
right but the last time it was on is when it was switched to off
well, not exactly.. i want the time when it was turned to on
because it will be running for a while as well
Only create the to_on temlate sensor then, and trigger the other sensor on a state change of that sensor
compare the from_state with the to_state
red
Nice drawing!
hehe, yes
red
blue
device_class: duration is not valid, is it?
it is valid, but you need to be on 2022.5
if you arn't, remove it and it'll still work
i'll skip it
how can i do this pre-2022.5 then?
you can't do it safely
you could post the value to MQTT topic which you make into a sensor.
and before you post the value, you'd perform the math
Why do you want this anyways?
i want to see if the interval between each pump run is increasing or decreasing
it's nice to see if we're being flooded or if stuff is cooling down
this is the spring flood water into our basement
I hope it's nice to see that you are NOT beeing flooded ;-p
hehe, it is
@ebon yoke Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
which imagehosting service do you guys use?
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
but that is for code, not for images
none of these support images
I posted that because @ebon yoke was using pasteboard
yepp and that does support images 🙂
which supports images?
hehe
there is also a bot message for that 😅
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
ty
but don't share images of code please
Images of code = bad
agreed
think of it this way, if I’m going to fix the code, am I going to want to rewrite the whole thing or copy and paste and alter?
I think he was trying to share a non-code image
Aaah, you could just do some OCR, and fix all the mistakes it made before reposting a corrected version right! 😇
petro-as-a-service ?
ERROR: ServiceNotFound
it wasn't an image of code, no
i just wanted to show the intervals
but again.. how do i solve my issue?
i'm not able to get out what i need
this should be possible to solve pre 2022.5, no?
Why not upgrade to 2022.5?
i don't dare to upgrade anything right now
h-a runs the pumps
and if they stop, then our basement is flooded
so if something breaks with z-wave or certain integrations, then i'm stuck at running pumps manually
= not an option
is it possible to solve for red pre 2022.5?
You have to get inventive
MQTT, something
you need to store the last off->on in a temporary spot using an automation
can't i just store that in a sensor?
no
why not?
because you can't circular reference
that's why this was created
why aren't you updating?
Maybe this would work?
https://www.codepile.net/pile/wgRn8eg0
That would probably work
because that's the last state
ok, i'll attempt
why aren't you updating anyways?
see above
His basement will flood if the update fails 😛
ah
i don't dare.. ha is currently running the pumps.. i can't risk integrations being deprecated or something like that failing
will device_class: timestamp work pre 2022-5?
check if the config check complains
yes
that's old
2021.8 ish was the last change to that device_class
it existed prior to that
is this under template: ?
is that yaml code valid? i'm just a bit curious about the usage of '-'
You have to use template: because it's the new style only
This is under template yes
and missing indentation?
with triggers
Which indentation would be missing
the outer-most
well, officially it could use two spaces more for list items
But this will work
If you use VSCode with the Prettier extension it will auto-add them on saving 😉
I could add it, but it looks like you are copying it right now
Added it anyway now
It will not work before the switch has been turned to on twice