#templates-archived
1 messages · Page 101 of 1
Any way I can pad utcnow().month to two digits for a month like August (08, not 8)? I'm trying to have an automation curl an api where that's an issue
So like dateutc=2020-08-25+04%3A39%3A46 instead of (now) dateutc=2020-8-25+4%3A39%3A46 (please @ me since I'll be AFK for a while)
Hello everyone! Looking for a jinja guru to streamline an integration of 17track. How can I add a filter on the below template sensor to only look for entities that contain 'seventeentrack' ?
sensors:
seventeentrack_packages_not_found:
value_template: "{{ states | selectattr('state','eq','Not Found') | list | count }}"
@thorny snow entity states?
@mighty ledge No I want to filter entity_ids. This integration creates multiple entities with names like sensor.seventeentrack_package_lb988831186b3
You'll have to use namespace and a for loop, there isnt' a test that works for selectattr for matching parts of a string
I see. I also looked at selectattr and select but couldn't find a way to do it. I thought I may be missing sth
you can try this, it might work:
{{ states | selectattr('object_id[:14]','eq','seventeentrack') | list | count }}
the problem with select and select attr is that the use built in tests like "eq" and "==" etc
Ok, I will try that thanks a lot!
so you'd need one that is "contains" and that doesn't exist
yeah it is pretty restrictive in that way
exactly
ok thank you so much @mighty ledge will try that and hopefully get somewhere!
Can somebody help me with my REST binary_sensor? It's a Nuki brudge which returns a json where I want to check the doorsensorState value that tells if the door is open (or not). Currently, the sensor always stays OFF/Closed.
Door sensor status is currently not supported by the HA Nuki integration, that's why I'm building it custom.
Sensor: https://pastebin.ubuntu.com/p/sKDFyXqqzQ/
Example Json: https://paste.ubuntu.com/p/X5dHhYbG66/
value template should be
{{ value_json[0].lastKnownState.doorsensorState == 2 }}
can't use is_state because it's not a state object and not in the state machine
also, you'd want to make this a binary_sensor
{% if value_json[0].lastKnownState.doorsensorState in [ 2, 3 ] %}
{{ value_json[0].lastKnownState.doorsensorState == 3 }}
{% else %}
Unknown
{% endif %}
it works like a charm! thanks petro!
np
hi, is there a way how to make sensor from JSON response for REST API endpoint ?
How do I get just the 'episode' from the list {{ state_attr('sensor.sonarr_upcoming_media', 'data') }} ?
thx, I didn't noticed that it support other methods
@distant plover would need to see the output of that template
There are three items in that list, the last two of which both have an episode. Which do you want, and will the list always be the same?
Well, I kinda used it as an example. I'm creating a sensor from an external API but not sure how I should store the data. So I looked at the sonarr_upcoming_media. And if I can grab 'episode' from that somehow with templating, I may go for a similar approach. To answer your question: Say 'episode' from the second list, and say list will always be the same.
most seem to 2 part it. 1 to pull the whole payload and another to parse out the attribs into individual sensors
What I want to store is basically the 10 last bank transfers. Already have the sensors for each bank account. So I'm thinking something like this:
account_id: 23525235232asfasgfasfaf2535
account_number: 23525235235
available: 1000 USD
name: Bank account
transactions: {'26.08.2020: 500 USD from 23523523', '25.08.2020: 100 USD from 233523523', '24.08.2020: -500 USD to 23522352352'}
might want to edit out those numbers
Splitting the transactions into date, value and text is probably smarter, but a bit more effort perhaps
You mean from discord? They're not real. Just hammered keyboard.
Looks like dummy nubers
ok cool
Thanks though.
should have made yourself look like a baller
transactions: {'26.08.2020: 5000000000 USD from 23523523'}
But templating can easily access nodes with lists down in the hierarchy like that?
yeah, but you need to specify which dict within that list you want to reference
The short answer to your original question I think is: {{ state_attr('sensor.sonarr_upcoming_media', 'data')[1].episode }}
right, assuming it's always the second item in the list
Maaan... [1].episode outside the ()
yep, [1] is specifying the second item in the list (zero indexed) which is a dict that has an episode key
Yeah, I did all kinds of data[1]...
Thanks. Now I know that I can procede with building my sensor. 🙂
Sounds like me when I tried get the 1st temperature from a weather forecast yesterday 😂
im having trouble getting the value of the sensor to translate. im using the mqtt.publish service using this
payload: "states('sensor.ikea_dimmer_brightness')" topic: iotlink/workgroup/htpc/commands/audio/volume
but when i look at the value in mqtt explorer it says volume = states('sensor.ikea_dimmer_brightness')
Templates need to be wrapped in curly braces "{{states('sensor.ikea_dimmer_brightness')}}"
Probably rule 1 too
thats weird. when I posted that comment I actually realized that I didnt have the braces and tried it with the braces and it still didnt work
but I just copied your snippet right now and it worked
I gotta learn more about how this all works. Thanks for your help! 😄
is this still a viable template for an automation action:
action:
service: script.water_alert
data:
alert_title: "Water Sensor Alert"
alert_message: "Water detected from {{ trigger.to_state.attributes.friendly_name }}"
Well, until the change hits a release the makes data_template no longer necessary, you need to change data to data_template.
duh...thanks
FWIW, you can use trigger.to_state.name which is a shortcut for the friendly name attribute (or the entity_id if the entity does not have a friendly name.)
@hardy iris posted a code wall, it is moved here --> https://paste.ubuntu.com/p/NpCJY79G8N/
@hardy iris Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
nothing was showing up in my logs. I followed someone's example on reddit just now and added a "name" field and now its showing up, its just listed as a seperate entity now. But atleast I can see it and I can see the value chaning
I was originally following the z2m wiki https://www.zigbee2mqtt.io/devices/E1744.html
but using this https://www.zigbee2mqtt.io/devices/ICTC-G-1.html I have both of these devices and the ictc-g-1 properly reports brightness
hi, how do i set up a similar template for rgb_color instead of kelvin?
entity_id: light.entity
kelvin: "{{ state_attr('sensor.circadian_values', 'colortemp') | int }}"```
@solid dock where would you be pulling the rgb_color name from? another sensor?
I have a similar setup where I use an input_select. Does not scale wery well to millions of colors, but works fine for a few basic ones
- service: light.turn_on
data_template:
entity_id: light.foobarbaz
color_name: "{{ states('input_select.color_foobarbaz') }}"
yeah i have one where tasker sends the color name
changes a light color if i get a notification. yellow for snapchat, blue for facebook, etc
Lots of good stuff here! Its like a treasure hunt
I'm fairly new to HA and have found all to often that I have made thing harder than need be. I want to make use of templates to reduce bloat and make maint easier. I see groups and templates but have found a way to use State of a group to trigger a action that refers to the item in the group the triggered to group state. Did miss something or can you offer advice or guide to notification triggered by groups of like devices? Thanku
What are you trying to do?
Functionaly, I want to know when doors are opened, when garage doors are opened and left open, when motion is triggered on cameras all sending notifications. I haven't investigated it yet but later I'd like the notification from the camera to cast video, Specifically, I'd like to know which group member state chgd to trigger the group chg. If that isn't doable I will just use the entity's as a list in the trigger
Hey - I'm not very skilled in this code syntax and usage. But perhaps some one can help me. If i have a sensor that gives me a message as an atrribute.
last_message: 2020-08-28T18:17:00.175423+00:00: SIA: Code: TR, Type: Tamper Restoral, Description: Alarm equipment enclosure has been closed, Message: 1
How would i use as an example regex to take out the different values in this?
A regex like this i found to be successful (not good perhaps) Code:\s(?<Code>\w+|\d+)|Type:\s(?<Type>\w+\s\w+)|Description:\s(?<Description>.+),
But how would i do such a thing with a template?
Not sure HA's Jinja regex accepts all of that, but I found this might do it for you: {% set result = state_attr(ENTITY, ATTRIBUTE)|regex_findall_index("Code:\s(\w+|\d+).*Type:\s(\w+\s\w+).*Description:\s(.+)") %} Then you can use {{ result[0] }} for the code, {{ result[1] }} for the type, etc.
Hi there, is this possible to use templates within configuration.yaml ?
I'm trying to build a dynamic input_select entity
What do you mean by "dynamic"?
You might want to look at https://www.home-assistant.io/integrations/input_select/#services if you haven't already.
I'm using this declaration in order to build an input selector:
input_select:
harmony_hub:
name: Harmony Hub
options:
- Powered Off
- Regarder un film
- Écouter de la musique
- Écouter un vynile
- Regarder un DVD
- Steam
initial: Powered Off
icon: mdi:monitor
And i would like to populate options list with the content of another list, coming form one attribute of anther entity (in this case remote.harmonyhub.attributes.activity_list)
You might be able to use a YAML anchor & alias. Wait, never mind. Use a service. See the doc link above.
there maybe a much smarter way of doing this... i'm try to enhance some conf block grabed on a glog
Anchors and alias could work if activity_list was declared in the same yaml file, which is not the case. I'm i wrong ?
ok
I don't really understand how could I use the service. maybe by not declaring options in the yaml, and create/update the attribute through an automation ?
You have to declare some initial list of options. (Not sure if it allows an empty list.) But, yeah, you'd use an automation to update the options from the remote attribute.
Maybe just start with a list of one entry like Not Defined Yet or something.
I think you have to have at least one entry in the list. Yep, just verified.
ok thanks for the check
options: Not Yet Defined should work.
ok gonna try this thx
@violet oyster from the circadian_lighting sensor
I'm shamelessly copying code and testing to learn how to create template based automations. Can anyone tell me why
trigger:
- event_data: {}
event_type: state_changed
platform: event
condition:
- condition: template
value_template: '"{{ trigger.event.data.entity_id in (expand(''group.doors'')
| map(attribute=''entity_id'')) }}"'
action:
- data_template:
message: '{{ state_attr(trigger.event.data.entity_id, ''friendly_name'')}}'
title: State changed!
service_template: notify.mobile_app_jeffs_iphone
homeassistant.exceptions.TemplateError: UndefinedError: 'trigger' is undefined
you have some quote problems there
single quotes, double quotes, double single quotes all mixed up like a salad
Thanks - I think its time for me to move on from using the UI and cutting and pasting into it. I'm temporarily one handed but this is second time you've pointed this out.... walk of shame
I'm looking for a way to save the data of a sensor at a certain time to use it in a template. How can this be done.
Hi, as advised by @chrome temple i'm using this to template options of an input_selector through the input_select.set_options service.
data_template:
entity_id: input_select.harmony_hub
options: '{{ trigger.to_state.attributes.activity_list }}'
service: input_select.set_options
It basicaly works but seems to return a string and not a list. I've tried to add |list filter but the result is the same (or look the same : a string containing a pyhton list declaration)
I've tried several things, like iterating to build a yaml list, but nothing works so far.
Any idea ?
You can't get it to make YAML. YAML is a representation of data structures in text form - once they're loaded by HA, you're dealing with lists and dictionaries.
A possible answer was already given yesterday. Look at maps.
There are also threads on the forums about the very same problem you're trying to solve: https://community.home-assistant.io/t/using-templates-for-input-select-set-options-populating-options-within-an-input-selector/55025
ok, i've tried to deal with map but it seems i did not yet understand how to 😦
You need to use a python_script
I'll look into this post
Yeah, Python script seems about the only reliable way to get around the limitations of Jinja templates always returning a string.
If an integration can automatically cast a string to the data type it needs, great. Otherwise, you're expected to provide the correct data type.
understood
I'm on my phone so can't provide more details. Just search the forum for python_script and input_select and you'll probably find an example.
Right, thanks again 🙂
I'm having some trouble passing an array from an event to a template light.
The event correctly shows
"service_data": {
"hs_color": [360, 0]
But trying to pass that into a template is not working, returning homeassistant.exceptions.TemplateError: UndefinedError: 'hs_color' is undefined
data_template:
h: "{{ hs_color[0] }}"
s: "{{ hs_color[1] | round }}"
v: "{{ ( state_attr('light.strip', 'brightness') / 2.55 ) | round }}"
@tribal rock posted a code wall, it is moved here --> https://paste.ubuntu.com/p/DnCYVTVYwP/
Where are you using that data template? I don't see it in the rest of your code wall.
Also, don't forget the rules
@tribal rock Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
Ah, okay, I'm sorry about that @ivory delta. I didn't know if it was 15 lines per snippet or collectively
I will be sure to review the rules, looks like I'll be on here often 😅
The 15 lines is because looking at any wall of text is annoying, especially for mobile users.
That's understandable
The data_template in question is used in the configuration of a Template Light, under the set_color action
It would help if you shared that config upfront too if it's the core of your problem.
But the error message it's giving you is all you need to know. You're asking it to read from a variable called hs_color that doesn't exist in that context.
Don't share pictures of text.
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
sorry..
If you're going to share, share via one of those tools.
Or don't... but then you won't get the help you came for.
I'm installing haste on pi, for future use as well
There's no need to install anything. You just copy/paste into the website, hit save, share the link it generates.
Hmm, formatting seems off though
<config>/modules/lights/template.yaml
https://hastebin.com/abuhilosor.cpp
<config>/configuration.yaml (Excerpt)
https://hastebin.com/kewumowuqo.sql
Is this okay btw? Not an image, and much prefer the colour formatting. "Hastebin or similar"
https://carbon.now.sh/Yprn8FpgOOYE5W5Eq2LD
Hi, I want to filter out 0 values, so I've created this template, but it does not work. My sensor is zeroed during night. Why ?
sensors:
covid19_sk_daily:
value_template: "
{% if state_attr('sensor.covid19_sk', 'dailyConfirmed') != 0 -%}
{{ state_attr('sensor.covid19_sk','dailyConfirmed') }}
{%- endif %}"
entity_id: sensor.time
friendly_name: "Daily cases"
icon_template: "mdi:arrow-up-bold"
unit_of_measurement: "people"```
screenshot: https://i.imgur.com/OzppCvx.png
What do you want it to report if the number is zero?
You’ve only told it about what to do if it’s non-zero, but not what to do when it is zero. It comes down to what you mean by ‘filtering’
You just want it to report the previous value?
I would use an input_number and an automation based on sensor.covid19_sk to update the count if it’s non-zero
yes, if it is non zero, update sensor with current value, if it is zero, skip, use previous value
Ok, see my last comment
I don’t think a template sensor is the right tool for this job
@ivory delta and @chrome temple I've finally used a rest_command to update input_select like some others did in the thread you pointed me too. Works fine and it's pretty easy to setup. I'll look into python_script next time.
I end up with 3 automations, where i was using 2 automations and one script for each input... and the previous config was static where the new one is updated from the harmony hub states
way better then 🙂
@wispy chasm I have to leave, but I can give you the rest of the details when I get back. But here's a python_script that should do what you want (in conjunction with an automation): https://paste.ubuntu.com/p/NHSgFRPfFk/
Put that code into /config/python_scripts/set_options.py. Then use it like this: https://paste.ubuntu.com/p/MGYk9MhJWM/
Hello, so this is the scenario I am trying to figure out.
my water geyser has a rotating knob (already fixed a dc motor which works fine).
I want to set 3 steps, Low, Med, High by using rotation timing of the motor, e.g, 2s from med to high (middle to left).
How to deal with the complexity of let say making it know when it is on med, low or high so it moves accordingly. As in, having 3 button setup on HA, simple M L H, pressing M while it's on L, takes it to M and when pressed M again, it stays where it is.
Hope it makes sense. Thanks
you posted this same thing yesterday and I thought got some responses
are you looking for help with the UI part of it?
is a geyser a fountain?
Hello everyone! I have unsoldered the non-esp8266 wifi module and replace it with a esp8266 running tasmota on this gateway and I have most it it working thought console. https://www.aliexpress.com/item/4000303875313.html?spm=a2g0o.cart.0.0.5d773c004jMgEY&mp=1
The last bits of the message is a checksum for example to change the temperature: 55aa000c000f0633323137343502020004000000d230
06333231373435 is the ID of the TRV is going to control, D2 is the temperature I want to set and 30 (the last 2 bits) is a checksum of the rest of the message which can be easy calculated here https://www.scadacore.com/tools/programming-calculators/online-checksum-calculator/
Is it possible in HA somehow to calculate the checksum of the message?
@hybrid spoke If it's a simple calculation, yes. If it's hidden behind that company, no way to know without reverse engineering.
@mighty ledge the payload is 55aa000c000f0633323137343502020004000000 atm I have it converting with {{ my_test_json['test'] | int(base=16) }} which results in a payload 489055346287242978748645544381040812968793604096
is now possible to sum all those numbers together with a template?!
{% set v = my_test_json['test'] | int(base=16) %}
{{ v | string | list | map('int') | sum }}
@hybrid spoke are you sure you want to sum the ints? Wouldn't you want to sum the values of 55aa000c000f0633323137343502020004000000 ?
You get 2 very different results.
yes @mighty ledge that's what I'm understanding now
What's the expected value of 55aa000c000f0633323137343502020004000000, 111?
55aa000c000f0633323137343502020004000000d230 this is the complete message
i should get 30
Yes, but what do you expect as a sum
Ok, that's not what I would expect
what checksum equation are you using
I have no idea how you exepct to get 30 out of that. All the checksums listed on your link are much much higher.
@mighty ledge i need to sum all the byte values the result and the last byte should equal the result modulo 256
do i make sense?
Checksum = Byte-sum results from the beginning of the frame, 256 remainder
you'd be better off making a python script
aslo modulo 256 still doesn't return 30 as a result with that value.
I'm already struggling with a template @mighty ledge 😅
it's not the template that you're struggling with it's the equation
and your expected value
None of the checksums that i've tried result in 30.
also, they are infinitely easier in python opposed to jinja
Anyways, going off what appears to be modulo 256, I get an answer of 139
{{ my_test_json['test'].encode('ascii') | sum % 256 }}
its a sum of all bytes then mod 256
yes, the problem is he says he expects 30
my jinja template does a sum of ascii bytes and mod 256 directly above your post
that message is likely not following the proposed spec for checksum
sorry trying to work it out on excel, but the @jagged obsidian they follow or at least on the checksum calculator they all match 55AA000C000C063332313734356501000100ba taking ba out will result on modulo 256 ba
thanks alot @mighty ledge
let's take it from the top: how can i turn a string 55aa0003000103 into a list of 55,aa,00,03,00,01,03?
If you're trying to support a beginner, asking that is basically talking about magic.
{% set string = namespace(input="55aa0003000103" | list, output=[]) %}
{% for x in string.input %}
{% if string.input[0:2] %}
{% set string.output = string.output + [string.input[0:2] | join("")] %}
{% set string.input = string.input[2:] %}
{% endif %}
{% endfor %}
{{ string.output | join(".") }}
There must be a better way
lol I can’t think of one
If regex findall returned a list we could do it in 1 line
But whoever made that forced it to be a single index
i was close then {{ my_test_json['test'] |join('[2]) }} lol
findall would definitly work (I tried that first and got the same problem)
and the results match the given checksum
is it possible to have that calculation on a template?
@hybrid spoke
{%- set input = "55aa000c000f063332313734350202000400000037" %}
{%- set string = namespace(input=input | list, output=[]) %}
{%- for x in string.input %}
{%- if string.input[0:2] %}
{%- set value = string.input[0:2] | join("") | int(base=16) %}
{%- set string.output = string.output + [ value ] %}
{%- set string.input = string.input[2:] %}
{%- endif %}
{%- endfor %}
{{ string.output | sum % 256 }}
don't see how it will work if your last value is 3 characters or 2 characters and there's seemingly no way to know that.
Er, nevermind, i read your excel sheet wrong. that code should work.
thank you a lot!! I'm gonna work out the rest and test
I have this template that shows date, amount and text of a transaction: {{ state_attr('sensor.account_241412412', 'transactions')[2].accountingDate[:10] }} | {{ state_attr('sensor.account_241412412', 'transactions')[2].amount }} kr | {{ state_attr('sensor.account_241412412', 'transactions')[2].text}}
I'm using it in markdown card in Lovelace and it's working fine. But how can I have another line with transaction number [3] without corrupting the entire card if there is no transaction number 3?
Make a for loop and iterate based on the number of transactions
I was just about to ask if that was the way 🙂
{%- for transaction in state_attr('sensor.account_241412412', 'transactions') %}
{{ transaction.accountingDate[:10] }} | {{ transaction.amount }} kr | {{ transaction.text }}
{%- endfor %}
SOLVED!!!!! I have several automations that I c/want to/can now/ check a group of entities binary sensor for change and send a notification, By following examples I've gotten an automation to send a notif for any state_chaged in a particular group but I need to constrain the notif to "on" status for the sensor and have been unable to so after many tries at copying examples. I've also reviewed https://www.home-assistant.io/docs/automation/templating/ several times over several days. Can anyone suggest how I can better understand the nomenclature of triggers in an automation or other documentation and examples?
- event_data: {}
event_type: state_changed
platform: event
condition:
- condition: template
value_template: '{{ trigger.event.data.entity_id in (expand(''group.doors'') |
map(attribute=''entity_id'')) }}'
- condition: template
value_template: '{{ trigger.event.data.entity_id.new_state == ''on'' }}'
action:
- data_template:
message: '{{ state_attr(trigger.event.data.entity_id, ''friendly_name'')}}'
title: Door opened
service_template: notify.mobile_app_jeffs_iphone
Hello,
I have a timestamp in a MQTT topic. How can I create a rule that triggers 5 minutes before that timestamp?
I allready set up a time_date sensor, but unfortunately, I don't know how to compare the current timestamp with the one from the mqtt topic.
Anyone have a decent example of mapping one number to another? I want to use the Circadian Lighting value, which goes between 100% and -100% approximating the sun's elevation, to adjust the saturation of a color. My present goal is a blue accent light, which adjust slowly throughout the day to be a cool blue (nearly white) at solar noon, and is a deep saturated blue in the middle of the night. When I figure this out, I'll work on adjusting its brightness separately. Ideally, I'll use the UI to adjust the solar noon color and brightness and solar midnight color and brightness, and I'll have a light template track this color, then I'll assign one or more Philips Hue lights as "accent lights" which track this accent color. Any help with this task would be appreciated.
@slim sage dont mean to be rude but that question is way too broad to get an answer here. you'd need to show what you've tried and be asking why it didn't work. if you want guidance on broad concepts like this you'll have better luck on the subreddit or HA forums
only thing i can really say is manually adjust the light to match the current circadian value and then build a template to return the thing you want
@slim sage there’s a custom circadian lighting integration that you can use.
@lyric night posted a code wall, it is moved here --> https://paste.ubuntu.com/p/SSMkmmmPfJ/
So what I was saying is that my templating works fine in the templating page but not with a sensor, code in link above
Maybe this is a #frontend-archived question, but what does one do with templating in the markdown card if it's an interation over a null value because the entity isn't initiated yet? I'm getting a TypeError: 'NoneType' object is not iterable. Here is the iteration: {%- for transaction in state_attr('sensor.account_214242', 'transactions') %} {{ transaction.accountingDate[:10] }} | {{ transaction.amount }} kr | {{ transaction.text }} {%- endfor %}
Just slap a or [] in the for statement
@rugged laurel sorry to ping but do you have an idea for my issue ? been searching since yesterdayy :/
Haha. That crashed HA. Just spinning. You meant like this? {%- for transaction in state_attr('sensor.account_214242', 'transactions') or [] %} {{ transaction.accountingDate[:10] }} | {{ transaction.amount }} kr | {{ transaction.text }} {%- endfor %} EDIT: Nevermind. It crashed because I had manually set the values of the entity to something really invalid. I was able to find this in logs: AttributeError: 'str' object has no attribute 'keys'
Yeah, that worked in my test
A restart of HA fixed things and no errors in log on this matter anymore. Thanks a bunch.
if it fails, you can use this instead | default([], True)
How is it possible that a manually defined templating does not render as the exact same templating (copy/paste) set within a sensor and that this same sensor does not render the same result through templating page and the real entity ? This makes me crazy
i wish someone achieve to explain this to me
you posted this same thing yesterday and I thought got some responses
@inner mesa no, I was redirected here. Not just the UI, more of "how-to" guide. It's a water boiler/geyser. Thanks
@lyric night It looks like you're using {{ states("volet_roulant_salon_status") }} in the template page to check the value of the template sensor, however, the entity id will be sensor.volet_roulant_salon_status so you should be using {{ states("sensor.volet_roulant_salon_status") }}
https://www.home-assistant.io/docs/configuration/templating/#time and https://jinja.palletsprojects.com/en/master/templates/#comparisons
@wispy chasm thanks for your answer. This is what I found so far:
`- id: '1570917544192'
alias: Lichtwecker
trigger:
- platform: template
value_template: >
{% set time_now = as_timestamp(now()) %}
{{ time_now >= ( **MQTTValue **- 900 ) }}
action:`
But unfortunately I haven't found any possibility to get the MQttValue
oh you're right
but the state is still not the same between the sensor and templating 🤔
now() is not continually updated in templates, so your sensor won't update either.
You'll need to use something like the datetime integration.
For templates to be re-evaluated, at least one of the entities within that template has to change. now() is not an entity and I assume your MQTT value remains mostly static.
@ivory delta is this for me ?
I don't see anyone else wondering why their template isn't updating...
Wait, I do. D'oh.
What's the problem with yours, repz?
i don't have the same value between the sensor i declared and the same templating in the template page
What values do you have?
@lyric night I notice that you have entity_id: [] in your template sensor. That option is used to override the default detection of entities to track for changes for a template, so I would assume that this would stop it from working as it is telling it not look at any entities.
But unfortunately I haven't found any possibility to get the MQttValue
@dense wing You'll need to set up an MQTT sensor. Check the integrations page to see how.
That link doesn't work for me, repz.
But what states does the sensor give? And what are you trying to do?
Ah. So it works when you remove entities: []?
Awesome
made me craZY
I'm glad Steven was paying attention. I haven't had coffee yet 😄
thanks a lot
@dense wing You'll need to set up an MQTT sensor. Check the integrations page to see how.
@ivory delta ok thank you. I managed to build up the following:
{% set time_now = as_timestamp(now()) %} {{ time_now >= ((states.sensor.alarmtime.state | float ) - 60.0) }}
If i paste it to the template check in the web interface it says true ore false as expected. However the rule still not fires 😦
mono please go have some coffee
No need, I'm awake now. 😉
But they're using a template with only a single entity that doesn't change... of course it'll never trigger their automation 😄
LOL
Thanks for your replies, I finally managed to get it working 🙂
Hey, how can i day "now-7days" in template ?
yes
i have a sensor giving me my weight, i would to make a delta with my weight from a week ago
Some more details and/or context might help. E.g., what format do you want the result of the template to be in? Where is it being used? In a template sensor configuration, in a service call in an automation or script, ...?
Do you have any existing code that you could share, even if it doesn't exactly work yet?
ok! I don't have anything yet, i'm more planning and try to figure how to do it. Maybe template is not the best solution for that, i'm kind of a newbie in creating sensors etc...
So I have a sensor from withings giving me my current weight in an entity, tracked by the history component. My dream would be to make a sensor that gives me the average value of day-1 to day-8 (yesterday+one week) so that I can compare how my weight has evolved in comparaison to the average of the last seven days (which is more significant that comparing one day to another day).
Yeah, sounds like you should be asking for help on the community forum instead. 😉
So TLDR an average of a value based on X days of history
Ok, just wanted to make sure I didn't miss something obvious, thank you!
There's always the existing statistics integration.
Well, not saying you can't get a useful response on discord, just that when asking strategy questions, it's a little harder to answer here. At least maybe try #integrations-archived ???
There's always the existing statistics integration.
I'm going to check this integration 🙂 ty
Well, not saying you can't get a useful response on discord, just that when asking strategy questions, it's a little harder to answer here. At least maybe try #integrations-archived ???
yeah obviously, I was just thinking maybe i'm missing a simple function somewhere, but I understand that my question is not just "easy" to answer if there's no obvious function available to get some stuff ^^
Nah, you just need to be clear about the problem you're trying to solve. You've done that now and it sounds like there's an existing solution for you. That integration will give min/max/mean/etc over a specified period.
Statistics would be perfect if I could just skip one day (today)... But i can start with that and think about a solution later to make it perfect! Thank you
Another option would be to use Influx/Grafana magic.
You just made me realize i could use SQL...
I'm having trouble using a template message with Google Cloud TTS, is it specifically not supported?
When I try, it returns Failed to call service tts/google_cloud_say. extra keys not allowed @ data['data_template']
Using the dev tools to call the service for testing:
entity_id: media_player.kitchen
data_template:
message: "Good morning, it's {{ now().strftime('%A, %B %-d, %Y') }}"
cache: false
What I've searched online says it should be working, and the documentation clearly points it out, the only difference being the service.
https://www.home-assistant.io/integrations/tts/#service-say
You can't use data template at dev tools > services
oh
That text field is the data: field
Right, silly me. Is there an alternative for testing?
All good. Unfortunately you'll have to make a script with what you want to test, or if you just want to see the output of the template, use dev tools > template
In 0.115 data_template: won't be required anymore, so theoretically templates should work at dev tools > services then
Yep, I verified its the correct output in the Template pane, but I want to make sure the TTS engine is using the correct verbage
ooo, now I'm looking forward to that release 🙂
Anyone here mess with lights much? I have a value that approximates the sun's elevation that goes between 100% and -100%. I want to define a color/brightness at solar noon, and another color/brightness at solar midnight. Then I want to create a color/brightness (i.e. the "accent color") that blends the two inputs based on the sun's elevation. Then I intend to set one or more physical lights (e.g. Philips Hue lights) to be this accent color (with an automation that updates it every minute or so). The end result is a bulb that smoothly transitions between two desired colors/settings throughout the day. I'm not sure if I should be using complex templating to define the solar noon and midnight colors/brightnesses, or light templates (the latter would be better I think). Should I be using a light template to hold the "accent color" and just set up automations to follow it? I'm getting started but I'd love input from anyone with ideas.
I'm also struggling to get a color picker to work for a light template.
@slim sage did you try what was suggested when you asked about this yesterday?
seems like you are trying to reinvent the wheel maybe
@violet oyster Thank you, I tried to not clutter the already cluttered question. I am familiar with Circadian Lighting, and use it throughout the house. Several rooms have LED strips and such intended to provide accent lighting. My ultimate goal is provide accent lighting to works alongside Circadian Lighting, and emulates its features but for a color or palette. This way, for example, the accent light LED strip that makes a wall look very good when teal can be a bright desaturated cool white in the middle of the day, but as evening rolls along, the light becomes a deep heavily saturated teal. Ideally, the actual color (e.g. teal) of the accent lights, and perhaps secondary lights, can be automated to go along with the outside light and weather conditions. So on darker days, the colors are allowed to be more saturated, but on bright sunny days I want it to feel bright inside.
oooooooh i finally understand what you are trying to do
My thought for the easiest first approach at the moment is to set two colors/brightnesses and assign them to solar noon and solar midnight, and then use the Circadian Lighting sensor value (which goes from 100% to -100% following the sun's elevation) to blend between them. I can use Node Red to do all of the automations, like updating the sensor value every 60 seconds, etc. I was hoping to set the solar noon/midnight colors using template lights and a color picker, but I can't get that to work because you cant use a color picker on a light template! So I'm still trying to figure out how to make the UI for this wife-friendly.
you dont want the accent lights to be circadian, you want them to simply react to the circadian changes and become a different color altogether
Yes! Or rather, to "follow" the circadian changes, so that the accent light's saturation and brightness track the circadian value that the rest of the lights are using.
cool idea
Basically, Circadian Lighting adjusts color temperature throughout the day. I want it to instead adjust saturation :).
i'm thinking...
what field do you usually use to set 'saturation' on the accent lights? rgb_color?
and about how many different settings would you need?
i mean you could just make several scenes with the lights at the color saturation you want and then use an automation to activate the scene when the lighting sensor value changes
the problem with trying to template this is that templates always return a string, which can't be used to set rgb_color in the light.turn_on service. so you'd need to pre-define the rgb_color you want somehow (using scenes or scripts) and then call that in an automation. unless I'm missing something (which is entirely possible)
you could template if you are using color_name instead of rgb_color but then you can't adjust the saturation like you want to
the user who responded gave an idea of how to maybe do it but i've never tried that. give it a look
Apologies, I was called away for a bit. I'll check out your link, thank you for the ideas and input!
let me know if you figure it out. its a cool idea
I have National Weather Service integration setup. In it, they have a daily forecast, one that is ongoing every hour and another that is at 18:00 hours. It also lists tomorrow at 06:00 hours and 18:00 hours. What I am trying to do is store the next day's 06:00 into a template sensor which I can grab in an attribute_template {{ state_attr('weather.kiad_daynight', 'forecast')[2]['detailed_description'] }} but when that no longer matches, it just blanks out the sensor attribute.
How can I get it to not blank out the template sensor and keep the correct value? If it was an automation, I'd use a condition so it wouldn't run
here's the sensor: https://paste.ubuntu.com/p/hFBDCzvN4Y/
@brisk temple add an else statement referencing the attribute, it will pull the past data. {{ state_attr('sensor.daily_forecast', 'forecast_6pm') }}
ah perfect, thanks!
hey there,
i'm wondering a thing, and need to find an answear on how to change a timestamp data recieved from a sensor. To human readable thing.
Oregon Update Time 1599063410
it's configurated on a .yaml file
i have found a lot of converter, but don't know howto use it . :\
{{ as_timestamp(states('sensor.your_sensor')).strftime("your format here") }} iirc
searching strftime in google should get you the formatting arguments. Should also be a link to it on the template docs
Thanks, this had to be cp un configuration.yaml ? Or in sensor.yaml ?
depends on what you are doing. What integration are you using?
it's an rflink sensor
Oregon
oregontemphygro_228c8_update_time:
sensor_type: timestamp
name: Oregon Update Time
It's for print the up time in lovelace card 🙂
if you want to play around with it without having to restart your instance a ton of times you can use
> Templates
devellopement tools, ok. I'm using Hass core in docker. And it's in french xD
it's the 4th ?
i have etat, Service Modèle Evenement
oh, it's modèle i think
should be the 3rd of 4
yeah i think is the 3rd ( they are line code )
i didn't know that was an test area 😄
thanks 🙂
np!
I'll be back , i'm gonna eat 🙂
@nimble marten Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
on a template sensor how do I make sure 0 is represented as 0 not None? I need to do math on that number in other places and now I end up with nan because I need a number.
What's the logic you are doing?
pass it to |int?
Okay, not sure if i am in the right spot. Also a warning I am like level 0 HA ninja at this point...
I am trying to make a Sim Garage Door Opener like I had in Samsung's DumbThings. I am trying to combine an sensor.garage.acceleration + binary_sensor.garage.contact and a switch.garage.
Id like to be able look at the garage Icon and see when open when its closed and show when its in motion. I have searched the web and have only found peeps that combine binary_sensor.garage.contact and a switch.garage
Roger, thought I would need to make a template for this to work. Again, it scares me how much I DONT understand....
you might, but first have a plan for getting the icon to do what you want, and then figure out what it needs to do that
Hmm is there a door template?
maybe if you have a position template defined
I think it could be done with a custom button card and icon templates. Or state customization
i am feeling really dumb regarding value templates
the formula for a new EPA wildfire AQI for the purpleair sensor is going to be 0.524 * purpleair_pm25 - 0.0852 * purpleair_humidity + 5.71. I'm trying to define a new sensor in my config yaml copying from some other examples, but its not working.
i feel like im writing a gopher phlog
hmm. this might be a good start. https://jinja.palletsprojects.com/en/master/templates/#math
do i even do this w/ a value template? the value of new sensor = existing sensor 1 * 3 + existing sensor 2
sensor is probably not even the right word to use
Your value template should look something like
"{{ (0.524 * states('sensor.purpleair_pm25') | float) - (0.0852 * states('sensor.purpleair_humidity') | float) + 5.71}}"
@honest mauve posted a code wall, it is moved here --> https://paste.ubuntu.com/p/dq4QbsStYJ/
Hello
I have a for on my switched
and I want to set a variable to count
"x" in the example
the x gets increased to 1 in the first loop
but then it's always 1... doesn't increase
seems like it always do 0 + 1 = 1
do you know why?
What I want to achieve: create an inline_keyboard of commands... with 2 commands per line (telegram bot)
Jinja doesn’t allow scoping outside loops
You’ll have to use namespace to make a counter
like?
{% set ns = namespace(x=0) %}
{% for i in range(5) %}
{% set ns.x = ns.x + 1 %}
{% endfor %}
I'll try
thanks
It works, thanks
How can I easily remove the last comma?
@mighty ledge
You can try if loop.last but it may not work. My personal recommendation is to look into using filters like select, select_attr, reject, and reject_attr instead of your current approach. I don’t have examples because I’m replying on mobile
Basically, filter your search down. Then map the attribute you care about, then join the list of strings with a comma
I'll try loop last
data_template:
title: '*Controlla lo stato delle luci...*'
message: Accendi o Spegni le luci
data:
inline_keyboard: >-```
The template doesn't seem to work properly
If I copy and paste the result of the code, from the developer, model page and I invoke the service
the inline_keyboard work properly
if I use it with the template, it's not formatted properly
It seems I'm not able to set a list of items "-" with the \n option
All inline keyboard are on one line....
@mighty ledge do you get what I mean?
Your value template should look something like
Thanks @buoyant pine i was confused (obviously) about whether states() applied to numerical values or only like on/off. Also didn't expect to have to declare the variable type
@honest mauve Templates only return a single string. inline_keyboard requires a list of strings. It will be impossible to do what you want it to do dynamically because of that reason.
You should use a python script instead to get the job done.
doesn't matter, inline_keyboard requires a list. Templates only return single strings.
I'm not sure why you don't want to use a python script, the code would be almost the same.
I never used one
I need to understand how to integrate it
inside automations.yaml
😦
it acts as a service
so you just call the script as a service. All of this is described in the python_script integration
I can do it within script.yaml?
No, it’s a python script. Just check out the docs
I wlll
platform: event
event_type: telegram_command
event_data:
command: /controlloluci
chat_id: 808687121```
About this... can I make the "command" a template, inside automation.yaml?
@mighty ledge
I also saw the syntax of Python scripts... it's not just a copy and paste
I don't get how to transform the loop template into a python script
would you help me?
It’s just Python at that point
I'm trying to get the value of my sensor to round to 2 digits, but i'm struggling with the syntax. Referencing the example https://community.home-assistant.io/t/rounding-of-sensor-values/31452/11
value_template: "{{ (0.524 * states('sensor.purpleair_pm25') | float) - (0.0852 * states('sensor.purpleair_humidity') | float) + 5.71} | round(2)}"
i thought i could round the whole thing outside of the braces. do i need to round each value individually after | float? like | float | round(2)
Your curly braces are in the wrong place
You need to surround the whole expression that you want to round and then filter with ‘|round(2)’
Hard to tell with the curly braces messed up, but it looks like you’re just rounding the last part
oh hey the web ui file editor shows you which braces go together. thats handy.
i was using notepad.
Gack. Yeah, use a real editor 🙂
well i have about 14 tabs open in notepad++ and i thought oh this is simple i'll just copy/paste into notepad
oh, Notepad++ is better than "notepad"
anyway, did you get what I was saying about grouping and then rounding?
yeah i thought i had done that honestly by putting it right inside the outermost brace. but do you group them with regular parens?
yep, normal pemdas but | are after ()
I think you want this:
"{{ ((0.524 * states('sensor.purpleair_pm25')) - (0.0852 * states('sensor.purpleair_humidity')) + 5.71) | round(2) }}"
this is what im trying, restarting now. value_template: "{{ ((0.524 * states('sensor.purpleair_pm25') | float) - (0.0852 * states('sensor.purpleair_humidity') | float) + 5.71) | round(2)}}"
optimization kills 🙂
hey it works
now i need to add a state for when it first starts up and there are no values for sensor.purpleair_pm25 so it doesnt report just 5.71
state isnt the right word
I'm using value_template: '{{ trigger.to_state.state | int > trigger.from_state.state | int }}' as condition to notify me. But when I try to use the value as title in the notify service it just says 'trigger' is undefined. title: '{{ trigger.to_state.state | int - trigger.from_state.state | int }} moneys.' What am I doing wrong?
Or you're not using an automation/trying to manually run it without a trigger
you're probably not using
data_template:
or, you're just executing it from the UI
but probably the former
because you're clearly not using data_template:
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Thanks. That did it.
Hey!
How could i possible take this Fri Sep 04 06:45:00 GMT+02:00 2020 and change that to a time like 06:45:00 ?
I want a hour:minute state from the next alarm in android companion to an template sensor
looks like a timestamp already. whats it coming from?
Question; im using the DSMR power meter which publishes the timestamp over MQTT. The thing is, my power meters time is 41sec's early, and because it is out of my control, I want to try to correct it by substracting 41 seconds from the published timestamp. The device class is timestamp. I think I'm nearly there.. sample incoming timestamp: 2020-09-03T23:06:24+02:00
value_template: "{{ strptime(value) - strptime(41, '%S') }}"
hey, @vagrant monolith I just happened to be messing with something like that myself, and this is what i came up with:
value_template: "{{as_timestamp(states('sensor.sm_g930p_next_alarm')) | timestamp_custom('%X') }}"
or
value_template: "{{as_timestamp(states('sensor.sm_g930p_next_alarm')) | timestamp_custom('%H:%M:%S') }}"
just replace the sensor with your phone and you should be all set
^^^ Why is this not in the docs 🙂 Spent one hour figuring out how to format dates
The doc claims that strptime returns a datetime object, but it returns a string. https://www.home-assistant.io/docs/configuration/templating/
Noone clicked the edit button to say that
@keen crater wrap the strptime in a as_timestamp. The subtract 41. Wrap that in quotes an convert it to timestamp_local
@soft coral it does return a timestamp, if it’s returning a string you’re using the function wrong
strptime string parse time, input a string, get a datetime object
strftime string format time, input a datetime object, get a string in your format
Unless strptime fails to convert based on a bad format. when it fails it returns the string that was input
True, that was a happy path description
what's happy path?
Meaning that's what happens when you do everything right
Ah ok, i started googling happy path and I found something similar to nodered
definitely through me in a confused path
Lol sorry 😛
Unless strptime fails to convert based on a bad format. when it fails it returns the string that was input
@mighty ledge Here it is! That was very confusing, honestly.
platform: event
event_type: telegram_command
event_data:
command: /controlloluci
chat_id: 808687121```
Hi all, is there a way I can make the command a template?
@mighty ledge
Generally frowned on to randomly tag people
^^^ Why is this not in the docs 🙂 Spent one hour figuring out how to format dates
The doc claims thatstrptimereturns a datetime object, but it returns a string. https://www.home-assistant.io/docs/configuration/templating/
@soft coral I had a "oh, duh" it dawned on me moment - strptime is both a python and php function, and since home assistant is lousy with .py files, i realized the yaml file is probably being parsed by python. so you can use python's date formatting. https://www.w3schools.com/python/python_datetime.asp
(also, thank you w3schools! how many times have i looked programming/web stuff up and you've been like "I've got you, bro")
hi, when I've added new sensor template file (not in configuration.yaml), and every time when I change it do I need to restart HA , or is there any better way ?
I know, that there is service for reload, but it looks like only for configuration.yaml
and there are other services for reload automations, scripts, etc, but none of them apply my changes in sensor template yaml file
The only way I've found is to restart HA, sadly 😦
even if it's in configuration.yaml
(I'd gladly be proven wrong on this though)
I think, that in future releases it will be implemented, I found this: https://github.com/home-assistant/core/pull/39527
and restart from GUI does not work 😦 [supervisor.utils] Can't execute restart while a task is in progress
Is it possible to use a template for the command event_data of an event?
Like an event_data_template, with a variable command text
to get for example all the commands that ends with "on" or "off"
Thanks petro
you guessed right btw
how can I make a loop on switches inside a python script?
I don't think it's copy and paste of the code, from automations, like you said
right'
?
it's close, have you looked into python's syntax for a for loop?
is it better in private, maybe you can dedicate me 2 mins to give me the right hints
and I will proceed than autonomously
it's fine here
Ok thanks
this is my original automation snippet
it works
but all commands are on one line
so what shall I do first?
well, how much do you know about python?
a bit... I'm a coder
but not so deep into python and the way python interacts with HA objects
if you can drive me step by step
I would really appreciate it
Well first you should study the python API
You're trying to replicate {%- for state in states.switch -%}
Yes that one...
in python theres multiple ways you can do this
you can either request switch entity_id's then iterate the state machine and get each state. Or you can get all the state objects and only act on the switch domain ones.
this is all done through the hass.states object
I'm really lost
I would need some more guidance
do you have time/willing to deep dive it?
If you got the entity_id's... for entity_id in hass.states.entity_ids('switch'), you'd then need to get the state object state = hass.states.get(entity_id)
I just need to put those 2 lines in the code?
that would get you what's eqivalent to {% for state in states.switch %}
but make sure it follows python rules. Like spacing & punctuation
Do you mind creating a sort of prototype for me that I can test and correct?
Why don't you try it first
I dunno how to... 😦
Did you create the hello world python script?
So you can learn the process for creating the script. It's where I linked
I'm doing it
action:
service: python_script.ControlloLuci
data:
name: you
Like this, in automation?
even if file has it?
yep
I'll raise the log and test
Then, go line by line in your jinja and convert each line to python
The difference is that you'll be building up a list, then calling a service at the end
I will need help here 🙂
so you want to create a list in your python script and append entity_id's to it
mylist = []
...
mylist.append(entity_id)
or if it's a bunch of strings that you concatenate, then that's what you'll be appending to the list.
How can I then invoke Telegram bot
with list of inline_keyboard?
I do the loop, I fill the list
then I loop on the list and create the inline_keyboard
but how to invoke it with several lines (like a list of keyboard commands) ?
hass.services.call There's an example in the docs I listed
hass.services.call("light", "turn_on", service_data, False)
yes I see it
but I mean, how can I make it a list of inline keyboards?
data = {
'title': '*Controlla lo stato delle luci...*',
'message': 'Accendi o Spegni le luci',
'data': {
'inline_keyboard': mylist,
}
}
hass.services.call('notify', 'allarme', data)
you just need to populate mylist
Cool
let me try it... I'm about to test first the hello world
I got
2020-09-04 12:18:42 DEBUG (MainThread) [homeassistant.core] Bus:Handling <Event you[L]: wow=from a Python script!>
yep, and in your logs under info you should have "Hello world'
or
Hello you
whatever you used in name: ... for the service call
Yes
2020-09-04 12:20:25 INFO (SyncWorker_5) [homeassistant.components.python_script.controlloluci.py] Hello Stefano
Great, good start ! 🙂
Now... shall I restart HA each time I change the python script?
now start creating the real script that you want to create
For now you have to. I believe in 0.115 you can just reload the python_scripts
Now that I think about it, you should only have to restart when you add a script. Not for changes. We’ll see
I tested with this...
name = data.get("name", "world")
logger.info("Hello %s", name)
hass.bus.fire(name, {"wow": "from a Python script!"})
for entity_id in hass.states.entity_ids('switch')
state = hass.states.get(entity_id)
logger.info("Switch %s %s", entity_id, state)
And I didn't even receive the "Hello Stefano"
I'm trying to restart HA now...
Because you’re missing vital python punctuation
This is why I suggested you learn some beginner level python
Like making a for loop
Making a list
Making a dict
You know code based on what you created in jinja without much help. So it shouldn’t be hard for you. You just gotta learn the nuances and you’ll be flying in no time
I'll check
Invalid syntax
let me fix it
I added the ":" and it works
not even needed to restart
let me continue with it then
Yep! You got it
from state I can read:
The state objects are the same shape as jinja
<state switch.bagnogrande=off; tuya_device_id=XXXX, friendly_name=Bagno Grande @ 2020-09-04T12:32:07.507551+02:00>
it will be state.state?
Yep
😄
And state.name
I'm fast learning
It works
2020-09-04 12:40:18 INFO (SyncWorker_40) [homeassistant.components.python_script.controlloluci.py] Switch Bagno Grande off
2020-09-04 12:40:18 INFO (SyncWorker_40) [homeassistant.components.python_script.controlloluci.py] Switch Scala unavailable
2020-09-04 12:40:18 INFO (SyncWorker_40) [homeassistant.components.python_script.controlloluci.py] Switch Bagno Piccolo off
Nice
I'm make the data for the inline keyboard now
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 468: character maps to <undefined>
What does it mean?
You won’t be able to use those special characters unless you change the encoding of the file
@honest mauve posted a code wall, it is moved here --> https://paste.ubuntu.com/p/F7WtdpXJwk/
Yeah
What shall I do?
Well, there should be an ascii representation of those emojis that your notification service understands
No like for discord, :man_shrugging: will display 🤷♂️
those are all ascii characters
NameError: name 'replace' is not defined
stato = state.name + ' ('+ stato + '):/' + state.name.replace(' ','') + state.state.replace ('off','On').replace ('on','Off').replace ('unavailable','Unavailable')
that should work
but you're getting a name error
that means you're using replace somewhere else
you'd be getting an attribute error if it was broken in that line.
AttributeError
Nice. Aight have fun scripting I have to get ready for vacation
If you need more help, make a forum post
Thanks for your time
Np
Shall I add the "-" before each inline keyboard?
No, each time you want to add the -, append it to the list
Remember, your making a list. Not a long string
Again, a beginner python tutorial would work wonders
True
😄
It works!!!
I'm able to generate the buttons
thanks
I need to fix only the character set
issue
and I'm done
@mighty ledge you've been so helpful
thanks
for entity_id in hass.states.entity_ids('switch'):
Is there a way to sort it?
@mighty ledge
found it: sorted(hass.states.entity_ids('switch'))
looks like a timestamp already. whats it coming from?
@dreamy sinew yea but it's like 04:45 and my alarm is 06:45 which is weird
Unix time. Convert it to local
Can a template be cropped to fit one line in markdown card?
what do you mean?
Can i get some help with this please.
I have an automation runniing based on a calendar event, and it had the following condition in it value_template: "{{is_state_attr('calendar.calendar_name', 'message', 'vacation') }}", i beleive this means that if the calendar event matches the name vaction in my calendar then run the action. how do i get it to not trigger the action if vacation is not in the calendar event.
Example if todays date does not match the calendar event date/time or name then action not fire if it does match then the action fires
Hehe. I have a list of strings at variable lengths in a markdown card. Can I make it trunc at card width?
gonna need some examples @distant plover
@nimble marten you too
.share what you have
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
I've tried using substring as you can see but various devices have various widths of the card
@dreamy sinew heres my automation
alias: Calendar lights
description: Turn on Christmas lights
trigger:
- entity_id: calendar.christmas_lights
platform: state
to: 'on'
condition: - condition: template
value_template: {{not is_state_attr('calendar.christmas_lights', 'message',
'Christmas Lights') }}
action: - scene: scene.calendar_lights
mode: single
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
To start, you need to quote your templates
when i hit execute my light should come on which it does, i want to add another conditon that also checks todays date against what is in the calendar if it does not match then dont turn on
@inner mesa like this "{{not is_state_attr('calendar.christmas_lights', 'message',
'Christmas Lights') }}"
Yes
ok done
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
@inner mesa ok rob to test if the condition works, i changed where it says christmas lights to a random name and then pressed execute, in theory the action should not have fired but it did.
Please share the whole thing
doesn't the default trigger skip conditions?
alias: Calendar lights
description: Turn on Christmas lights
trigger:
- entity_id: calendar.christmas_lights
platform: state
to: 'on'
condition: - condition: template
value_template: "{{not is_state_attr('calendar.christmas_lights', 'message',
'tom') }}"
action: - scene: scene.calendar_lights
mode: single
Dear god. For the third time:
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
sorry
formatting is important in yaml. Without using a code block or a sharing site the formatting gets mangled and that hides potential issues
And a willingness to read helpful bot messages
help us help you, use a sharing site for code
@inner mesa @dreamy sinew i followed the HA google calendar guide is there something I missed
@inner mesa @dreamy sinew Should i try changing the trigger to the condition then trigger to the action, still all new to this
no, I think it's okay. As phnx said, I believe that manually triggering an automation from the UI skips the conditions
it's equivalent to just running the action
@inner mesa oh ok how would i test it then without executing it
no need to keep tagging
add a different trigger that you can control, like an input_boolean
like a toggle switch
or make the calendar entry change state. I don't know anything about Google calendar
sure. or just an input_boolean that you control manually from
-> States
or use
-> Services, choose automation.trigger and set the skip_condition parameter to false
skip_condition Whether or not the condition will be skipped (defaults to true). true
Can I make a line on the markdown card to trunc to the width of the card instead of continuing on a new line? Here is the template: https://pastebin.com/AVZdhn6G Maybe it's more of a #frontend-archived question?
yeah, I think that's a #frontend-archived question
will this work as a trigger?
- platform: template entity_id: {{ is_state_attr('lock.garage_door_locked', 'notification', 'Keypad Lock') }}
or should I be using a {% if
no, you want value_template, as described in the docs: https://www.home-assistant.io/docs/automation/trigger/
and you don't need the if
thanks, I knew I was forgetting something
- alias: Garage Door Lock Keypad initial_state: true trigger: - platform: template value_template: {{ is_state_attr('lock.garage_door_locked', 'notification', 'Keypad Lock') }} condition: - condition: state entity_id: 'group.users' state: 'home' action: - service: lock.unlock entity_id: !secret BACKDOORLOCK - service: switch.turn_off entity_id: !secret GARAGELIGHTS
wrong copypasta
reward for locking the garage is the backdoor gets unlocked and the lights are turned off
looks like itll work
~share in the future
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
gotta quote your template
true
and maybe not quote your entity_id, but that may not matter
looks fine to me
just updated from 0.100.3 docker the other day and just cleaning up all the things. its been pretty fun
lol thats a long time to go without updating. i don't envy you
stopped letting watchtower auto update the container a while back because breaking changes were not ideal at the time
yeah maybe like 9 months
honestly there wasn't much to fix, just a few minor things really
zwave was the main issue for not updating and then updating
ah
just trying to do some clean up and improve some automation handling while I've been digging around, been a while since I've messed with templates... really need to re-read the new automation docs. sounds great but I don't think I still quite understand all the new options
@inner mesa the entity ID does need to be quoted
like this: entity_id: 'group.users' ?
I never do that
condition:
- condition: state
entity_id: input_boolean.heat_water
state: 'on'
me either, i dont know why i did it on the first paste
yeah i only single quote state
but it's a string, so doubt it matters
and single or double quote value_template
doesn't matter - just don't use the same ones inside and out
right
ah, yeah. I was talking about the condition
which had an unnecesarily quoted entity_id
Yeah, that doesn't need to be. Won't hurt though
Is there a better way to keep track of wheter a time is within a range than this.
binary_sensor:
- platform: template
sensors:
daytime:
value_template: "{{ 'on' if ('08:00' < now().strftime('%H:%M') < '22:00') else 'off' }}"
friendly_name: Is Daytime
Is the binary_sensor the correct form of entity and does the template make sense?
If all you want is a binary display, then that is a good choice
Do you always want it to be between those too times?
Also, it is very likely that that sensor will never update. You need to use an entity for that
@soft coral it does return a timestamp, if it’s returning a string you’re using the function wrong
@mighty ledge I tried this but did not work.value_template: "{{ as_timestamp(strptime(value)) - timestamp_local('41') }}"But maybe I misunderstood you.
@keen crater (as_timestamp(strptime(value)) - 41) | timestamp_local
@crisp marten This will not work. now() is evaluated at the yaml parse time, so this sensor is telling you you restarted your HA during daytime or not. You need to compare your time with https://www.home-assistant.io/integrations/time_date/
@crisp marten This will not work. now() is evaluated at the yaml parse time, so this sensor is telling you you restarted your HA during daytime or not. You need to compare your time with https://www.home-assistant.io/integrations/time_date/
@soft coral Thankyou now it works perfect. I am a bit curious how Jinja is able to compare the times without me typing them as time. But it seems to work.
Is it possible to set the min/max value of an input_number to a template value?
@tribal rock nope
hmm fair enough, I just found a little tidbit on the forums too.
I've never looked at custom components, but this seems like the time to look into it
Hi All, Can someone have a look at this for me, I am always getting a returned value of 0.0. I have spent a fair bit of time on this one but just cant seem to work it out. Thanks 🙂
https://paste.ubuntu.com/p/hkPk9MhPP3/ https://imgur.com/a/eCDDx0c
@buoyant pine Super late response, but for my auto-climate control automation (ACC), I'm using input_number to set the high and low temperatures for sleep and wake cycles. I could monitor inputs manually, but it'd be nice to programatically make it a rule that the max value for the low temperature should not exceed the state value for the high temperature for example.
I get 'Template sensor 'network_devices' has no entity ids configured to track nor were we able to extract the entities to track from the value template(s). This entity will only be able to be updated manually
Verbindung getrennt. Verbinde erneut...'
with
unit_of_measurement: "Device"
value_template: "{{ states.device_tracker | selectattr('state', 'eq', 'home') | selectattr('attributes.scanner', 'eq', 'LuciDeviceScanner') | list | count }}" ```
But the sensor works fine, the error just appears on boot.
can I do something about that?
You could have added an ‘entity_id’, but that’s going away. See here: https://community.home-assistant.io/t/heads-up-upcoming-breaking-change-in-the-template-integration/223715
@coarse tiger
so I‘m futureproof with this? 😄
i cleared my log today of misc issues and stuff... this is the last message remaining
Seems so. I have a few warnings like that and now I need to tackle them
Wait, @inner mesa I didn't know that's being removed. I hope my sensors still work if I remove the entity_id variable
the workarounds are easy
If I'm using a template for the is_state() part, will it still update accordingly?
does it match the description of the problem?
For example:
{% set temp_lim_id = "input_number.acc_%s" % states("sensor.time_cycle") + "_%s_limit" %}
{% set temp_lim_high = states(temp_lim_id % "high") | float %}
{% set temp_lim_low = states(temp_lim_id % "low") | float %}
in mstone's example, there's no entity ID, so it's exactly the problem
I would think that just having this in there is enough:
states("sensor.time_cycle")
I think if you're not getting a warning in the log, you're okay
Fair, but I also want it to reevaluate if the other entities' states update. E.g.
input_number.acc_wake_high_limit and
input_number.acc_wake_low_limit when is_state("sensor.time_cycle", "wake")
And vice versa for "sleep"
and you have a list of entity_ids now?
you may just need to give it a hint based on the description in the thread for the ones you care about
I do, I added them just for insurance when I created the automation, but I'm going to run a test without them
@keen crater (as_timestamp(strptime(value)) - 41) | timestamp_local
@mighty ledge I can't get it to work 😦 Is it also possible to get the "received timestamp" from the MQTT message? Not sure HA records that. I figured that maybe a better solution because it uses the Home Assistant server time.
I don't think it'll figure the other ones out without help
you could try pulling the sensor.time_cycle out and see if you get a warning
Hmm, maybe it should be okay since I have an entity in the template that updates every minute
your call
Do you mind taking a look at the full value_template for the sensor?
https://hastebin.com/azamelezan.cs
are you having a specific issue with it?
You mentioned the entity_id config variable is being removed from template sensors, I'm about to test it now, but I'm just unsure if it will work the same way without some refactoring
it's not really a big deal - it only affects when the template sensor is re-evaluated, and it's easy to work around
if you were already using entity_id with a list of entities to ensure that it's updated regularly based on state changes, then just add them into the template
that same list would still apply. if you weren't doing that before and were happy with when it's automatically evaluated, you have nothing to worry about
@mighty ledge I can't get it to work 😦 Is it also possible to get the "received timestamp" from the MQTT message? Not sure HA records that. I figured that maybe a better solution because it uses the Home Assistant server time.
@keen crater whats the format of the time value
@keen crater whats the format of the time value
@mighty ledge 2020-09-06T15:36:38+02:00
reading lewx template I ask me if I you can set a variable in jinja.
I got an automation to dim the light if it is turned on.
I have to define the entety 3 times and wondering me if I can get around this.
{% set light = "states('light.whatever')" %}
anyone in here on beta?
yep
i tried to shorten a template but can't make it work.. it's a condition in an action of an automation
- condition: template
value_template: "{{ now().strftime('%M') < '58' and now().strftime('%M') > '02' and (states('sensor.sonarr_queue') == '0') }}"
that works
- condition: "{{ now().strftime('%M') < '58' and now().strftime('%M') > '02' and (states('sensor.sonarr_queue') == '0') }}"
doesn't???
try conditions:
Is that something that is supposed to be available in the beta? Because it's definitely wrong for current
yes, it's new
Gotcha
tried conditions: as well
what does the rest of it look like?
the whole automation?
that is the only condition.. the whole thing
action:
- service: input_boolean.turn_off
entity_id: input_boolean.retrigger
- delay: '00:00:01'
- service: input_boolean.turn_on
entity_id: input_boolean.retrigger
- condition: template
value_template: "{{ now().strftime('%M') < '58' and now().strftime('%M') > '02' and (states('sensor.sonarr_queue') == '0') }}"
- service: input_boolean.turn_off
entity_id: input_boolean.retrigger
conditions don't start with "-"
yeah, that's not how that should be written
oh, nevermind
sorry, was confused
um... ok... well it's valid and working like that..
no idea
hmm... it's not really a beta issue... I might try there though
if the "new way" doesn't work and the old way does, then it does seem like a beta issue
they don't have an example in the docs that looks just like that
What am I doing wrong with this sensor template? I'm trying to have a combined data rate in Mbps converted from kib/s
`sensor:
- platform: template
sensors:
rt_ac68u_7578_mib_s_total:
unique_id: rt_ac68u_7578_mib_s_total
friendly_name: RT-AC68U-7578 Mb/s total
unit_of_measurement: 'Mbps'
value_template: "{{ (states('sensor.rt_ac68u_7578_kib_s_sent') + states('sensor.rt_ac68u_7578_kib_s_received')) | float * 0.008192 }}"`
So just float() both of them?
|float them
Awesome, got it working now. Thanks!
hi all ! i try to begin with templates, i write something and its not working :
{% if is_state("sensor.thermohygro3_temperature", " > 15 " ) -%}
its over 15°
{%- endif %}
It's exact match
"{{ (states('sensor.thermohygro3_temperature') | float) > 15 }}"
okay, very nice thnak you !!
Hi All, Can someone have a look at this for me, I am always getting a returned value of 0.0. I have spent a fair bit of time on this one but just cant seem to work it out. Thanks 🙂
https://paste.ubuntu.com/p/hkPk9MhPP3/ https://imgur.com/a/eCDDx0c
now i try to use this in an action , i don't know if its in the right place or what, and i don't know if i can increment a number directly like this 😗
action:
- service: input_number.increment
data_template: >
{% if (states('sensor.thermohygro3_temperature') | float) > 15 %}
input_number.servo_control
{%- endif %}
@tender prawn from what i've read, it was broken in the beta. A fix is on the way. All you really need is just the condition:
- "{{ x == y }}"
@brisk sonnet
{% set rainfall = state_attr('sensor.bom_perth_possible_rainfall_4', 'possible_rainfall') | replace('mm', '') %}
{% if 'to' in rainfall %}
{% set values = rainfall.split('to') | map('float') %}
{{ values | sum / values | length }}
{% else %}
{{ rainfall | float }}
{% endif %}
@dusky bane you can't template the data_template field. Only field's inside data_template.
- service: input_number.increment
data_template:
entity_id: >
{% if (states('sensor.thermohygro3_temperature') | float) > 15 %}
input_number.servo_control
{%- endif %}
Also, you'll need a backup plan because you can't call a service without a template. FYI you can place conditions in automations too. So instead of going this route, you can just place a condition prior to the service call and it will cancel all remaining actions.
Thanks @mighty ledge would you be able to explain that to me please ? Is that splitting the two values and then adding them together ?
I have an automation on my robot vacuum with a trigger from 'returning' to 'error' but I need a condition when the attribute 'error' == 'Charging fault'. Should I use templating for that? How?
@brisk sonnet the state appears to be "2 to 6 mm". So with that in mind, I'm splitting on the word 'to' and averaging the results.
And if they just give a single value, we default to that. I could see this not working if states like '< 1' occur. You'll have to add each of those cases as they come up.
thank you @mighty ledge !! i will try to understand your advice and write something
@distant plover that's a very simple template, what have you tried?
Ok got it. Thanks 🙂
Well i have been trying different routes to Adjust the value of a slider with the variations of a sensor,
but i don't find a concise template to do it other than telling at 20° move the slider 10 at 21° move the slider 20 etc...
Maybe someone can indicate me a way to tell the slider to move proportionaly according to the sensor value ?
petro, well... {{ state_attr('vacuum.xiaomi_vacuum_cleaner', 'error') }} seems to work but I'm not sure how to use that in automation. I'm a bit confused on that part when comparing to other stuff I'm using in automations. For instance I tried {{ trigger.to_state.error == 'Charging fault }} but I don't think that works.
But perhaps I shouldn't look at the trigger but use {{ states.xiaomi_vacuum_cleaner.attributes.error == 'Charging fault' }} instead?
Can a condition simply be {{ state_attr('vacuum.xiaomi_vacuum_cleaner', 'error') == 'Charging fault' }} ?
if you want to dynamically pull it from the trigger {{ trigger.to_state.attributes.error == 'Charging fault' }}
What is the benefit from pulling it from the trigger?
in 115 you can also just trigger off attributes
if you don't pull it from the trigger, there's a chance that it's not the same state when you check in the condition
Ah. Clever.
@dusky bane if the values are linear, make a chart in excel and get the trendline equation. Then plug the information in properly in a template step. I can help you.
@dusky bane the equation from excel will be y=ax+b. So in a template it would be {{ a*x + b }} to get Y.
it will probably look something like this {{ 10 * states('sensor.xxx') | float + 9 }}
yep
very nice
well i put my data in excel, and watch a tutorial about trendline equation, but i really don't know how to get to it...
ok i have the equation thank you petro
and i used it like you said and it works
i love you @mighty ledge
np
and what condition can i use to make this action work only when the sensor value move for at least 1 point
because know it's acting with every decimal
You'd need to check the current value against the new value. How are you using the template?
and even then, you'd only get the previous value, nothing historical
so if it ticked up 10 times of 0.1 you'd only ever see the last 0.1 change
I have set up a template sensor which adds three temp sensors together and splits in 3 to get the mean. However, some entities may go to unavailable state and that messes up the measurement. Is there any way I can know which amount to split by, based on number of available sensors?
Current code looks like this:
((
(states('sensor.temperature_stue_1')|float) +
(states('sensor.temperature_stue_2')|float) +
(states('sensor.temperature_stue_3')|float)
)/3)
| round(1) }}```
i have something similar
downstairs_avg_temp:
friendly_name: "Downstairs Average Temp"
device_class: 'temperature'
unit_of_measurement: '°F'
value_template: >-
{% set sensors = [
states('sensor.living_room_temperature')|float,
states('sensor.office_temperature')|float,
states('sensor.thermostat_temperature')|float
]
%}
{{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}```
when you |float a string it goes to 0.0
i have 3 copies of this with different sensors lists
Neat, @dreamy sinew . I just discovered the Min/Max sensor platform, which offers a mean type and seems to do the trick as well. Any reason to choose template over Min/Max sensor platform?
none that i can see
Ok. Thanks for providing the solution, much appreciated. Think I'll use that, then I can drop it in place of my existing variable.
if you're doing a simple average min/max seems like it'll work well since it'll handle unknowns and stuff automagically. If you wanted to add any extra logic though, that's where the template comes in to play
Makes sense. I'll try this for a while. Can't hurt to learn some more templating anyway! I have only had issues with sensors going to unavailable, which is now handled.
@mighty ledge this is how i use the template
action:
- service: input_number.set_value
data_template:
value: "{{ 10 * states('sensor.thermohygro3_temperature') | float - 250 }}"
entity_id: input_number.servo_control
String math
States are strings. Need to convert to an number
value: "{{ 10 * (states('sensor.thermohygro3_temperature') | float) - 250 }}"
Should do it
i swear to god the last time i looked at this window yesterday it was robc explaining string math
phnx is the string math dude usually
maybe it was him now that you say that
But we can take turns
@inner mesa that doesn't matter, order of operation applies filters first. I asked him to show me how he was using it so I could help him only adjust when the change in states('sensor.thermohygro3_temperature') was greater than 1.
@dusky bane can you show me the whole automation, sorry for not being clear
Oh, alright. Good to know
yeah, it's the same as float(states('x.y'))
yes
Sorry for jumping in the middle of a discussion in progress 🙂
-
alias: "Slider Movement Template"
trigger:
platform: state
entity_id: sensor.thermohygro3_temperatureaction:
- service: input_number.set_value
data_template:
value: "{{ 10 * states('sensor.thermohygro3_temperature') | float - 250 }}"
entity_id: input_number.servo_control
@dusky bane this condition will make the automation only fire when the delta is greater than 1 (or -1)
condition:
- condition: template
value_template: >
{% set before = trigger.from_state.state | float %}
{% set after = trigger.to_state.state | float %}
{% set delta = after - before %}
{{ abs(delta) > 1 }}
thank you for the gift
i have a problem to use it with a switch i was putting as condition also to turn on/off the automation
condition:
condition: and
conditions:
- condition: template
value_template: >
{% set before = trigger.from_state.state | float %}
{% set after = trigger.to_state.state | float %}
{% set delta = after - before %}
{{ abs(delta) > 1 }}
#a switch to turn on/off the automation#
- condition: state
entity_id: input_boolean.automation_extracte
state: 'on'
it gives an error :bad indentation of a sequence entry at line 22, column 14:
value_template: >
your formatting is wrong. or could be. we can't tell because you didn't use code formatting or a code sharing site
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
or at the very least:
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:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
if you're under 15 lines (you currently are)
condition:
condition: and
conditions:
- condition: template
value_template: >
{% set before = trigger.from_state.state | float %}
{% set after = trigger.to_state.state | float %}
{% set delta = after - before %}
{{ abs(delta) > 1 }}
#a switch to turn on/off the automation#
- condition: state
entity_id: input_boolean.automation_extracte
state: 'on'
thank you @dreamy sinew
ok, then yes. your formatting is incorrect. the v for value needs to be lined up with the c for condition above it
oh ok it was dumb i already tried moving stuff around but not correctly it seems thank you for your help
i'm trying to build a template sensor for a MQTT Sensor, its a door sensor an i try to strip out the "unavailable" message, so that i always just get 'open' or 'close' is there some kind of previous state i can use for that?
entity_id: switch.door_sensor1
icon_template: mdi:door-open
value_template: >
{%if is_state('switch.door_sensor1', 'on') %}
'on'
{%elif is_state('switch.door_sensor1', 'off') %}
'off'
{% endif %}```
should really rename this channel #phnxplates
Lol why?
everytime i peak in here I see a phnx wall of code lol
Lol
Hi, need some help here with a template that is not rendering, it seems that because the sensor starts with 1, something breaks. When I try the template "{{ (states.sensor.1h_pool_kwh_difference.state | float) | round(2) }}" it gives me this error
Error rendering template: TemplateSyntaxError: expected token ')', got 'h_pool_kwh_difference'
Seems to not be able to render sensor.1h.... doesn't see the 1
Hi @mighty ledge I'm still having the same issue with a result of 0.0 Did I miss something ? https://paste.ubuntu.com/p/pvdzhYGqPF/ https://imgur.com/a/bFEaBGV
Good Day All, Anyone know how i can make a template that can calulate estimate time remaining on my investor battery?? I have sensors for capicty voltage and amps per hour.
@brisk sonnet Can you post a screenshot of the state in the dev tool -> states page? Also, please make sure the attributes are present in the screenshot.
@rare sage do you have the equation already or do you need to generate the equation, because those are 2 very different questions and require very different skillsets.
@mighty ledge here you go https://imgur.com/DFnIdFw
Oh ok, it's the main state, not an attribute. try this:
{% set rainfall = states('sensor.bom_perth_possible_rainfall_0') %}
{% if ' to ' in rainfall %}
{% set values = rainfall.split(' to ') | map('float') %}
{{ values | sum / values | length }}
{% else %}
{{ rainfall | float }}
{% endif %}
i get an error Unknown error rendering template
using sensor.bom_perth_possible_rainfall_1
sensor.bom_perth_possible_rainfall_0 returns a result of 0.0
this line:
{% set values = rainfall.split(' to ') | map('float') %}
needs to be
{% set values = rainfall.split(' to ') | map('float')|list %}
Bingo! That did the trick 🙂 Thanks @dreamy sinew @mighty ledge
Ah oh yeah, forgot to cast the generator to a list
@lusty vine try
"{{ states('sensor.1h_pool_kwh_difference') | float | round(2) }}"
@buoyant pine thank you, will give it a try
better method anyway. to do it how you have it you'd need to use brackets: https://www.home-assistant.io/docs/configuration/templating/#entity_id-that-begins-with-a-number
More of an #integrations-archived question. I’ll bet the container doesn’t have the ‘ha’ cli command installed
Hi, how to change state attribute from template ? I've tried something like this, but I don't know correct syntax:
{{ state_attr('sensor.sms_parsed', 'number') = '999' }}
you can't. what are you trying to accomplish?
so I saw somewhere that how template sensors are checked on startup is going to be changed again. Does anyone have a link to the post talking about that or a TLDR for what should be added to template sensors soon/now so they dont break in the future
nvm found it I was talking about this https://community.home-assistant.io/t/heads-up-upcoming-breaking-change-in-the-template-integration/223715
can some one tell me what is wrong with this one ?
platform: command_line name: "Latest Version" command: echo "$(ha core info | grep 'version_latest: ' | cut -f2- -d:)"
the command it self works in cli but when i try to add it as a sensor i get following error:
Error loading /config/configuration.yaml: mapping values are not allowed here in "/config/components/packages/../sensors/latest_version.yaml", line 3, column 53
.share the contents of that package
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
and in the logs its says the following
while parsing a block mapping in "/config/components/packages/../sensors/latest_version.yaml", line 1, column 1 expected <block end>, but found '<scalar>' in "/config/components/packages/../sensors/latest_version.yaml", line 3, column 17 mapping values are not allowed here in "/config/components/packages/../sensors/latest_version.yaml", line 3, column 62 mapping values are not allowed here in "/config/components/packages/../sensors/latest_version.yaml", line 3, column 53
Also there's a version sensor
realy ??
There's the updater binary sensor but I've heard it's apparently but working
i need a normal sensor for that to get the amount of updates there are
Oh we should move to #integrations-archived
How Can I check with templates the last state change on a sensor? Thank you
@rugged lichen you want to pull the date/time the sensor changed state? if so I would make an automation that is triggered whenever the sensor's state changes and then just use the automation's 'last_triggered' attribute in the template. might be another way but that is what popped into my head.
As for me, does anyone know if it possible to use wait_template with events? specifically I want a script to wait until a specific event fires.
0.115 will introduce a wait_for_trigger action that could do that. You can install the beta if you want to try it now, or wait until next Wed
what a shock that RobC knew the answer to my question. I think it was yesterday that I declared you know everything
thanks mayne
next wed is a long time... might have to try my first beta
You can read more about it and the rest of 0.115 here: https://rc.home-assistant.io/blog/2020/09/07/release-115/
There is no default lets say attribute of every entity when the last time changed the status?
I would be able then use a template to (now() - when the sensor last changed) = I will get the time in hours since the last change was on the sensor.
that would be the thing what I want
to have a data what only contains a number in hours how many time left since my motion detector seen something.
for that I would probably use a timer. have the trigger be the state changing and the action be to restart the timer.