#templates-archived
1 messages · Page 38 of 1
And the value for for: 😉
I return a datetime object with a macro, in template editor is as string recognised, wanted to filter it | as_datetime it returns None
Edit: I'm in BETA
you have leading spaces
you have to ensure your macro doesn't output leading spaces or trailing spaces
yeah you right! i already had that problem and forgot abou it, thnx
Does anyone happen to be importing values through MQTT and telegraf for proxmox stats?
telegraf does the stupid thing of posting all values for a given stat under the same topic (e.g. load1 load5 load15)
I've ended up with something like
value_template: >-
{% if value_json.fields.load1 == null %}{{ states('sensor.proxmox_load_1m')
}}{% else %}{{ value_json.fields.load1 }}{% endif %}
but HA no longer likes it
is there a better way to not have unavailable states seeping through?
I guess an availability template would help?
I would love to have some help on the following.
` ##Product naam zoeken
- platform: rest
name: Productnaam
resource: https://nl.openfoodfacts.org/api/v0/product/{{ states.sensor.barcode_reader.state | default('1') }}.json
value_template: "{{value_json.product.product_name}}"`
The states.sensor.barcode_reader.state seems not to be filed. The response is based on the default value 1.
You need to use resource_template if you want to use templates in the resource
AWSOME! thanks a lot!
power_cur will be power, measured in Watt. Not energy (measured in kWh)
And I guess you need '{{ value_json.Power_cur }}'
@flint yarrow I converted your message into a file since it's above 15 lines :+1:
doh, that makes it harder to read 😅
@flint yarrow I converted your message into a file since it's above 15 lines :+1:
@pseudo glade To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
re: the template. I'm only looking to pull out a small subset of data fields. For each result, it'd be the address.* (to be concatenated later into an attribute... somehow), brands.image_url (assuming I can change the icon to a remote image), name, and prices[0]['credit']
So I've gotten a little bit further. My REST config is as such:
https://gist.github.com/Morgon/1d196003db9fd207d1cb243219a2672a
I see that I can't directly reference nested attributes, so only "Name" is working, but I'm uncertain how to go about adding the rest as attributes. I think I would prefer not to make unique sensors for every field if possible (and if it's not, please do let me know).
Strangely, the results of value_template are "Unknown" instead of the expected price value. I've been using jq to validate the structure, so I don't think it's a pathing issue. I also tried square brackets instead of dot notation. Would appreciate any thoughts!
if the value template is unknown that means theres an error in your template
In the demo template, it says The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago. but that looks at the sunrise in UTC, not in local time. It's saying that the sun rose 2 hours ago, but it rose 8 hours ago. How can I fix that? Edit: never mind, that's simply when I restarted HA
take the value template, copy it into the dev template tool with {%set value_json = [json]%} so you can play around with getting the value template right
if it works in there and you have the same content as the rest sensor, you should jsut be able to move it over to the value_template
is there anyone that can help me? i am scraping data from a website but i want the value to change from comma to dot and divide by 100. i can't get it to work. anyone?
what i have now: value_template: '{{ (value | replace(",",".")) }}'
if its a string, replace should work, but then you need to convert it to a number
nvm, just got it lol
had to float it first and then divide
value_template: '{{ ((value | replace(",",".") | float) / 100) }}'
probably when you restarted your ha, last_changed i think resets on restart
Yup
oh i didnt see the edit lmao
I did. The path is correct, AFAICT, assuming that value_json is based on json_attributes_path. Or do I need to start from root?
value json isnt affected by the json_attributes_path
its an attributes path
and the value template is for state
Ok, I still can't figure out how to juggle as_timestamp, timestamp_local and timestamp_custom to get the sunrise or sunset time in HH:MM. I'm lost.
The sun will set at {{ as_timestamp(state_attr("sun.sun", "next_setting")) | timestamp_local }} gets me the local time with microseconds - I doubt my planet is that round that it's true, but hey.
But then I can't pass that to timestamp_custom
Got it. Will update to full path. (Although it still seems to be Unknown 😦 )
I don't suppose you know how I might be able to utilize these nested attributes? Must I create a unique sensor for them..?
To reiterate, my current YAML is https://gist.github.com/Morgon/1d196003db9fd207d1cb243219a2672a
And the JSON response is https://gist.github.com/Morgon/628fba2b0aee7f8205186bf4084d6c54
If I run as_timestamp on the timestamp_local, it gets turned into UTC again
Hi! Short question, can someone tell me why doesn't work this code in a template chip with mushroom?
{{ states.group.all_lights | selectattr('state','eq','on') | list | count }}
Thanks
are you jsut trying to format the date
i dont believe you can use templates on attributes for rest sensors
Thank you again @orchid oxide
Sorry to belabor the question, but are there any other ways to accomplish it? e.g. setting unique sensors for each value? Originally, I was hoping I could re-use the templates and have each entity from the JSON list be applied to it, but I haven't seen any examples of such code re-use
i mean it looks like you could, achieve this with 3 rest sensors as you have 3 different json paths. then theres always the option to just take the input and run it through a template sensor
Yeah, I don't want to make multiple calls (the endpoint has rate limiting and couldn't handle it anyway), so the second option seemed like what I should do, but again I haven't seen any good examples of this that I could directly apply to my data.
My end goal is to have an entity card like this that'll show the top 5 name, address, and prices https://i.imgur.com/GhTtDPw.png
personaly i would make the rest sensor target the results list and have that be a single attribute, then just deconstruct it into the attributes you actually want using your template sensor
I know some of those words... 😅 What do you mean by "target" the results list? Are you referring to the json_attributes_path?
I was about to go down this road but I don't think this is what you mean
- resource:
...
sensor:
- name: Gas Station 1 Address
unique_id: gasstation_0_address
value_template: "{{ value_json.data.locationBySearchTerm.stations.results[0].address.line1 }} {{ value_json.data.locationBySearchTerm.stations.results[0].address.locality }}, {{ value_json.data.locationBySearchTerm.stations.results[0].address.region }}"
(which is why I was hoping that json_attribute_path was the base for the value template.)
i mean that works too lol
it would be better to do it as an attribute rather than a state, since attributes can be lists and states cant
Right, but I cannot get nested attributes..? Would the "template sensor" be part of the rest resource, or I would need to create an actual sensor within the templates yaml?
Interesting. I did get the address to be an entity, but price still isn't working. (Doh, typo)
i would do this
json_attributes_path: '$.data.locationBySearchTerm.stations.results[0]'
json_attributes:
- "name"
- "address"
- "brands"
...```
and then in your template sensor
...
attributes
line1: "{{state_attr('rest_sensor', 'address').line1}}"```
etc
i think i did that right
cause the attribute address should return the json as the value
iirc
Hm, brands[0] would work? I was under the impression that only bare attributes would, but I will try it for sure.
Can I make a "template sensor" as part of the rest, or it has to be a top level sensor?
I'm having trouble with a statistics sensor - the yaml validates but it just doesnt show up:
this is in the file config/sensor/max_elevation.yaml
my configuration.yaml has sensor: !include_dir_list config/sensor/
name: max_sun_elevation_yesterday
entity_id: sensor.sun_elevation
state_characteristic: value_max
max_age:
hours: 24
oh yknow what, i forgot about this, i think this solves your problem https://www.home-assistant.io/integrations/rest
That's what I'm already using, I just couldn't figure out how to format my data from within the larger json
oh, you can make 3 sensors with this with 1 api call
Okay, so I do have to make unique sensors? Name, address, price? Or you're referring to each of the overarching station data (I was going to do 5)
yeah you can specify a different json_attributes_path for each sensor
since theres 3 paths for you that would be 3 sensors
since the 3 from address are all under the same path, they can all be attributes on one sensor
Gotcha. So a total of 15 unique sensors if I want to show the top 5. Not ideal (was hoping for self-contained attributes for each top entity), but something is better than nothing. Thanks for your help, I will play around with that idea more.
theres that or theres breaking it down in a template sensor so instead of 15 rest sensors you could do 1 (or 5 depending on how you want to do it) template sensors
Can you help me wrap my head around the template sensor? I had asked before if I could make a template sensor from within the rest module or if I would need to make a top level one. I like the idea of it, especially if I can define things a single time and reference the template
like this
you need to make a seperate template sensor, not part of the rest sensor
since you cant use templates on rest attributes
Ah, I see what you meant by that now
Unrelated, is there a way to get an icon to be a remote image instead of mdi (or local img)? Web searches are a PITA.
could anyone help debug my template sensor
its an dual android alarm clock time sensor ...
when my wife sets her alarm her time etc is noticed in the sensor but not her name ??
text_whos_alarm: null
?
or am i overcomplicating things for a wake-up-routine ... both android alarms
@orchid oxide thank you again for your help earlier. My huge getting-out-of-bed tts routine now works perfectly.
if that's null, you've encountered an error in your template during execution. Look in your logs.
also, I think you're over complicating your alarms
and I'm the king of over complicating things
you can use time triggers to trigger at timestamp sensor times.
personally, i'd make a template sensor that simply has the next name and the next time to send the notification paired with an automation
Yeah i noticed them alarm sensor now have a local time nicer format
text_whos_alarm: >
{% set alarms = { 'Martijn': states('sensor.pixel_7_next_alarm'), 'Mirella': states('sensor.mirella_next_alarm') } %}
{% if alarms.Martijn == alarms.Mirella %}
Geen alarm
{% else %}
{{ alarms.items() | min(attribute='1') | first | default('Fout') }}
{% endif %}
if you just want to fix your template @north locust ^
FYI you can use the same code just about everywhere
instead of doing math in multiple places
figure out what the lowest is, then do the math
no reason to do the math, then figure out what's the lowest
Time is finnicky
if you have trouble, I made a whole library that calcs things for you
although it wont help you here
it will help you get relative time though
easter()
Easter’s date.{{ easter() }}
this one feels so random lmao
Hi! Can someone tell me how can rewrite that code so that it counts me how many lights are on in that group of lights.
{{ states(group.all_lights) | selectattr('state','eq','on') | list | count }}
{{ expand('group.all_lights') | selectattr('state','eq','on') | list | count }}
Thanks @obtuse zephyr !!
No prob
Are any docs about this in the official website of Hassio? I tried to search the problem but no results...
Sure, this doc is your friend: https://www.home-assistant.io/docs/configuration/templating/
Thanks
wait is expand the same thing as states.entity_id.state?
expand enumerates all of the entities contained within a group
So here, you called it rest_sensor, is that just a placeholder for the explicit sensor.gas_station_1 (etc) that I've created, or can this be re-used in a way that I can pass it generically and reuse it?
Yes to the first one and not sure I understand the 2nd one
Well I was hoping to make single generic sensors/templates/something (whatever needs to be done) so that I can feed it any number of entities that I've set up this way (in my case, 5 - sensor.gas_station_x, 1-5) without explicitly creating 15 different sensors. It sounded like you alluded that it could be done, but wasn't clear on how to approach it.
you can make one template sensor with all 15 attributes
or you could probably make a macro if you wanted (dont think macros can be used in the front end)
Oh. So to be clear, there's no way to abstract it out?
I'm trying to avoid making 15 explicit attributes/templates, and simply define it once, e.g.
{{my_input.address.line1}} {{my_input.address.locality}}, {{my_input.address.region}}
Where my_input is assumed, in the template, to be whatever I pass into it. Whether it be 1 "Gas Station" entities, 5, 10, or 50. It's defined a single time and re-used.
macros can accomplish that
A lot of date libraries include it, because calculating when Easter falls is a huge pain, but basically every other holiday is either set based on Easter or actually related to the normal calendar, lol.
but seeing as how youre doing this 15 times once, macro seems like more effort to me personaly. to each their own i suppose
youd still have to make 3 macros for your 15 template attribtues
Well next month I could decide I want to show 10 stations, or 3. I don't want to have to go into three different files to update them, you know?
gotcha gotcha. i dont celebrate easter so i wasnt aware lmao
WOO. Okay, that is actually working on the UI
type: entities
entities:
- entity: sensor.gas_station_1
type: custom:secondaryinfo-entity-row
secondary_info: >
{% from 'gas_station.jinja' import gas_get_address %}
{{ gas_get_address('sensor.gas_station_1') }}
wow ok i actually didnt even think about skipping the temp0late sensor lmao
Still trying to figure out if I can dynamically update the name, though..
thats only gonna work in some cards though, not all of them accept templates
https://i.imgur.com/W7BiKiI.png Instead of "Gas Station 1", I'd like it to show the name. I couldn't find a way to dynamically update the sensor's name itself (though that'd be ideal), so just printing it on the UI would be fine
i mean if entity row lets you use a template as a name its just state_attr('sensor', 'name') if im remembering it right
No, it doesn't seem to.
type: entities
entities:
- entity: sensor.gas_station_1
type: custom:secondaryinfo-entity-row
name: {{ state_attr('sensor.gas_station_1', 'name') }}
Configuration errors detected:
missed comma between flow collection entries (5:55)
need quotes around the {{}}
Tried that, too - that just prints the literal jinja string
well then you can either make a new entity for the name and use that (if the card supports it) or you can use template config card
So outside of the UI, there's no way to dynamically reference the name based on an attribute? I feel like there's gotta be some way of doing it, because it seems like a somewhat common use case.
get the entity name by searching for what, the attribute value?
I guess, or some other way of automating it (which I suppose is another angle, automations)
well i thought the card didnt let you use a template for the name
Right, but if the actual name of the entity could be dynamic, then it wouldn't matter what the template supported because it the idea would be HA returning the custom value as the name.
yeah i think the only entity that could support a dynamic name would be mqtt entities
so you could make mqtt entities and publish with a new friendly name, and all the work that goes into that or you can wrap your card in config template card
or you can use a different card that supports templates in the name
Hm. Apparently there's a friendly_name attribute
afaik you cant update the friendly name outside of mqtt entities
best pick one of the options above
or template sensors https://www.home-assistant.io/integrations/template/#name
Oh wait, restful sensor name is templateable https://www.home-assistant.io/integrations/sensor.rest#name
Although I'm not sure how to refer to itself. 🤔 Or whether that'll make it hard to refer to it in the UI - I was hoping unique_name would take over for addressing a sensor
the entity_id wont change just cause you change the name
Right, but the entity_id was initially populated by the name rather than the unique_id, I called it "Gas Station 1" and the device became sensor.gas_station_1
Even if existing sensors don't rename their ID, I'm concerned about new ones
i mean you cant create a sensor out of thin air (except for mqtt lol), unsure if sensors try to use unique_id for the entity name if given, but if not you can just change it in the ui
Okay, template-entity-row to the rescue. Ended up being much much harder than I imagined, but finally have (mostly) what I want.
https://i.imgur.com/e58e0AK.png
(Sweet, it also has an image, so I can show that, too)
Greatly appreciate you hanging with me to work through this, @orchid oxide
yw
(lol, all that and there's a gasbuddy bug - even if you choose to get prices for "Credit Only", it'll sort by the cash price, thus making the list out of order as shown in the last image)
sort it yourself, in...a template sensor lmao
or config template card again
actually if your card takes templates for the name and entity i guess you could sort it there too
Well, if you look at the macro, it’s a ridiculous equation. You can get any other holiday easily with one of the other macros. For Easter you can’t, so I just built the macro
That's actually crazy, I didn't realize how insanely complex the date for Easter was lmao
Useful little template to set the coulor of an icon based on a temperature if anyone want's it!
{% set colourhex = ['#0000FF','#0000F9','#0000F3','#0000ED','#0000E7','#0000E1','#0000DB','#0000D5','#0000CF','#0000C9','#0000C3','#0000BD','#0000B7','#0000B1','#0000AB','#00FFFFFFFFCCA5','#00FFFFFFFFF69F','#002099','#004A93','#00748D','#009E87','#00C800','#C89600','#CA6400','#CD3200','#CF0000','#D20000','#D40000','#D70000','#D90000','#DC0000','#DE0000','#E10000','#E30000','#E60000','#E80000','#EB0000','#ED0000','#F00000','#F20000','#F50000'] %} {{colourhex[states('sensor.average_house_temperature')|round(0)]}}
Goes from Blue for temperatures around 15, Green at 21 and then onto the reds
Is there any way to include a macro for the entirety of a script? Was looking to use one for setting up some variables, but right now it's looking like it needs to be included on each variable definition.
- name: "Shirts - h:m:s"
unique_id: shirts_hms
state: >
{{ (states('sensor.shirts') |float(0)) | round(0) | int | timestamp_custom('%H:%M:%S' , false) }}
icon: mdi:tshirt-crew
- name: "Shirts - when"
unique_id: shirts_when
state: >
{{ (states('sensor.shirts') | float(0) + now().timestamp() | int) | timestamp_custom('%d | %H:%M:%S' , true) }}
icon: mdi:tshirt-crew
In development tools, second sensor: "30 | 16:23:29"
Gives the right value.
In configuration.yaml, and a entities card: the second sensor stays at: "30 | 01:37:29"
sensor.shirts=2,249 sec
Is that 2249?
Yes.
Can't really pinpoint the moment the values start doing that. It was working fine before...
The template of the second sensor is incorrect, you are adding a floating point number and a string together
Oh no, I missed the brackets
What is your goal there, adding two timestamps together doesn't really make sense to me
One says how long in: hours:minutes:seconds it will take. The other says "when" in: day | hours:minutes:seconds
{{ (now() + timedelta(seconds=states('sensor.shirts') | float(0))).strftime('%d | %H:%M:%S') }} should do the same
Yep, but weirdly enough it does the some discrepancy. In development tools: "state: 30 | 16:39:31", if I add to confiigution.yaml, restart templates, in the entities card it stays: "30 | 01:37:29"
What does developer tools > states say
30 | 16:41:29
Ohhh, I think I pinpoint the problem. But that's strange...
I added a trigger: 1h, time_pattern, to a template that was part of the equation; that would give the seconds.
- trigger:
- platform: time_pattern
hours: 1
If I take that off, the values give the correct state in the cards....
Unfortunately it keeps changing all the time, instead of the value change from 1h-1h.
Where is the difference between template sensor and number?
When the temple number value changes the calculation is performed? Correct?
They both reevaluate their state when an entity in the template changes value. You can't directly set the value of a template sensor, while you can define a sequence to update a template number
If your sensor.shirt updates every hour, your other template sensor will update everyone hour and every minute
To prevent it from updating every minute (which it does because you used now() in the template), you can change it to a trigger based template sensor which triggers on a state change of sensor.shirt
semi template-relate, template sensor related. ive got a template sensor with device_class: running, the last_run attribute seems to change to when my sensor last went from any other state, to off. this means when I restart and the state is unknown for about 20 seconds, then switches to off. It changes the last_run. Is it possible to alter this behavior so that it only changes last_run when it goes from on to off?
all entities have this behavior. Even if you were able to filter this out (you can with a supplemental template sensor), it'll still update the last changed & last updated on restart.
ah ok
2 way esphome sync
if I want to reference a trigger id in a template, its trigger.id yes?
ie, the following is correct?
- trigger:
- platform: event
event_type: zha_event
event_data:
device_id: 405aa8670b602b8480633896e93eac3a
command: vibration_strength
id: dirty
- platform: state
entity_id: binary_sensor.dishwasher
from: 'on'
to: 'off'
id: clean
- sensor:
- name: Dishwasher Cleanliness
state: "{{'Clean' if trigger.id == 'clean' else 'Dirty' if trigger.id == dirty}}"
Hi, I was wondering what's the best way to set an alternative name for an entity. I have a Zigbee device that I want to keep its name, e.g. "Motion sensor bathroom". But in the scripts I'd like it to be "Bathroom" only for a concise status message. Is the only way to achieve this to create a map by its id/real name with the value being a short name? or is there a way to set some alias in the UI perhaps?
Hello. i have a problem with this template:
@digital harness I converted your message into a file since it's above 15 lines :+1:
its shown as not available in home assistant
test template works.
can anybody help?
Same issue: #templates-archived message
Looks correct, but you can also just use
{{ trigger.id | title }} or just add the first capital character to your trigger id
Your availability template should be a template
Probably something like "{{ states('sensor.shellyuni_e868e7f472ec_adc') | is_number }}"
You should also use states('sensor.foo') instead of states.sensor.foo.state
this is very true and also simpler lol, didnt think of that
Hello masters, another one I need help with.
I'm creating a fake "heater" that replicates what my remote dummy controller is doing (lol).
What I intent?
A custom sensor that'll show a temperature. How? Well, considering the list below, with booleans and sensors, I want the new sensor to represent said temperature. Let's call it sensor.heater to work as an example.
Practical example:
if - input_boolean.heater_friday_1 is ON
it would read the value of sensor.heater_friday_1 and show it on the new sensor. If input_boolean.heater_friday_1 goes off but input_boolean.heater_friday_2 goes ON instead, it'll then update to what's on the sensor.heater_friday_2 instead.
How do I do this? I figured I could create an automation with "on" triggers (and I already have one created that all the other booleans go off, if one's on).
I just realistically want to know how I make one sensor show what's on other, BASED on a ON state of another boolean.
Not sure if this should be on #automations-archived instead, if so, lmk and I apologise in advance.
I figured I could make a custom-template-card with all this on the UI, but I'd think it would be so much nicer if I managed to just create a custom sensor with all of this.
there is an integration that does this
save your time lol
I saw and used it. It somehow manages to work way differently than my controller and the way I intend will work the exact same way.
Plus learning how to make sensors replicate each other would be a nice thing to learn. Appreciate the suggestion tho
no, you need quotes around dirty. But you can simplify this to {{ trigger.id | title }}
You can remove the word "Motion sesnor" using templates w/ yourstring.replace("replace this", "for this")
I see thefez beat me to it
it's honestly so obvious i deserve to be told twice lmao
You could aslo just add capitals to your trigger id to avoid even needing title
that's just a template sensor with if statements
{% if is_state('input_boolean.heater_friday_1', 'on') %}
{{ states('sensor.header_friday_1') }}
{% elif ... 2
{{ ... 2
{% endif %}
if you want something that just works assuming that your sensors and heaters are all named the same...
Something like this?
- sensor:
- name: "BOILER: Temperature"
unique_id: boiler
unit_of_measurement: 'ºC'
state: >
{% if is_state('input_boolean.heater_friday_1', 'on') %}
{{ states('sensor.header_friday_1') }}
{% elif is_state('input_boolean.heater_friday_2', 'on') %}
{{ states('sensor.header_friday_2') }}
{% endif %}
{% set day = now().strftime("%A") | lower %}
{% for i in range(5) if is_state('input_boolean.heater_' ~ day ~ '_' ~ (i + 1), 'on') %}
{{ states('sensor.heater_' ~ day ~ '_' ~ (i + 1)) }}
{% break %}
{% endfor %}
that would work for all days w/ all input booleans
Yeah, they're all named from sunday to saturday, 1 to 4, same format
@mighty ledgeShouldn't be too far from what we wanted to to do. It kinda works but it's giving me a 0ºC value. Ignoring with booleans on.
This is what I came up with:
- name: "BOILER: Temperature"
unique_id: boiler
unit_of_measurement: "°C"
state: >
{% set day = now().strftime("%A") | lower %}
{% for i in range(5) if is_state('input_boolean.heater_' ~ day ~ '_' ~ (i + 1), 'on') %}
{{ states('sensor.heater_' ~ day ~ '_' ~ (i + 1)) }}
{% break %}
{% endfor %}```
https://imgur.com/gURBpCd screenshot of the sensors
if it's giving you a number, its working
Okay, news for you, I just tested on the programmer tools thing
Both give me a value. So both work. BUT they don't work together?
As in:
{% for i in range(5) %}
{{ states('sensor.heater_' ~ day ~ '_' ~ (i + 1)) }}
{% break %}
{% endfor %}``` gives me a 20 value (ºC) and gives the proper sensor name we intended.
But I had to remove the {% for i in range(5) if is_state('input_boolean.heater_' ~ day ~ '_' ~ (i + 1), 'on') %}
The complete template you gave me, doesn't give neither the sensor OR the boolean, gives me this:
Result type: string
This template updates at the start of each minute.
This template listens for the following state changed events:
Entity: input_boolean.heater_monday_1
Entity: input_boolean.heater_monday_2
Entity: input_boolean.heater_monday_3
Entity: input_boolean.heater_monday_4
Entity: input_boolean.heater_monday_5
but gives no ºC value. Something is breaking. And probably that's why it's giving 0ºC on the final sensor. We're almost there 😄
I tried with multiple and all gave 0 as value too, let me retry but I'm p sure there's always at least one on.
input_boolean.heater_tuesday_3 is ON
so it'll output the number for sensor 3
if you get a number out, it's working 😉
I was testing with a TUESDAY boolean on, on a MONDAY hahahahaha
if you get no number out, it's also working but you don't ahve any booleans on
It works. As soon as I turned on a "monday" boolean it worked and updated the sensor we created.
Petro, I can't thank you enough. This will be so useful even for other stuff. Thank you. I understand the process behind it 😄
Have a good day!
Thanks, good and very simple solution!
I'm trying to set up custom:vacuum-card and add some stats, but my value templates aren't working. I made this using the template section in Developer Tools, but it doesn't seem like it works in the card
{{ (float(states('sensor.roborock_s6_filter_left')) / int(3600)) | round(0) }}
That shows the correct value of 130, but the vacuum card still shows 467756, which is the value before dividing
And this is the yml for the vacuum card
type: 'custom:vacuum-card'
entity: vacuum.roborock_s6
actions:
start:
service: vacuum.start
service_data:
enetity_id: vacuum.roborock_s6
stats:
default:
- entity_id: sensor.roborock_s6_filter_left
value_template: {{ (float(states('sensor.roborock_s6_filter_left')) / float(3600)) | round(0) }}
i had this same issue with the vacuum card, make a template sensor and do the math inthe sensor, so youre just putting a raw value, no math, into the card
Yeah seems like that's gonna be the way to go
This card is so nice but there's so many unresolved issues looking through the Github page
Hi, I was triggered by a question on the forum... is it possible to combine sensors to one line? Example
sensorA, value 1 and attr C and sensor B, value 2 and attr. C
can I combine this to one line grouped by attr. C, i.e. : attr.C , value 1, value 2
I hope I am not to confusing 🙄
im getting getting the following error for the following template:
2023-05-02 02:33:39.300 ERROR (MainThread) [homeassistant.helpers.template_entity] TemplateError('UndefinedError: 'trigger' is undefined') while processing template 'Template<template=({{'Dirty' if trigger.id == 'dirty' and states('sensor.dishwasher_door') == 'on' else 'Clean' if trigger.id == 'clean'}}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.dishwasher_cleanliness'
is trigger id not supported in template sensors? cause changing this to an automation and swapping out the state for a persistent notification it works fine
Well, I don't really understand what you mean here.. So you might be 😉
have this auto-entities template filter working just fine: {% set ns = namespace(sensors=[]) %} {% for s in states.sensor |selectattr('entity_id','search','poe_port') if s.state|float(0) != 0%} {% set ns.sensors = ns.sensors + [ { "entity": s.entity_id, "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim), } ] %} {% endfor %} {{ns.sensors}}
but when I use it in dev template, it errors with UndefinedError: list object has no element 1
what am I missing here?
especially odd, since this {% set ns = namespace(switches=[]) %} {% for s in states.switch |selectattr('entity_id','search','poe_port') %} {% set ns.switches = ns.switches + [ { "entity": s.entity_id, "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim), "secondary_info": 'last-changed' } ] %} {% endfor %} {{ns.switches}} works fine in both dev template and auto-entities
is it possible to do math in a template sensor and round it on the same?
Yes, sure
just wrap the entire calculation in paranthesis and add a round() filter
hmm, rejecting a specific string of another sensor make it work: {% set ns = namespace(sensors=[]) %} {% for s in states.sensor |rejectattr('entity_id','search','poe_ports') |selectattr('entity_id','search','poe_port') if s.state|float(0) != 0%} {% set ns.sensors = ns.sensors + [ { "entity": s.entity_id, "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim), } ] %} {% endfor %} {{ns.sensors}}
It looks like you have a sensor which has PoE at the end of the friendly name, or without PoE at all
really odd..
should be one of the sensors with poe_ports in the entity_id then
yes thats is correct
its because this "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim) doesn work in that case`
okay, well that sensor will have only one item after splitting the friendly name
so indeed it will fail on that line
you have a list with one item, and you want to take the 2nd item out of that list
there is no 2nd item
not sure why auto-entities doesn't error on it though, but I wouldn't consider it smarter 😉
its the same with the selects on attributes. In auto-enties those simply work (as they used to in Ha some time ago), in HA we need to select 'defined' first
It's probably null coalescing and/or just handling that in the background for you
I need to select these entity_id's sensor.switch_48_poe_port_1_poe_power where only that port number changes of course. Ther is 1 compound sensor it needs to exclude sensor.poe_ports_power
I love that 'handling in the background'...
Bear in mind, it's just that someone else wrote the code which checks if it's defined first. It's still doing that
well yes, personally I really like that a system has these kind of checks, and doesn't impose that on the user. Wev'e seen a huge amount of that the last couple of years, just think of all the defaults..
round brakets? Or what are excatly paranthesis? (my bad english)
btw I now see that if I use |selectattr('entity_id','search','poe_power') the template is fine... guess at the time I didnt have the compound sensor yet.
I guess you answered the wrong guy 🙂
o my pardon, yes, I hadn't noticed I 'answered'.
no problem
but what the Fes was saying was {{ (your_calculation_in_parenthesis) |round(2) }}
have another challenge, a matter of ordering. please see the switch template #templates-archived message
if I use it as is, it orders on human listing perfectly, except for the last
if I add sort: name, things go understandably wrong, so that is not useful
the order with the Port 17 as last is also in the dev tools.
so I seem to be needing a sort in the template on that number. But I dont understand why it does this in the first place
states[domain] used to sort on entity_id, but that has been removed like 2 months ago, becuase it was quite heave on resources
but that also only works with a leading 0 in the entity_id
you could sort it in your template, by adding a sort id to your dict and sort it on that
HI, as I was confusing ... a new attempt with more realistic data
sensor.station_ABC_e10
state: 0.99
attr:
- type: e10
- address: xyz
sensor.station_ABC_diesel
state: 1.8
attr.:
- type: diesel
- address: xyz
Wished output: 'columns' per station
station_ABC 0.99 1.8 xyz
ok, I will do so, however, can you explain why only 17 is misplaced?
where are you sorting on now?
nothing, just the {% set ns = namespace(switches=[]) %} {% for s in states.switch |selectattr('entity_id','search','poe_port') %} {% set ns.switches = ns.switches + [ { "entity": s.entity_id, "name": (state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim), "secondary_info": 'last-changed' } ] %} {% endfor %} {{ns.switches}}
try it in dev tools template and it does what auto-entities does, no background magic just yet 😉
I'm not sure how states.switch is sorted now. But it will use whatever order the state objects are provided
I must add that I only recently added that entity (enabled it in the integration), so maybe some background calculations on being available..
or it uses the order in the the config entries in .storage
it's probably last there, as it was most recently added
yeas, something like that would explain that behavior
which is ofc a completely silly sorting argument, might even call that an issue
the point is that it doesn't sort anymore
there is no sorting argument, it just provides the state objects as it gets them
maybe not an active sorting argument, but listing in order of recently added is de facto sorting.
for this to work properly again, I have to disable all, and re-enable all again....
or just sort them yourself
right.. and thats when we get back to some posts above
{% set ns = namespace(switches=[]) %}
{% for s in states.switch
|selectattr('entity_id','search','poe_port') %}
{% set name = state_attr(s.entity_id,'friendly_name').split('PoE')[1]|trim %}
{% set ns.switches = ns.switches + [
{
"entity": s.entity_id,
"name": name,
"secondary_info": 'last-changed',
"sort": name.split(' ')[1] | int
}
] %}
{% endfor %}
{{ns.switches | sort(attribute='sort') }}
something like this
yes, that is beautiful, thank yvm. also works in auto-entities.
given that a helper with entity id 'input_text.04_26_fb_c2_e3_72_81' exists and a tag_id correctly returns '04_26_fb_c2_e3_72_81', can i get it's state like this, if so please help with syntax ... name: "{{ states('input_text.' ~ trigger.event.data.tag_id).state }}"
i'm trying to evaluate the text for use in an automation action.
because you added .state
remove that
it's either states.sensor.foo.state (which you should avoid) or states('sensor.foo')
i just noticed another problem... the name of the text input and the tag_id returned is input_text.04-26-fb-c2-e3-72-81... but the entity has underscores! lol yikes..
can i add in some kind of search replace to change tag_id '-' to '_' so that states will function correctly?
oops.."_"
i think i'm almost there with name: "{{ states('input_text.' ~ (replace(trigger.event.data.tag_id,"-","_")) }}" ... but still syntax
you need to replace - with _
now you're just removing the -
"{{ states('input_text.' ~ (replace(trigger.event.data.tag_id,"-","_")) }}"
Oh wait, it was just because you didn't add code formatting, and discord made your text cursive
or you use "{{ states('input_text.' ~ trigger.event.data.tag_id | slugify) }}"
slugify! for the win
thanks so much!
I've been staring at dashes and seeing underscores for hours! lol thanks again
why does visual code studio say this is a unknown tag:
frontend:
themes: !include_dir_merge_named themes
What's the error
"unknow tag <! include
i don't understand it. now it displays a different error on "default_config:
unable to load schema from'http://schemas.home-assistant.io/configuration' : no content
You're using the latest version of the add-on, which has schema validation issues
You need to revert to the previous version if you want it fixed
what is schema validation issues?
yes. thats exactly what i found this minute
so it is just a displayed error and does not affect my system=?
That error itself doesn't affect you, correct. Apart from it not being able to actually validate the file
It doesn't mean it's wrong (or right...)
Yeah, this would likely prevent it from showing other actual errors
hmm now how to downgrade?
You using HA OS and the addon?
yes
Restore a partial backup
WOW thank you this is amazing. i learned now what the partial backup is
i found the other issue now: (from before)
it says:
unknown tag <!include_dir_merge_named>
as error to this: frontend:
themes: !include_dir_merge_named themes
okay seems like no more errors after restore
i thank you a lot for your help
You bet np
👍
the other problem is still not solved but has nothing to do with templates🥲
u know which channel would be right for trusted network/user problems?
I'd go to #integrations-archived ... #general-archived would work too, but there's quite a bit going on there
I posted earlier about this value. Is there any way I can have it be a minumum? For example, if sensor.coreception_progress is less than 7, then the value should be 7. If it's more than 7, the value should be sensor.coreception_progress
value: "{{ states('sensor.coreception_progress') | float }}"
How do I do that?
Ah thanks. Any chance that you would have a doc that shows that's how it's done? I googled it and couldn't really find anything that says that's how it's done. I just want to learn about these different functions I can use.
there's an example in the docs: https://www.home-assistant.io/docs/configuration/templating/#numeric-functions-and-filters
min([x, y, ...]) will obtain the smallest item in a sequence. Uses the same parameters as the built-in min filter.
and that points to the official Jinja docs: https://jinja.palletsprojects.com/en/latest/templates/#jinja-filters.min
which shows essentially what I gave you
Thanks. That's useful.
With the help of some awesome boffins from this forum, I put together a sensor to check my history sensors (+ utility meter sensors) to see who is watching the most content on my plex server. This works great. However, I would like to tweak this code to look at the state attribute "last_period" and not just the state, but not sure how to achieve this
@peak juniper I converted your message into a file since it's above 15 lines :+1:
Every time I hear 'boffin' it seems like the most unlikely word to be a positive or complimentary description 🙂
Hey, who are you calling a boffin? 😠
Or some kind of bird. I would totally believe that
I have a 433MHz sensor and it works well with RTL_433 and publishing to MQTT. It's a doorbell, so it pushes a message when someone rings, but it's stateless. So the signal is sent twice for redundancy, but there's no "on" or "off". Topic is rtl_433/doorbell/12345- the sensor ID is 12345, and then there's values inside, although they don't really matter much. What sort of sensor would work in HA where it would trigger?
Do you need an entity/sensor? You can just trigger automations straight from the MQTT event with an MQTT trigger.
I'd prefer to do something in my config such that I can then switch to the GUI to setup my automations.. if possible. But not 100% necessary.
This is what I have so far, not sure if I'm in the right ballpark or not.
mqtt:
sensor:
- name: "Reolink Camera"
state_topic: "rtl_433/Reolink-Doorbell/4151085"
value_template: '{{ "3f572d8" in data }}'
Anyone know how I can turn this into a value template? I want to change it so that the below value is 'equal to or less than' ?
condition: numeric_state
entity_id: sensor.avg_climate_temperature
below: input_number.thermostat_setpoint
above: sensor.combined_ac_temp_setting
{{ states('input_number.thermostat_setpoint')|float <= states('sensor.avg_climate_temperature')|float < states('sensor.xxxx')|float }}
Got tired of typing long names on my phone
It would be a template condition
Could anyone help to change this, so that I could use it in a time trigger function:
´´´
{% set energyPriceSensor = "sensor.energi_data_service" %}
{% set priceData = namespace(numbers=[]) %}
{% for i in state_attr(energyPriceSensor,'raw_today') %}
{% set priceData.numbers = priceData.numbers + [i.price] %}
{% endfor %}
{% set three_consecutive_hours = namespace(numbers=[]) %}
{% set this_hour = now().hour %}
{% for n in range(this_hour,22) %}
{% set three_hour_sum = (priceData.numbers[n]+priceData.numbers[n+1]+priceData.numbers[n+2])|round(2) %}
{% set three_consecutive_hours.numbers = three_consecutive_hours.numbers + [three_hour_sum] %}
{% endfor %}
{% set min_three_hour = min(three_consecutive_hours.numbers) %}
{% set least_expensive_hours = this_hour + three_consecutive_hours.numbers.index(min_three_hour) %}
{{ least_expensive_hours | int }}
For other:
Changed that last line to
{{ least_expensive_hours | int ~ ':00' }}
Trying to start an automation based on a template sensor time value,
The sensor value is hh:mm and is called: sensor.bedste_3_timer_i_dag
so the sensor is 11:00 i would like for a automation to start at 11:00
Actually, now that I think about it, it might be better to just look for the hour value, so the sensor is 11 and the hour corresponse to 11...so a condition based on time...Ive got the trigger but need to check for the hour value
I'm trying to match a future datetime in a list using selectattr('datetime'.... But running into trouble.
I can't work out why, but this code is showing me (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() this output 2023-05-04T05:00:00+00:00
However, I'd exepect it to show tomorrow at 06:00 not 05:00. What am I doing wrong?
This is the example datetime=2023-05-04T06:00:00+00:00 I'm trying to match to in the list of items.
You start with local time 6:00 and you then convert that to UTC, which seems to be 5:00
So I assume your timezone is GMT with 1 hour because of DST
But are you sure it's not a datetime?
So not a datetime isoformat string, but actually a datetime object
I'm on London/Europe Tz. So yes, GMT+1 because of DST.
Here's the first item in the list of weather predictions. I'm not sure how to tell if the datetime is in an isoformat string or a datetime object.
{'datetime': '2023-05-03T15:00:00+00:00', 'condition': 'cloudy', 'precipitation_probability': 16, 'wind_bearing': 'NE', 'temperature': 14.0, 'wind_speed': 6.44}
How can I tell?
Using the Dev Tools>Template window. It reports that the result type is a string for this
{{ state_attr('weather.XXXXX', 'forecast')[1].datetime }} which is the weather sensor that is providing the data.
If it's from a weather entity it should be a datetime
@nimble copper Just try to compare it to a string
{{ state_attr('weather.XXXXX', 'forecast')[1].datetime > 'foo' }}
The test returns false. So it's a datetime object?
No, if it returns false it's a string
Otherwise you would have got an error that you are trying to compare a datetime.datetime with a string
👍
Is there a way to convert each datetime field in my dict into a date object?
Lately HA complains with a warning to a temple sensor I created in YAML which usually contains a number but also can contain a string. The warning goes like this:
WARNING (MainThread) [homeassistant.components.sensor] Sensor sensor.full_moon has device class None, state class None and unit thus indicating it has a numeric value; however, it has the non-numeric value: at 7:33 P.M. Central European Summer Time, Friday, May 5, 2023 (3) (<class 'str'>); Please update your configuration if your entity is manually configured, otherwise create a bug report at <link here>
The definition of the sensor goes like this:
- sensor:
- name: "Full Moon"
unit_of_measurement: ""
unique_id: "a775b3cd-8d50-4583-9ffa-e4c6fbb6c322"
icon: mdi:moon-full
state: >
{% set d = states("sensor.Full_Moon_days_until") %}
{% if '0' == d %}
{% set d = 'today' %}
{% endif %}
{% set s = states("sensor.Full_Moon_date") + " (" + d + ")" %}
{{ s }}What can I do to make the warning go away?```
It would need to be recursive and it wouldn't be able to be a macro. It's better to just make your datetimes into iso-formatted strings and treat them as strings
because you have unit_of_measurement attached to it, remove that all together. You'll have to delete it from the UI as well because you attached a unique_id to it.
i.e. delete it from the UI, then remove the unit_of_measurement from the yaml, then restart HA
Also entities should be always fully lowercase
Hey there - Thanks alot - That sounds great - Im trying to paste the url into hacs but it doesn't work ?
You don't need to add the repo to HACS, it's in the default HACS library. You do need te be on HA version 2023.4 or higher, and you need to enable experimental mode in HACS to download custom templates
Thank you.
Is there a way to format the future data calculation without the +01:00 that's being added due to DST?
e.g.
{{ (today_at('06:00') + timedelta(days=1)).isoformat() }}
Output
2023-05-04T06:00:00+01:00
Or should I just use a string replacement to remove the +01:00 and change it to +00:00?
Output
2023-05-04T06:00:00+00:00
you want the +01, that tells the system it's in the +1 timezone.
if you change the +1 to 0, you just changed the time by 1 hour.
But then it wont ever match with one of the items in weather sensor.
All of the datatimes in the weather sensor are like this.
2023-05-04T06:00:00+00:00
if you're trying to match against UTC, then you need to use UTC timestamps
06:00+00:00 is not 6am
it's 6am UTC
which is 5 AM +01:00
{{ (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() }}
I get: Repository 'thefes/cheapest-energy-hours' exists in the store.
I'm a bit confused here. The code above doesn't match the expect item I'm trying to select from the weather sensor dict.
The item in the weather sensor dict is this
However the code above shows tomorrow at 05:00am and not tomorrow at 06:00am as I'm expecting. Presumbaly due to BST / London/Europe.
Output
2023-05-04T05:00:00+00:00```
Apologies I'm probably missing interpretaing / understanding something .
no, you think 6am +00:00 is 6am when it's actually 5am
UTC is a universal time zone
it's +00:00
6am for me is 10:00+00:00
6am for you is 5:00+00:00
Ok. That makes sense.
So is {{ (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() }} changing when my time moves from DST (Winter +00:00) to BST (summer +01:00)?
DST will be accounted for with your today_at
You are still trying to add it as a custom repository
Ok. So how can I match an item in the dictionary of weather predictions? Bearing in mind that I'm trying to find the item that's tomorrow at 06:00:00+00:00?
Is there an equivelant today_at('06:00') that uses UTC time that I can add a timedelta(days=1) to?
So - Its already ready after enabling experimental ?
no, just use isoformat, your timestamps are already in isoformat in your dict.
[{'datetime': '2023-05-04T06:00:00+00:00', ....
^-- ISOFORMAT
You need to download it
e.g.
{% set t = (today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() %}
{{ state_attr('weather.XXXXX', 'forecast') | selectattr('datetime', 'eq', t) | first | default }}
How the...h... damn...I can't find it anywhere
@nimble copper I converted your message into a file since it's above 15 lines :+1:
Can't even find that place 😄
Because you’re searching for 6am your time but it’s not in the list… remember your utc is 05:00+00:00 not 06:00+00:00…
Then you don’t have experimental turned on
Im pretty sure.... I have hacs on the left hand side...from there...where should I go ?
Change your filter, my screenshot is from the main page
How do I go about calculating the the 06:00+00:00 that's in the list? So that I can match that item and use the data within it?
integration ?
The code I was suing was working as expected when it was DST back in Winter. It's only since moving to BST that it's broken
If 6am is 5am utc, what should you use? To get 6am utc?
No it's under template
In hacs ?
I'm not sure. 06:00+01:00?
Or {{ (today_at('07:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat() }} ?
But wont this code need to be changed, once my tz moves back to DST?
Do you just want {{ today_at('06:00').replace(tzinfo=utcnow().tzinfo).isoformat() }} ?
Removing unit_of_measurement from the YAML was enough to do away with the warnings. Thanks!
Yes, which you can only see if experimental mode is activated
In the intregation tab, i see hacs, if I press configure i have enabled experimental mode
Did you restart after you turned it on?
You're assuming that your forecast sensor will have 6am utc it in when DST changes
I did! :S Hmm strange...
Yes I believe so. Because the code I was using was working prior to the change from DST to BST.
To the best of my knowledge the datetime field inside the dict object has remained in the same format. YYYY-MM-DDTHH:MM:00+00:00
I can't think of another reason why the template code would stop working that would coincide with the change from DST to BST.
Im not second guessing you... 😄
then just use 2 datetimes
{% set ts = [
(today_at('07:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat(),
(today_at('06:00') + timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat(),
] %}
{{ state_attr('weather.met_office_battlefield', 'forecast') | selectattr('datetime', 'in', ts) | first | default }}
In my hacs intregrations im getting this error: Error while loading page repository.
all of them
I actually downloaded all templates which are in the store (and two of them are created by me) 😅
Not so popular yet
All templates, or also for integrations
Thank you. I appreciate the help!
In still can't see templates, its only intergrations and frontend
Not loaded in Lovelace
You have 5 Lovelace elements that are not loaded properly in Lovelace.
and 4 menus
then you're not running experimental
Is there another place to enable experimental ?
the main page will look like this:
you enable experimental via configuration options on the integration page for hacs
if the store shows HACS, then it's enabled, so maybe you haven't cleared your cache and refreshed the page
After you change the setting for experimental features, you must fully reload HACS. Restart Home Assistant and then, once Home Assistant has fully started, clear your browser cache.
Tried incognito...bingo
Just press ctrl + F5 to clear browser cache
Thanks....I think its download...so how to use it...only though code and no ui....
You were already creating a template sensor right, which is not possible in the GUI
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24') }}
Something with start ?
Not sure what you are trying to achieve
Im trying to start a device when the energy price is low
Will you be here in a couple of hours...need to pick up my kids ?
Is there a way to test / run templates from VSCode?
not within HA's environment
TIL
You probably want look_ahead: true
That's not available in VSCode though, maybe the vscode addon, but it's not available in vscode because there's no HA running
yeah, I just downloaded the HA extension and template command pallet tasks are missing
Just that Line underneath or ?
It's enabled by the extension
Which I generally assume folks here are using
it's not though if you don't run it inside the container
that's what I'm saying
That's how I run it, and that's why I've never seen the command pallet
there is no Home Assistant: Render Template for the extension outside of the container
You mean installing it in the remote code-server container?
I mean installing the extension in VSCode
That's...what I did
what OS?
It's an advertised feature of the extension
🤷♂️
Indeed
what extension are you using?
The one from Kees
Yes
You configured it with a link to your HA instance?
I'll have to look at the configuration later, work calls
I have problem with my FR24 Feeder rest sensors.
Can anyone help...
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true) }}
In an automation as a trigger ?
That could give you a 24 hour format time string when the cheapest consecutive block of three hours today starts
will that check if the now(hour) is equal to cheapest hour ?
No
If I put it in template test thingy - it says; UndefinedError: 'dict object' has no attribute 'start'
Did you test this in developer tools > template?
Okay
Did you have a look at the documentation I provided
You will need to provide a time_key
Yes I saw the banana/apple site but being all new...its tricky...
And maybe also a value_key
Look in developer tools > states to see which keys are used for your sensor
I this: sensor.energi_data_service ?
it does
In that you will see a list with an item for each hour of the day
yes correct 🙂
And there is a value with the date and time in each of those list items
Preceded by a key to indicate that value
That is what you need to provide as time_key
raw_tomorrow:
- hour: '2023-05-04T00:00:00+02:00'
price: 1.23
raw_today:
- hour: '2023-05-03T00:00:00+02:00'
price: 1.3
Okay, so you need to add time_key='time', value_key='price'
not hour ? (trying to learn)
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', value_key='price') }}
Yes, hour, sorry for the confusion
YES that gives me a response: 21:00
Okay
Just so that I learn here... that means that todays 3 cheapest hours starts at 21:00 ?
Well, not sure what time it is currently where you are, but because of the look_ahead=true setting the hours which are already passed are not taken into account
So it could be the cheapest block of 3 hours was actually at 13:00
Am I the only one that is looking for a way to create custom jinja filters? I have a need to use a small python function as a filter. There was a hacs component but it no longer seems to work.
I would love to be able to do that, and you can't
there was a feature request for Jinja to use macros as filters, which would also be nice, but it was rejected. I posted it here a while ago
(rejected by the Jinja project, not HA)
So jinja doesn't allow custom filters?
Sorry - misread your last post
Any thoughts on how to handle a complicated data conversion? I need to convert a value before passing it to a modbus service call. using a python script didn't work because the python_script integration doesn't support import.
PyScript, Appdaemon
It still takes the current hour into account
Can pyscript return a value i can use?
no, but you can stuff it into a helper and use that
or you can just call the service from PyScript with whatever you want
Arh okay... cool
the latter is what I recommend
How do I make an automation with this now ?
Either using a template trigger, or by creating a template sensor and using that in a time trigger
lost 😄
This would work for the trigger:
platform: template
value_template: >
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{% set s = cheapest_energy_hours('sensor.energi_data_service', hours=3, look_ahead=true, time_key='hour', value_key='price', time_format='time24') %}
{{ now().strftime('%H:%M') == s }}
I just lost all local access - didnt to anything
That's not related to templates
Sorry... - If I put this in template tester.. it says false
But should there also be a time pattern trigger to acompany this template trigger ?
by it self or do i need to trigger this in another manner ?
And it depends on your goal what the trigger should be, but time pattern triggers are almost never the best choice
so its not "checking" by itself ?
I'd assume that if you want to turn on a device which has a 3 hour run time, you'd want to do that when that period starts
yes..
It is, it will check every minute if the current time matches with the outcome of the template
should i somehow check for true/false ?
or do it just run when it becomes true
It would return true if the current time would be 21:00
so false since its past 21:01 ?
Correct
when will it check for next 3 hour period ?
@silver wren I converted your message into a file since it's above 15 lines :+1:
Basically every minute
so in 6 minuts I should get a new value ?
for info the code is of course slightly wrong but it's due to the translator who broke it (I'm french)
I would just like to add a second one in my configuration.yaml
Yes, but it will not return a time anymore then, because there are no longer 3 hours left in the day
if I include: include_tomorrow=true ?
Then it will probably show some time in the early afternoon
You need to add this config under the existing switch key
And only use switch: once
Ill test this out...finally, can I have this template output shown on my dashboard.
Yes, in any card which supports templates
Indeed you are right I looked with other shit that I had succeeded in creating but by chance by the miracle of the copy and paste and indeed it just worked without creating error
Thanks for the help, it's hard to connect the neurons correctly at 10pm after a day of work xD
Or by creating a template sensor out of it
I would like that...:S
Then do that 🙂
Funny... dont know how or where ?
As I said im learning much more talking here...It just makes more sence "in person"
be back in 40 min...:)
Grateful for all your help! 🙂
Looks like a single pyscript , um, script will suffice. I can move the conversion and service call into the script. Thanks for the tip.
Like this:
template:
- sensor:
- name: "Billigste 3 timer i dag - NY"
state: >
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', value_key='price') }}
quick question about trigger -> sensor
http://pastie.org/p/60yS3n6RmKIwNFNLuzwwTv
never mind, I figured out how I had to change the syntax
little advice on what i'm doing wrong here please:
state: >
{% if states('sensor.vibration_sensor_garage_door_angle_z')|int() < 0 %}
Closed
{% else %}
Open
{% endif %}
READS as Open
However the sensor state i see is 14...
apparently i can't paste screen shots
the unit of measure is angle. maybe that is messing me up somehow?
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
sorry, updated. Also, i removed the () and still shows open
state: >
{% if states('sensor.vibration_sensor_garage_door_angle_z')|int < 0 %}
Closed
{% else %}
Open
{% endif %}
im sorry. it's been a long day. i appreciate your help.
my logic brain has clearly shut down.
No worries, it happens
i still dont know, is it possible to do somthing like this
states('sensor.pc_lastsystemstatechange') == ('unavailable' or 'Suspend')
obviously without having to specify the state twice. everything i try either doesnt work or something like this only listens for the first string
states('sensor.pc_lastsystemstatechange') in ['unavailable', 'Suspend']
or is_state('sensor.pc_lastsystemstatechange', ['unavailable', 'Suspend'])
you are a lifesaver. these wouldnt match if i had a state that was available for example, would it?
this will be true if the state is either unavailable or Suspend
for all other states it will be false
cool cool, tysm
My heatpump has a sensor that gives the total system uptime every minute, I have been trying to create a binary sensor to be able to quickly tell if the heatpump is on or off, I tried this:
- trigger:
- platform: state
entity_id: sensor.total_system_uptime
to:
binary_sensor:
- name: heatpump_test3
auto_off: 0:01:01
state: >
{{ trigger.from_state.state | int < trigger.to_state.state | int }}
it seems that the trigger does not work when the state remains the same so I had to add the auto_off, is there a better way to do this?
what is the state of that sensor when the heatpump is off ?
Hey! I have a rest sensor. Is it possible to template the json_attributes reults without making a new sensor with the template as value?
I want to convert one of the json_attributes
im having some trouble with this sensor. every time i reload the templates yaml, it changes the state to clean. for some reason its triggering that id, despite it supposed to be going from on to off. the sensor binary_sensor.dishwaser is a template sensor, but its going from, unavailable to off when i reload the yaml, so i dont understand why its triggering this automation
what am i looking straight past here
no its not. you can specify a json attributes path, but you cannot template the attribute itself
Are you sure the binary sensor doesn't go to on shortly?
tbh, inline if statements are hard to read the order of operations when you have multiple. I'd break it out.
{% if trigger.id == 'dirty' and is_state('binary_sensor.dishwasher_door', 'on') and is_state('binary_sensor.kitchen_motion_sensor_motion', 'on') %}
Dirty
{% elif trigger.id == 'clean' and trigger.from_state.state == 'on' %}
Clean
{% endif %}
Also keep in mind that your tempalte will only update on the triggers, it will not update when either binary_sensor in the template updates.
@orchid oxide ^
But just to be clear, you don't have an else built into that. So the sensor will go unavailable whenever the for 3 minutes triggers and the from_state is off.
It was hard to see that logic because you were using nested inline if statements
It goes unavailable, it doesn't stay in its existing state?
Kk ill fix that then
what's confusing me is that the trigger is activating when I restart the template yaml even though theoretically neither of the triggers should activate
{% if trigger.id == 'dirty' and is_state('binary_sensor.dishwasher_door', 'on') and is_state('binary_sensor.kitchen_motion_sensor_motion', 'on') %}
Dirty
{% elif trigger.id == 'clean' and trigger.from_state.state == 'on' %}
Clean
{% else %}
{{ this.state }}
{% endif %}
is binary_sensor.dishwasher a template?
Yes. But it goes from unavailable to off, not on to off
you can make a debug sensor to see if that's true
or add them as attributes
attributes:
from_state: "{{ trigger.from_state.state }}"
to_state: "{{ trigger.to_state.state }}"
id: "{{ trigger.id }}"
Okay something much more suspicious is going on as I've added those attributes, checked my config and even double checked the yaml and spacing, and they just aren't even showing up. I'll have to figure this out later since I'm on my phone
Just kidding, actually manually triggered one of the triggers in devtools and the attributes updated, which I'm assuming means that there is no trigger causing the automation to update when I reload the yaml
Which doesn't explain why it's changing State when I reload..
trigger template entities restore state
Hold on... I'm realizing my issue now lmfao
I haven't let it actually run the dirty trigger since trying to fix this yesterday and what you put in devtools doesn't count towards restoring state so... It's probably fixed
@wanton girder I converted your message into a file since it's above 15 lines :+1:
@wanton girder what does the macro return now?
False
I have put sensors on my dashboard so I know that I have passed a time multiple times
No, the macro itself
I don't know
What is wrong with this template. It gives since the update of 2023.5.0 unknown as value
template:
- sensor:
- name: water_usage_daily_liters
unique_id: "water_usage_daily_liters"
unit_of_measurement: L
state: "{{ (states('sensor.water_usage_daily') | float * 1000) |round(3)| replace ('.',',') }}"
- name: water_usage_daily_liters
sensor.water_usage_daily has the value: 0.0592
How do I check that
by looking at what s returns in the template editor
It says false
no... {{ s }}
You say you've put sensors on your dashboard, what kind of sensors do you mean?
1200
Why are you changing the decimal symbol, that means HA can't use it as a number anymore
1200 or 12:00
12:00
all right, then your last line should be
{{ now().strftime('%H%M') == s }}
I'm using it in a mushroom chip
I made these:
template:
- sensor:
- name: "Billigste 3 timer i dag - NY"
state: >
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', value_key='price') }}
- sensor:
- name: "Billigste 3 timer i dag og imorgen - NY"
state: >
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=true, time_key='hour', include_tomorrow=true, value_key='price') }}
So, just so you understand, your template will only be true exactly at 12:00
all other times it will be false
yes but I didn't get any notifications today
When did you create the automation?
@wanton girder I converted your message into a file since it's above 15 lines :+1:
The problem with including tomorrow is that the time can change to a time which has already passed today after the data for tomorrow becomes available
I expect you also want to remove look_ahead=true, because that will also keep moving the time
When I execute it in the developer tools, the value is showed correctly: state: "59,2"
But when I add the sensor to the dashboard it shows unknown. Is there any breaking change of this? I don't see it
Could I just set these to to false for now ?
@marble jackal Okay the solution is to remove the replace part...now in the mushroom chip it is showed with the correct decimal seperator....in the developer tools it showed it wrong but that is no problem.
That's because your dashboard shows states based on your selected language and number settings
okay.
Yes, you can do that
@floral steeple I converted your message into a file since it's above 15 lines :+1:
{{ area_name(trigger.entity_id) }}
thanks!
could you explan look_ahead ?
What it does, or why you should remove it?
I am trying to figure out what I am doing wrong using Pedro's template guide. ``` sensor:
- platform: time_date
display_options:- 'date'
template:
- 'date'
- sensor:
- name: recycling day
state: >
{% set t = now() %}
{% set midnight = today_at() %}
{% set event = state_attr('calendar.recycle', 'start_time') | as_datetime | as_local %}
{% set delta = event - midnight %}
{% set values = [ 'Today', 'Tomorrow', 'Day After Tomorrow' ] %}
{{ values.get(delta.days, 'In %s Days'%delta.days) }}```
- name: recycling day
The sensor sensor.recycling_day comes back unavailable
The calendar shows the correct date and the date seems correct.
Seems it doesn't work in the template tool but his other example does.
What example did you base this on then?
@amber hull I converted your message into a file since it's above 15 lines :+1:
works
I'm trying to understand what I am doing wrong (or not understanding why Petro's code is not working for me. In any case I have them all working modifing one of his examples.
what it does
It basically sets the start hour to consider for the data to the current hour.
I actually have no clue how this should work
Oh wait, I do now
Thanks. I have it working so I'm good. Just trying to follow his code and gain a little knowledge 🙄
It works if yo do this
{% set values = { 0: 'Today', 1: 'Tomorrow', 2: 'Day After Tomorrow' } %}
@mighty ledge did something change here? You posted this 3 years ago, I expect someone would have mentioned that it did not work in that time period
It should work
Oh that version never worked apparently
{% set midnight = today_at() %}
{% set event = state_attr('calendar.hvac', 'start_time') | as_datetime | as_local %}
{% set delta = event - midnight %}
{% set values = [ 'Today', 'Tomorrow', 'Day After Tomorrow' ] %}
{{ values[delta.days] if delta.days < values | length else 'In %s Days'%delta.days }}
or
{% set t = now() %}
{% set midnight = today_at() %}
{% set event = state_attr('calendar.hvac', 'start_time') | as_datetime | as_local %}
{% set delta = event - midnight %}
{% set values = {0: 'Today', 1:'Tomorrow', 2:'Day After Tomorrow'} %}
{{ values.get(delta.days, 'In %s Days'%delta.days) }}
Or with a dict like I did above
ya
Thanks guys.
I don't understand...could you make an example
Well, assuming you only look at the data of today, and the cheapest consecutive block of 3 hours is at 13:00, and the current time is 20:50
With look_ahead= false it will show 13:00, but with look_ahead=true it will reject all hours before 20:00
Then it should be true...i guess...
That really depends on your use case. If you want to start a device on the cheapest hour of the day, so eg at 13:00 you don't want that time to change every time so the automation will trigger again at 14:00 and then again at 15:00 etc
True - Thanks, that makes sense....im waiting for the time to be 21:00
That's now
Sorry? What do you mean with that last sentence?
look_ahead=false not look_ahead='false' right
My templateslooks like:
template:
- sensor:
- name: "Billigste 3 timer i dag - NY"
state: >
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=false time_key='hour', value_key='price') }}
- sensor:
- name: "Billigste 3 timer i dag og imorgen - NY"
state: >
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_format='time24', look_ahead=false, time_key='hour', include_tomorrow=true, value_key='price') }}
Right now the first one says:: entity not avaliable and number 2 says unavaliable
@wanton girder I converted your message into a file since it's above 15 lines :+1:
did you update to the latest version in HACS, seems I introduced a bug there
Im running 1.4.1
Try to downgrade to 1.3.x for now
And I need to fix something else, I know why it doesn't work
@wanton girder I converted your message into a file since it's above 15 lines :+1:
on version 1.4.1 or an older version?
1.3.2
let me check
what does this give in devtools > template
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{% set s = cheapest_energy_hours('sensor.energi_data_service', hours=3, look_ahead=false, time_key='hour', value_key='price', time_format='time24', include_tomorrow=false) %}
{{ s }}
1.4.2 fixes the issues in the other 1.4 versions
What does this give
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{% set s = cheapest_energy_hours('sensor.energi_data_service', hours=3, look_ahead=false, time_key='hour', value_key='price', time_format='time24', include_tomorrow=false) %}
{{ s == '13:00' }}
True
Hi all, I have a water meter that reports instantanoues water consumption in the units L/h. How do I create a sensor that turns that into consumption, i.e. just Liters? I'm a little confused about the time part
Hi
i got six counters and want to pick an action based on which of them is the lowest. Is there any more elegant way than "if this counter is lower than THAT counter AND lower than THAT counter AND ....." for each and every one of them?
I have very little experiance with templates (pretend it´s zero)
Okay, so that works. Then it should also work as a trigger
what should the final try be then...does it work as a trigger and a condition ?
That would you want to put in the condition?
?
Do these sensors work?
The code you were using should work
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %} {% set s = cheapest_energy_hours('sensor.energi_data_service', hours=3, look_ahead=false, time_key='hour', value_key='price', time_format='time24', include_tomorrow=false) %} {{ now().strftime('%H:%M') == s }}
As you already have these sensors, you could also use
{{ is_state('sensor.billigste_3_timer_i_dag_ny', now().strftime('%H:%M')) }}
Do check if that entity_id is correct though
thanks ill try that 😄 Thanks again 🙂
No worries, I'm off to bed now
Sleep tight 🙂
This the correct channel for "scripts" as well?
Is there any good introduction into templates? I have NO idea how they work
Several links in the channel topic
i would like to make a template select that can inherit the state of another entity, but still set its own state or the state of a trigger sensor, but this seems to not be possible, as template selects seem to be unable to affect their own state, and there is no way to inorganically set the state of a sensor entity. therefore, the only way i can see to make this work is to have the template select change the state of a dummy entity, which can be one of the trigger sensors triggers...but then the dummy entitys state wont update if the trigger sensor updates, meaning i wont be able to trigger the template trigger...i cant figure out how to do what im trying to do lmao
at least, not without creating an automation to make the dummy sensor mirror the trigger sensors state on change
and im trying to avoid automations for stuff like this if possible
so far, the following is the best solution ive come up with, but its not particularly elegant. it would be nice if there were a more elegant way to do this:
automation: https://dpaste.org/yWqiG
template yaml: https://dpaste.org/qJNTD
is it possible in template that sensor value is be zero automatically when mqtt data does not come in ( mqtt device is turn off)?
how to solve it?
Because when device turned off then sensor value is still old value.
possible that expire_after: 3 but i want to value is zero
Since some versions ago the number of default decimals are changed. I have a lot of utilitymeters that are now showing a lot of decimals instead of 2 some versions ago. What is the best way to have 2 decimals in the UI. I have this template:
utility_meter:
vaatwasser_energy_daily:
source: sensor.vaatwasser_energy
cycle: daily
According to me you can't specify in this template how many decimals you want.
could you set thevalue template to do something like {{0 if value_template == 'unavailable'}}
dont qoute me on this, i dont have manny mqtt sensors myself
{{'{:.2f}'.format(yourvalue)}} is how i do this
ok thank possible it.
where 2 is the number of decimal places
I don´t understand what i am doing wrong. This gives me "false" even if "tagesaufgabe_wasche" is the hiighest counter.
{{ states('counter.tagesaufgabe_wasche') == counters | map('float') | max }}```
{{ states('counter.tagesaufgabe_wasche') }}
gives 20
{{ counters | map('float') | max }}
also gives 20
but
{{ states('counter.tagesaufgabe_wasche') == counters | map('float') | max }}
gives false... WHAT?
{{ states('counter.tagesaufgabe_wasche') == 20 }}
gives false
{{ 20 == counters | map('float') | max }}
gives true
BUT
{{ states('counter.tagesaufgabe_wasche') }}
still gives me 20.... I don´t get it
because states are strings and you're comparing a string to a number.
the output of all sensors is a string
if you use states() you will get a string
it doesn't matter if it looks like a number, it's a string
that's it. There's nothing else to it
so when you do a comparision with states() == 349283, you're comparing a string "this_is_a_string" to a number 89892834
notice the lack of quotes
and "89892834" will always be unequal to 89892834
I would have thought of that if the output didn´t specificly state it was a number 😄
Okay, how do i convert it?
( I know about strings and numbers, i just didn´t think HA would lie to me 😛 )
so...
{{ states('counter.tagesaufgabe_wasche') | float == counters | map('float') | max }}
?
You can simplify your template btw
{% set counters = 'counter.tagesaufgabe_altpapier', 'counter.tagesaufgabe_aufraumen', 'counter.tagesaufgabe_bugeln', 'counter.tagesaufgabe_fensterputzen', 'counter.tagesaufgabe_kuche', 'counter.tagesaufgabe_wasche' %}
{{ states('counter.tagesaufgabe_wasche') | float == counters | map('states') | map('float') | max }}
Ah got it thx
it's not lying to you
that's the ending result inside your sensor
not the result output of the template
so if you were to put that into a template, it would produce a number
templates themselves always return strings
oohhhhhhhhh i get it
the template resolver runs after and tries to discern the type it will be.
you can check types inside your templates by using is
e.g. {{ 'abc' is string }}
thats something to trip a beginner up
At least when i was programming a compiler would give me something like an invalid variable type or something 😄
Thanks for rescuing me
AGAIN!
np
Where do you place this? Do you create a new template sensor based on the utility meter?
i didnt use it for utility meter, but i looked and utility meter doesnt accept templates, so you could create a template sensor if you wanted, or if you just want to use it on the dashboard you could just place it in a card that accepts templates
Okay I will format it in my dashboard
hi. what's the optimal way to turn off all lights except one particular entity (e.g. light.led_eyes), without creating and then curating a group by hand.
service: light.turn_off
target:
entity_id: >
{{ states.light | rejectattr('entity_id','eq','light.led_eyes') | map(attribute='entity_id') | list }}
should work
great! indeed it does
I got the following list
I need to map each iten to get the value of a dict and then join it all as a string
{{ states.sensor.plex_ena_server.attributes.keys()|list|reject('in', ['unit_of_measurement', 'icon', 'friendly_name'])|list }}
I cant figure outhow map works with this syntax
what are you trying to do?
I want to get the values from the dict to send as a message
the values from all the keys that aren't in that list?
like this?
{{ states.sensor.plex_ena_server.attributes.items()|rejectattr('0', 'in', ['icon', 'friendly_)name', 'unit_of_measurement'])|map(attribute='1')|join(', ') }}
works4me
Im trying to understand how this map works
in this case, it's extracting the value for every key (that's left)
but like what is attribute='1'?
it's kind of a special case. using .items() on a dict returns a list of (key, value) tuples
then you can access each item in the tuple by its index
it's a dumb example, but this returns [3]:
{{ [(1, 2, 3, 4)]|map(attribute='2')|list }}
that hurts to look at
both of these return 3:
{{ [(1, 2, 3, 4)]|map(attribute='2')|first }}
{{ (1, 2, 3, 4)[2] }}
thus endeth the class on stupid template tricks
the 2 in [2] and attribute = 2 is just the index of the value
yes
{{ states.sensor.plex_ena_server.attributes.items()|rejectattr('0', 'in', ['icon', 'friendly_)name', 'unit_of_measurement'])|map(attribute='1')|join(', ') }}
in this, 0 is the key and 1 is the value of the respective key-value pairs
I did itah I get it this doesnt help
bc it ltierealy can only Map
like directly to another param
can i have 2 green checks
{% for key in states.sensor.plex_ena_server.attributes.keys()|list|reject('in', ['unit_of_measurement', 'icon', 'friendly_name'])|list %}
'{{ key }}' is watching '{{states.sensor.plex_ena_server.attributes[key]}}'
{% endfor %}
this worked
was a nightmare tho
That all seems like gibberish
is your point that you want to compose a sentence with those keys and values?
yes
that too
I guess im just too spoiled by javascript's map, where I can do anything inside of a context of the map
Sure!
HUGE
hi
i am trying to make a template sensor which can calculate the date out of weekday, year and calendar week
this is what i have, but it does not work:
- platform: template
sensors:
berechnetes_datum:
friendly_name: "Berechnetes Datum"
value_template: >
{% set januar_1 = as_datetime(sensor.akt_jahr ~ "-01-01") %}
{% set tag_jan_1 = januar_1.weekday() %}
{% set erster_donnerstag = januar_1 + timedelta(days=((4 - tag_jan_1 + 7) % 7)) %}
{% set gesuchter_tag = erster_donnerstag + timedelta(days=(input.wochentag - 4)) + timedelta(weeks=(input_number.kalenderwoche - 1)) %}
{{ gesuchter_tag.date().isoformat() }}```
I've got a few errors while rendering some template sensor in logs :
Error while processing template: Template<template=({% set alarm_time = as_timestamp(states('sensor.next_alarm')) %} {% set time_now = as_timestamp(now()) %} {% if alarm_time != None %} {{ time_now >= alarm_time }} {% else %} {{ unavailable }} {% endif %}) renders=2>
don't quite know what's wrong with it ...
What's states('sensor.next_alarm')?
a time
Why is the following selectattr('state'|int, 'lt', 25|int) failing?
{%- set entities = states
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'battery')
| rejectattr('state', 'in', ['unavailable', 'unknown', 'none'])
| selectattr('state'|int, 'lt', 25|int)
-%}
Errr
ValueError: Template error: int got invalid input 'state' when rendering template '{%- set entities = states
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'battery')
| rejectattr('state', 'in', ['unavailable', 'unknown', 'none'])
| selectattr('state'|int, 'lt', 25|int)
-%}' but no default was specified
I tried adding int(0) on the state, it didn't help. I tried float, no luck. And if I use 'lt' with string, then obviously the filtering is incorrect.
Do I have to use a for loop? 😦
this part is wrong:
'state'|int
that's trying to turn a string into an integer 🤷
and 25|int is turning an integer into an integer
there isn't a straightforward way to do what you want
Well, I can't compare strings, the compare will be false. For example, if I use selectattr('state', 'lt', '9') it will list all sensors with battery laver (aka state) of 100 🙂
So, I have to use selectattr on the state attribute in int or float in order for the filtering to be correct. But for whatever reason, it doesn't accept the |int conversion.
you're literally trying to turn the string "state" into an integer
indeed, that is the goal!
you can't do that to modify
no, literally the string "state"
that is a word
it is not a number
I understand what you're trying to do and there isn't a straightforward way to do it
it really depends on what you're planning to do with the entity list you're generating
This is why I make sure I filter out entities where the state is only a number, basically device_class=battery where the state is not unavailable. I checked, the returned list has only numbers in states. Now I want to filter out numbers below say 9 (9% battery), and I need to compare numbers, not strings for that.
The bloody thing doesn't want to convert the state str into a int 🙂
I don't think you're understanding
'state' is just a string
it is not the state of an entity
I just want to get a list of entity_id's that are of class battery and have the state (battery level) below N%
Well, it should work !! Here is an example of it working
{% set test = "foo" %}
{{ test|int(0) }}
Retunrs 0
we have discussed creating a filter that allows one to modify the incoming value before a comparison (such as converting it to an integer), but I don't think it exists yet
sigh
I'm saying that this makes no sense at all
| selectattr('state'|int, 'lt', 25|int)
do you understand that?
nope 🙂
I mean, i don't need the 25|int, the int can go away. But it should be able to convert the 'state'|int(0) to an integer where possible and to 0 where not possible. I don't get why this is not working
you do not understand at all
I keep saying it
"state" is just a string. it IS NOT the state of an entity
it is a string
a string
not a number, not a state
like "foo" or "tulip"
or "whale"
you cannot pretend that typing 'state' represents the state of the entity, and then do something to it. it is just a random string
ok, how do I pipe and filter out based on state then? is it not {% set entities = states | selectattr('state', 'lt', 25) %} ?
It can't be that, as states are strings and your comparison value is an int. There isn't a way using selectattr to map state to a string though and compare it to the comparison value, as Rob mentioned.
One way is a loop ... if you need other properties from the object, if you need a count, just map state to an integer and then filter your list
I get it, but what is the way then?
And the 'state' in this case is the state. For example this works perfectly:
{% set entities = states
| selectattr('state', 'eq', 'on')
%}
{% for entity in entities %}
{{ entity.state }} : {{ entity.entity_id }}
{% endfor %}
I can filter and only show entities that are 'on' or 'off'. So why cant I filter based on numbers, where the state is a number
I see, so a for loop is the only way.
As I said, it's one way. If you need to list things out like you've got there, that's probably the route you want to take
If you just want to say ## of devices have < 25% battery, you can do it using filters
apparently I cant, because the comparison can only be based on strings, not on integers 🙂
jinja weirdness I guess
How about we try this... what are you trying to accomplish
End goal
It's not Jinja-weirdness, it's order of operations in this case
This is literally what you're doing in the template, notice how it's the same error
GOAL: I want to get a list of all entities where the battery level is below 15%.
Approach: iterate trough the state database, filter only entites where device_class is battery, filter out entities that are in unnown/unavailable state, the filter only entities where the state (the battery level) is below 15%, and then map that to entitty_id attribute so I get a list of entity_id's which satisfy my criteria above.
Technically, this should work
{%- set entities = states
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'battery')
| rejectattr('state', 'in', ['unavailable', 'unknown', 'none'])
| selectattr('state'|int(0), 'lt', 15)
| map(attribute='entity_id')
-%}
But it throws an err (see above), saying that I didn't supply a default value when converting the state of the entity from str to int
so I know how to do a template for if a device is on, else etc, but I have a water temp on my washing machine that when off or not running it shows water temp as not selected
how should the template go for this if anyone has time
Hey guys, I've got a simple question I can't quite figure out
I've got some code atm that imports a macro, runs some code and spits out a result, as below:
{% set postcode = states('input_number.postcode') %}
{% set coords = suburbCoords(postcode | int) %}```
This code works and spits out a valid working result for coords, but I want to use it for a rest url and want to do something like add it to the end of a url like www.google.com or whatever
Whenever I try to do something like www.google.com/{{coords}} in dev tools it just has the url and a bunch of white space that never seems to end (on mobile and it takes so long to scroll I've not been able to get to the bottom yet). How can I add it to the end of my url for a rest command?
-> is the way, though