#templates-archived
1 messages · Page 164 of 1
@stuck remnant I looked it back, but I see I actually put the state change in the notification, so it should have shown in changed from off to off
Well... I think we need to amend the automation which sets the input_datetime
Because that will also be triggered here, where it shouldn't
ok
So there is actually an issue here
add a condition which checks if the to_state differs from the from_state
Can you share that automation again?
No, it checks if the previous state is either on or off, and if the new state is either on or off.
So off to off is valid
condition:
- condition: template
value_template: "{{ trigger.from_state.state != trigger.to_state.state }}"
ok so now I think I get it
and why it didn't make sense to me until now
because this also stamped from off to off, it messed up the other sensor
or at least it messed up my understanding of it
now it makes sense
thank you
Is there a way to use an attribute of a template sensor to access the value of a variable in the state template? I would want to use the hours list in a script for loop without having to harcode the list in the script and make any changes in 2 places. What I am trying to accomplish could be accomplished if there is a way to have the attribute, in this example output the next item in the list of the states template? Meaning if the state template outputs 65 can the attribute output 6:10 and add the : to 610 which is the next item in the list {{h[0]}}?
https://dpaste.org/2QVZv
No, you can not reuse part of your template in the attributes like that
The other way round is possible, set the hours in your attribute, and use the attribute in your state template
However, the state template will be rendered first, and then the attributes, so you have to work around that
How could I do this?
Something like this
sensor:
- unique_id: "daniels_thermostat_schedule"
name: Daniels Thermostat Schedule
state: >-
{% set hours = this.attributes.hours if this.attributes.hours is defined else [] %}
{% set t = states('sensor.time').replace(':','')|int %}
{% for h in hours if h[0] <= t <= h[1] %}
{{h[2]}}
{% endfor %}
attributes:
hours: "{{ [[530, 610, 65], [610, 740, 69], [740, 1500, 66]] }}"
changed it to match your format
And this gets around the fact the state is rendered first?
yes, because it will first use an empty list, and update after the attribute is updated as well
I see. Perfect thank you.
I actually don't have a sensor.time I copied this template from the forums. What was the format you had before? Or should I just make a sensor.time?
No, just use now(), but you can do that in a better way than I did, because I had to jump some hoops to get to the right format
Meaning replace sensor.time with now() or make sensor.time template now()
{% set t = now().strftime('%-H%M') | int %}
Perfect thank you
Is it possible to do what the state template is doing but instead select the next list item {{h[0]}} meaning If the state result is 65 can a template using the hours attribute in a script select 610 from the next list item [h0] and output {{h[0]}}.
If it's after 530 and before 610 it selects 65 in the state template. In a script I would want to use the hours attribute list to select the next item which would be [610, 740, 69] and output {{h[0]}} which is 610
In the script I would want to know the next time. The first number is the start of a time block for the temperature and the second is the end. In the script I want to run the time between now and the next change time 610 from [[530, 610, 65], [610, 740, 69]. The state of the sensor would be 65 if it's between 530 and 610. Then the 610 from [610, 740, 69] would be used to take the time between now and 610 in a loop to check weather conditions decide whether to adjust the temperature
so, when the state is 66 you would like to have 530
Yes and if the state is 65 I would want to have 610 for example. Without hard coding this so that I can expand the list without having to make other changes to achieve this
You can use single backticks to use inline code parts
makes your posts more readable
and less page filling
Single instead of 3?
yes
See the difference between my post and yours?
Yep I see the difference.
Eventually the list will be much bigger to cover 24 hours I only have [530,610,65],[610,740,69],[740,1500,66] for testing the concept
You can add it as an attribute like this: https://dpaste.org/jQDUv
Awesome thank you.
Would next_start need a >- instead of >?
What's the difference between the set time in state and set t in next_start?
The template sensor threw an error https://dpaste.org/rB57R
Hey, i have issue with scrape integration. When url is not accessible the sensor is delete with history of sensor. do you have any solution for keep history ? thanks
Not sure if this is the place for that? That is likely an #integrations-archived question. But I could be wrong.
single backticks!
Could it be that your current time range falls out of the ones you provided
And the set time is the same, but there is no way to reuse it, the variable time from the state template is not known in the template for the attribute
It would have been in the current time. [610, 740, 69], [740, 1500, 66] now it is [740, 1500, 66] and should show 530 [530, 610, 65]
Somehow without doing anything and another template reload it worked
Oops lol. Good to know. I'm working on taking a massive choose automation and changing it to a clean variable automation that is both dynamic based on weather and easy to modify vs a 400+ line choose automation. I will be back tomorrow with a question on a loop for the weather conditions between now and the next_time if I can't figure it out myself.
>- and > only differ in whitespace control, which doesn't matter much because HA will trim the empty lines anyway
I see.
Hey, i need to remplace value 1.0 and 0.0 to on and off when open and close the door. I have this for moment --> - platform: rest # INCUBATEUR 1 # resource: http://xx.xx.xx.xx/atmoweb?DoorOpen= name: incubateur01_doorstatus device_class: door scan_interval: 10 value_template: > {{ value.replace('"DoorOpen": ', '').replace(',','') }}
Hi Guys, Im relatively new to HA and need a hand with parsing some json in a template, the json that ill be working with is below. Essentially what I need is a loop that will check if any of the values are true then do something else do something else
{"abc123": false, "cbda123": false, "fsdfsd2": false, "dfgdfg222": false, "sdfdsf22": false}
{% set map={"abc123": false, "cbda123": false, "fsdfsd2": false, "dfgdfg222": false, "sdfdsf22": false} %}
{{ map.items()|selectattr('1', 'true')|list }}
depends on what you need to do with the results, but that will output a list of items where the value is true
Thanks Rob, ill give that a try now
which will be an empty list for that data
Essentially the data is number plates, so if none of the plates are known then get the number plate and alert me
the data is coming from an entity attribute
so:
{% set map={"abc123": false, "cbda123": true, "fsdfsd2": false, "dfgdfg222": true, "sdfdsf22": false} %}
{{ map.items()|selectattr('1', 'true')|map(attribute='0')|list }}
->
[
"cbda123",
"dfgdfg222"
]
Ill paste you the entity attribute as I think that will make more sense
vehicles:
- {}
orientation:
watched_plates:
abc123: false
qwe123: false
321sss: false
www123: false
eee123: false```
in the vehicles array it will show the registration detected, so if its not in the watched_plates section I'd like it to notify me
I think it will, still getting to grips with it haha - appreciate the help
ok I'm almost there, how do I extract the plate from this json? I think the additional [ ] is tripping me up
[{"box_x_centre": 926.0, "box_y_centre": 637.5, "confidence": 0.898, "plate": "abc123", "region_code": "gb", "vehicle_type": "Sedan"}]
{% set map=[{"box_x_centre": 926.0, "box_y_centre": 637.5, "confidence": 0.898, "plate": "abc123", "region_code": "gb", "vehicle_type": "Sedan"}] %}
{{ map|map(attribute='plate')|list }}
->
[
"abc123"
]
or just {{ map[0]['plate'] }}
but if it's going to be a list with more items, you'd want the first
It'l just be a single result so that should do the trick, lets see if i can adapt that 🙂
Thanks for the help, really appreciate it
Any ideas why the following:
{{ plate_json }}
{% set plate_check = plate_json|selectattr('1', 'true')|map(attribute='0')|list %}
{{ plate_check }}```
is giving me [] on plate_check?
```{"abs233": false, "sdfsdf2": true, "sdfsd1": false, "qweqwe1": false, "ydfdf22": false}
[]```
Because you've put quotes around true in your selectattr filter
if i remove the quotes i get
TemplateRuntimeError: No test named True.
yeah, you need that
if its easier, do you know of a way to output the number of values that equal true? aka on the above json it would output 1
Ah right, what Rob said!
I dont need to plates i just need to know if any are true
checking
UndefinedError: 'markupsafe.Markup object' has no attribute 'items'
sigh
my code:
{% set plate_json = {"abs233": false, "sdfsdf2": true, "sdfsd1": false, "qweqwe1": false, "ydfdf22": false} %}
{% set plate_check = plate_json.items()|selectattr('1', 'true')|map(attribute='0')|list %}
{{ plate_check }}
see what's different
my guess is that you forgot the ()
you need from_json
not to_json
{% set plate_json = '{"abs233": false, "sdfsdf2": true, "sdfsd1": false, "qweqwe1": false, "ydfdf22": false}'|from_json %}
{% set plate_check = plate_json.items()|selectattr('1', 'true')|map(attribute='0')|list %}
{{ plate_check }}
you want it to take json and turn it into a dict
so thats giving me
TypeError: the JSON object must be str, bytes or bytearray, not dict
ok
unfortunately I cannot debug on your system
it actually looks like you just need to remove the to_json
it's already a dict
bingo
not dict
TheFes is Robin to my Batman
😂
All of this just to get my gate to open on number plate recognition.... the things we do eh!
That's a cool use case, but spoofable is somebody cared.
I wouldn't jump to plate number as the trigger if I was guessing how it worked
So im trying to get my garage to only send a command if the port is open with this:
close_cover: >-
{% if is_state('binary_sensor.shelly__switch','off') %}
service: switch.turn_on
data:
entity_id: switch.shelly_shsw_1_
{% endif %}
But I have the wrong format
How can I archive this i yaml?
you can't template a whole service call like that without some advanced logic
you should use if/then
Can that be used in a cover device?
yes, the action in the template cover links to that page
sorry could you guide me a bit more with a example of the open cover action im trying to do?
I only want the template to send the switch turn off if the cover is open
otherwise nothing
you just have to put the two things together
close_cover:
- if:
condition: state
entity_id: binary_sensor.shelly__switch
state: 'off'
then:
- service: switch.turn_on
data:
entity_id: switch.shelly_shsw1
looks like you're missing a space
anyway, this checks fine in my config:
open_cover:
if:
condition: state
entity_id: binary_sensor.garage_door_sensor
state: 'off'
then:
service: switch.turn_on
data:
entity_id: switch.garage_door_switch
you're worry what VSCode tells you, and not what HA's config check tells you
and you appear to be using an old HA extension for VSCode that doesn't understand if/then
maybe you're using an ancient version of HA
if everyone who had issues would start by making sure they're up to date
update to 2022.6.3
but then i would have to migrate my zwave 😭 🤣
still no excuse though, should just do it
if you stay behind, you're on your own
i'm just lazy but also none of my stuff is currently broken
Version core-2022.2.9
i'm sure that will change
the docs move forward without you, and then you'll just be sad and confused
im gonna throw out all crap zwave and put in shellys
you can also use choose: there, but you're on your own to convert it
or even just an inline condition. That's really the easiest
didn't think about that at first, but it's just what you want. There are many ways
Don’t know what’s a in-line condition is
hi, i need help
What is the raw output from your rest sensor, before doing the replace?
Since updating to 2022.6 using states.binary_sensor|selectattr('attributes.device_class', 'eq', 'window') fails with "UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'" I suspect because the device_class is not set on all my binary sensors and the fact you need a default for most template values, but I can't work out how to provide one. Any suggestions?
Hi guys, I was using an automation that was working like a charm since last update.
The automation is checking for rain precipitation in the daily forecast to allow the morning irrigation.
{{ state_attr('weather.city', 'forecast')[0].precipitation == 0 }}
Unfortunately now I get this error: template value should be a string for dictionary value @ data['value_template']. Got None
for what I understand seems the value is not considered as a number anymore but i I check the state i get this value: precipitation: 6.5
"DoorOpen": 0.0, And on my sensor i have just 0.0 or 1.0 (Close or Open). I need for that a card on lovelace when is status is 1.0 door icon is open and when status is 0.0 door icon close. The best would be convert double "0.0" -> close and "1.0" -> open.
Just use a value_template that checks if it has the DoorOpen value:
{{ value == '"DoorOpen": 1.0' }}
This will return true if the rest sensor returns the string "DoorOpen": 1.0 and false otherwise. Which is a binary sensor.
{{ value.replace('"DoorOpen": ', '').replace(',','')}} I have this now
Yup you don't have to use replace to isolate out the 1.0 or 0.0. Just use the whole string
{{ value == '"DoorOpen": 1.0' }} this ?
The rest sensor only returns two possible strings? "DoorOpen": 1.0 or "DoorOpen": 0.0?
resource: http://10.10.30.4/atmoweb?DoorOpen=
name: incubateur04_doorstatus
device_class: door
scan_interval: 10
value_template: >
{{ value.replace('"DoorOpen": ', '').replace(',','')}}``` It's my config
yess
Try replacing your current value_template with this then
selectattr('attributes.device_class', 'defined') add this before your select on which device class you need
Thanks very much I will give that a go.
With dev tools on HA for test it's work or he should open door?
If you want to test in Dev Tools > Template, put the whole thing into the text box {{...}}
ok
Then you can go open and close the door and see if the output changes from true to false as expected in real time.
.share the whole yaml of the part in which you use this template
And just to be sure, check the first pinned post
UndefinedError: 'value' is undefinedhe missing thing?
Oh right...in Dev Tools > Template, you won't have access to the value from your rest sensor. Mmm afraid you can't test it as-is in Dev Tools > Template then.
Try just putting that in the value_template of your actual rest sensor and then see how the sensor state changes in Dev Tools > States when you open/close the doors.
ok i will test
add value_template to name of sensor?
Where you had {{ value.replace... }}, replace it with the new one.
this good ? {{ value_template('"DoorOpen": ', '').value_template(',','') }}
who can help me out. Someone on the facebook home assitant group suggested me to adjust my template setting so i don't get any negative values anymore in my graph. But when i adjust it i get errors. Sorry i'm new to ha and still learning. https://imgur.com/a/ZVkjM9w https://imgur.com/a/vSrPSBC
it's same UndefinedError: 'value' is undefined
Nope. What I meant is:
- platform: rest # INCUBATEUR 4 #
resource: http://10.10.30.4/atmoweb?DoorOpen=
name: incubateur04_doorstatus
device_class: door
scan_interval: 10
value_template: >
{{ value == '"DoorOpen": 1.0' }}
In dev tool. ?
@rose scroll
No, in your config directly.
Hi guys, not sure if this is the proper channel. If not, sorry about that.
I'm building a bridge to integrate a 433mhz controller fan using home assistant to mqtt to esp8266 to 433 mhz.
The communication is working great and I'm able to send the payload to the esp and make it do whatever i want.
I need to parse into the payload the value of an slider named: input_number.nivel_luz
The templeate {{int(states('input_number.nivel_luz'))}} returns the value of the slider.
If i put this templeate into a button which on tap runs the mqtt:publish service and as a payload template i use the previous template it doesn't work. After saving it changes the template to [object object]: null
I not really sure what I'm doing wrong here, if you could give me some guidance it will be great
ok it's done, and in dev tool, i paste just {{ value == '"DoorOpen": 1.0' }}?
UndefinedError: 'value' is undefined
resource: http://10.10.30.4/atmoweb?DoorOpen=
name: incubateur04_doorstatus
device_class: door
scan_interval: 10
value_template: >
{{ value_template == '"DoorOpen": 1.0' }}```This
or
you probably don't have quotes around your template. Post the entire mqtt.publish service's yaml.
resource: http://10.10.30.4/atmoweb?DoorOpen=
name: incubateur04_doorstatus
device_class: door
scan_interval: 10
value_template: >
{{ value == '"DoorOpen": 1.0' }}```
this, it's same
@rose scroll
Yeah, that was it. Thank you so much 👍👍👍
Are you sure the raw output isn't something like
{
"DoorOpen": 0.0,
"othercrap': "y"
}
no bracket {} just "DoorOpen": 0.0,
can you copy/paste everything from the endpoint here?
go to the endpoint
use CTRL+A, CTRL+C, then CTRL+P the result here.
I don't understand for endpoint, my dev tool don't work
trying to see if there is hidden characters
this is a rest sensor correct?
open a browser. Go to: http://10.10.30.4/atmoweb?DoorOpen=
Ho no with {{ value.replace('"DoorOpen": ', '').replace(',','')}}
it's work
but i want replace 1.0 and 0.0 to on or off
value_template: "{{ 'on' if '1.0' in value else 'off' }}"
and with my old config?, i need this {{ value_template('"DoorOpen": ', '').value_template(',','') }} for select value.
no, replace it
you can also just make it a binary sensor
with
value_template: "{{ '1.0' in value }}"
but your rest sensor needs to go in the binary sensor section
and it will then become binary_sensor.<name_of_sensor> instead of sensor.<name_of_sensor>
Any idea why both "{{ state_attr('sensor.right_dockpro', 'status'). water_level <= 40 and not is_state_attr('sensor.right_dockpro', 'status.water_level','0') }}" and "{{ state_attr('sensor.right_dockpro', 'status'). water_level <= 40 and not 0 }}" are evaluating to true when the value is 0. I tested both in the template editor and the not works.
The first because you put quotes around the 0
The second because you are not staying what should be not 0
Alright use the first and remove quotes?
"{{ 0 < state_attr('sensor.right_dockpro', 'status').water_level <= 40 }}"
Ok but just with value_template: "{{ 'on' if '1.0' in value else 'off' }}" it's work ?
Unless it can be below 0, in that case this doesn't work
I set it to notify me with the value when it triggered and it was 0 never below 0. It becomes 0 when there's a disconnect or API issue
Just try it
that work, you are a amazing genius 🙂
Okay, then my template should be fine
Corrected it
It is, but you should put a dash in front of it
Invalid config for [light.template]: Unexpected value for condition: 'None'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['lights']['kitchen_fan_light']['turn_off'][0]['if'][0]. Got None
required key not provided @ data['lights']['kitchen_fan_light']['turn_off'][0]['then']. Got None. (See ?, line ?).
@marble jackal
How can I get the translated/plain value from a sensor via template? Eg. states('alarm_control_panel.abc') returns 'armed_home'. Fine. But I would like to e.g. receive the German value like it is shown in UI, History, Log, etc.: "Aktiv, zu Hause". How can I get this (without endless if-else-rebuilding of the different states)?
Why did you remove them in the places where your actually had them.
And don't share images of code. Use a code sharing site like dpaste.org
deleted*
can you please help me format it right @marble jackal
its the turn off section
Did you actually read my message? Use a code sharing site. Don't place walls of code on the channel
@marble jackal https://dpaste.org/J9EVd#L2
Invalid config for [light.template]: required key not provided @ data['lights']['kitchen_fan_light']['turn_off'][0]['then']. Got None. (See ?, line ?).
Don't tag me please, I'm on the channel and trying to correct it
This should be better https://dpaste.org/kqT8R
And data_template had been depreciated over 2 years ago, and you are not even using a template there
The then is part of the if action, so no dash there. And your actions which are part of the if-then should be intended so they are part of the then
How do you do regex with templates, or starts with?
Think we need a bit more info better
Are you using Helium network? You can add sensors, binary_sensors, and devices trackers to HA using the API and no config is needed in HA or mqtt at all, its all done in the helium console. devices are created when you submit data. If you want more info i can share my console setup. I have GPS trackers and, voltage sensors and relays from Helium in HA now.
I think more people would use the Helium LoRa network if they knew about it, and how cheap is is. $0.00001 per packet. way cheaper than Hologram.io
0.0001 would be the cost of 10 packets. I edited my original comment, i put not enough 0's
It would cost $0.50 to have a GPS tracker send location every 10 minutes for a year.
I dont know what you mean by markup..
Like if you only sent 10 total packages a year
Are you getting charged a penny?
Ah yes, I'm using a webhook to run an automation, I want to run a specific command if the "{{trigger.value2}}" equal a regex string and sometching else otherwise , I can't find how to do that.
packets.. not packages. a packet is a beacon, like a GPS sending its info once..
Yeah, on mobile, auto corrected
I still don't think you understand my question
lets say the billing cycle is 1 year
When you sign up for the helium console they give you 10,000 data credits free, $10 worth.
it will last a long time..
There is no billing cycle... you buy data credits a head of time.. every packet costs $0.00001
you tell me how many packets you want to send in a year and then times that by the cost.
You cant buy just one data credit.
and that's where I was going with this, thanks
So you would pay $10 and you get 1,000,000 data credits. But the cool thing is when you create your free account, they give you 1,000,000 data credits for free. to incentivize using this network. explorer.helium.com lets you look at the coverage area.
in your account that do not expire ever
that still doesn't help us help you
regex is extremely complicated. There are 1000s of tutorials, outside HA.
I use this site to help format regex https://regex101.com/
and if you don't know, regex was not created by HA, it's simply used by HA. And it uses pythons regex.
Every language has a rendition of regex and they are all slightly different
so you should just ask how to format the regex unless you feel like learning a whole new symbolic language
Ah yes I think the regex is "^Starting*" is what i need
just {{trigger.value2 == "^Starting*"}}
doesn't seem right
why do you have 0 or more of indicator there
remove the *
you're literally seraching for Startin or Starting or Startingg etc
I dont want to learn regex, I just want a command that I can use regex in for example in python re.pattern("some string","regex") would allow me to use regex. Im just trying to find the command, in this example re.pattern
but yea, i was going to play with for a bit, been a while since i have used it.
my regex is def wrong
what's the phrase you're looking for in trigger.value2?
Im looking for a matching on it starting with "Starting Upload"
You don't need regex for that
simple == will work
if "Starting Upload" is anywhere in the string, you can simply
{{ "Starting Upload" in trigger.value2 }}
if you want to see that it starts with "Starting Upload"...
{{ trigger.value2.startswith("Starting Upload") }}
your right, might be overcomplicated it
Only resort to regex if you have to.
Thank you so much😁
Hi Guys, I've setup a custom sensor in my configuration.yaml and need to get the last time it was updated for an automation, is that possible?
We meet again Rob! - Thanks 🙂
HA & Jinja noob needs help with a simple template
Is it possible to use this as an automation trigger? e.g. if last_updated < 2 seconds ago do xyz
yes
Your example isn't really a trigger, though. A trigger is a point in time when something happens or becomes true
what you described is a condition, perhaps, with something else as a trigger
My situation is for my number plate recognition for the gate opener. Its all working fine but if the same number plate is detected with no other cars in between then because the stored number plate is the same it doesnt trigger the opening
and you're using a template binary_sensor or similar?
so the state doesn't change?
I would just add auto_off: "00:00:02" or something like that
Its just an ordinary sensor, is it possible to do something similar to auto_off? perhaps remove the state entirely after x seconds
what do you mean by "ordinary sensor"?
how does it get its state?
as opposed to binary_sensor?
Apologies for what is very likely awful coding but here it is:
sensors:
number_plate:
friendly_name: "Number Plate"
entity_id: "sensor.number_plate_id"
value_template: >-
{% if states('image_processing.platerecognizer_gate') != "unknown" and states('image_processing.platerecognizer_gate') > "0" %}
{% set raw_data = state_attr("image_processing.platerecognizer_gate", "vehicles") %}
{{ raw_data[0]['plate'].upper() }}
{% else %}
No Plates Detected
{% endif %}```
then what do you do with the state of that sensor?
it seems like in the end, you just need to encapsulate whatever logic you care about in there
I have an automation with the trigger being that sensors state being updated followed by a number of IF's for each plate
it depends on what you're actually doing in the automation, but if it's just "is it a recognized plate or not?", then I recommend making a template binary_sensor that just encapsulates all of that and gives you "on" or "off", with an auto_off to reset it
Yeh it is, so if its recognised then open the gate and notify me
you would just need something like:
{% set known_plates = ["AAA", "BBB", "CCC"] %}
{{ raw_data[0]['plate'].upper() in known_plates }}
once again you've been supremely helpful, thank you
there's a bit more to think about to form a complete solution, but I would do the following:
- Make it a
binary_sensor - Add a trigger to your template sensor to watch for state changes of image_processing.platerecognizer_gate
- Add the logic above to make the state 'on' if a known plate is identified
- Add an
auto_off: "00:00:05"to have it auto-reset - In your automation, use a state trigger on your template
binary_sensorand notify with the logic from above:
{% set raw_data = state_attr("image_processing.platerecognizer_gate", "vehicles") %}
{{ raw_data[0]['plate'].upper() }}
just a thumbnail sketch. there are lots of ways to accomplish it
maybe you need a longer auto_off value to ensure that it doesn't trigger for the same car before it's cleared the gate
That does sound like a good way to do it, I'll give that a go and see what the results are
If it triggers more than once for the same car it wouldnt matter as the input is ignored by the gate
@quick yacht posted a code wall, it is moved here --> https://hastebin.com/sadoqiwuto
Hi, my first ever question to the community. Also a newbie in the python world but managed to write a small integration for my Chinese inverter (https://github.com/basghar/teslapv_pk). Basically I am saying that feel free to roast me but like a rookie 😳 . I am still grasping the core concepts. Let's see how the journey goes. So here goes my question.
I need to calculate current from the values that my inverter is providing.
https://hastebin.com/sadoqiwuto
It works fine but I have few questions.
- For things like this, is using template the recommended way or does HA have another trick up it's sleeve
- Under certain conditions, the value cannot be calculated and therefore I return unavailable. Is that the correct implementation? I saw availability in the docs but I am confused. If the value unavailable of a state of a sensor does the job, then why is the availability attribute needed? I thought that the state template would not be evaluated if the availability attribute returns False. Please excuse me if that is a dumb question.
- I had to do the same calculation for a few other energy sensors. Replication bit me a few times so I started looking for a way to reuse. Looks like it's not straightforward in the templating world. I came across https://github.com/home-assistant/core/pull/42244#issuecomment-716042818. python_script does not support imports so I looked at the custom component method but the custom component does not appear to be designed for providing such functionality. Like the iot_class manifest attribute seems irrelevant for such a use case. I looked for an example but could not find a way.
Afternoon all. I am trying to create a quick template that compares the current and old value of a sensor and keep running into issues. What would be the best way to do this? This is not an automation, just a regular template.
What have you tried and what were the issues?
@inner mesa Current code is @ https://codeshare.io/j0YWr3 -- i've tried many iterations and forget everything I have tried.
Just added a previous attempt I forgot about
it's all just random stuff
what you're asking for only makes sense in the context of a state change, which you detect with a trigger in a template sensor or an automation
so in that context:
so I am trying to add this to the config of the UI card so it changes the icon as the comparison changes, if that makes sense.
trigger:
platform: state
entity_id: sensor.whatever
condition:
condition: template
value_template: "{{ trigger.from_state.state|float < trigger.to_state.state|float }}"
action:
...
for example
I'm sure there are threads on the forum for stuff like this
i've found examples for a fixed number or a on/off state but that doesn't help for trying to compare the previous value of the sensor.
you can't just get the previous value of an entity from the entity itself
it's part of the state change event when it changes state
that was hit #1 🙂
and it's basically doing exactly what I have above
yup, i've been there a few times. I'm not sure how I can apply that to the card code.
it doesn't belong in a card
so I can change the icon of the card from an automation template like that?
you could use it in an icon_template for a template sensor, or other integration that supports it
but again, it needs to be based on a trigger where you have the old and new states available
ok. i'll focus my search on that and see what I can find. I saw that early on but I don't remember why I passed it up. I'll have something else for you/the channel later on lol. (new topic)
thanks for the guidance ... hopefully I have my eureka moment soon.
how could I modify this:
{% for state in states.light -%}
{%- if state.state == 'unavailable' %}
{{ state.name }}
{% endif -%}
{%- endfor %}
so that instead of showing the name of the entity that is unavailable , it counts all those entities and return the number of them being unavailable ?
{{ states.light|selectattr('state', 'eq', 'unavailable')|list|count }}
also, to simplify your first one:
{{ states.light|selectattr('state', 'eq', 'unavailable')|map(attribute='name')|list }}
Ah! Thanks alot!
Hello! I'm trying to set a picture card in home assistant that the url is what's displayed as the art cover of a media player.
this template gives me the url correctly {{state_attr('media_player.denon_avr_s740h', 'entity_picture')}}
but this template doesn't return the image if I put it inside a picture card
anyone knows why this doesn't work?
it works if i just use image: /api/media_player_proxy/media_player.denon_avr_s740h?token=(my_token)
just realized it doesn't update unfortunately
most cards don't support templates
how do i exclude an entity from a list
{{ states.light | selectattr('state', 'eq', 'on') | rejectattr('entity_id', 'in', area_entities('Bedroom')) | map(attribute='entity_id') | list }}
never mind i see my mistake
hey i am trying to make a temp
late so i can track my dehumidifer run time. i have this
- sensor:
- name: Dehumidifer state
state: >
{% if (states('sensor.dehumidifier_power')|float > 3.5) %}
"on"
{% endif %}
i was trying to get it to say on
but i can't figure out how to get that part to work.
i can have it report false, but i really want on.
also is there somewhere to check what state. attributes things have ?
the multiline example is using a switch with pwr sense capabilities. how can we find the same info
also where are all the i guess programming directives like state_attr and stuff?
is there a central place to ref them?
If you want to use on and off as state for your template sensor, a binary sensor makes more sense
The template yes, but the state of a binary sensor is either on or off
Check
> states
That's also the answer to this question
then shouldn't this work instead of saying it got None?
{% if state_attr('sensor.dehumidifier_power', 'W')|float > 3.5 %}
No, that doesn't output anything
so then i am going to ask again about state_attr()
{{ state_attr('sensor.dehumidifier_power', 'W')|float > 3.5 }}
Because the that statement is not complete, it needs what you want to output in case that the statement is complete, and an {% endif %}
Test your template in
> template
i only provided the part that is failing.
and i am testing it tehre
and that is why i am here with all of these questions
and i pasted the full if statement above. it is a complete if statement.
{{ state_attr('sensor.dehumidifier_power', 'W')|float > 3.5 }}
is also failing and daying float got invalid input. it is behaving the same as the my if statement.
This will output true, false or an error
Well, then your input is wrong
"{{ states('sensor.dehumidifier_power')|float > 3.5 }}"
that produces true or false.
and its still not clear how to get state_attr from the states and how to correlate them
based on what is my input wrong?
This input is correct, state_attr is used to get the value of an attribute
Example:
entity_id: sensor.bureau_martijn_power
state: 69.1
attributes:
state_class: measurement
unit_of_measurement: W
device_class: power
friendly_name: Bureau Martijn Power
{{ states('sensor.bureau_martijn_power') }} output: "69.1"
{{ state_attr('sensor.bureau_martijn_power', 'device_class') }} output: "power"
i guess i need to review the examples again
as there is a disconnect somewhere. is the state_attr function documented anywhere? i checked on the jinja site, and this seems to be an HA thing
The state_attr functions is documented in the HA Templating docs: https://www.home-assistant.io/docs/configuration/templating/#states
ahola , haven't touched ha for a while except for upgrades. looking at moving to appdaemon. Is this the right place to ask for hints. thanks
This is the place for jinja templates 🙂
Hi, i need to create a virtual sensor with link to a rest or scrape sensor. I need that because i want to keep history of sensor when a rest or scrape integration sensor do not respond. Do you any solution /idea for my issue ?
@tranquil yew
pastebin some info
Most reliable is probably to write the value to an input_text or input_number on every state change, and check in the conditions if the value is correct
didn't you get the solution or something similar the other day
Do you have an example in pastebin ? for syntax
if I were to set my mqtt sensor to unavailable if the value wouldn't be a state, could this do it?```
{{iif(is_number(value), min(value|round(2,none),2500),'Unavailable')}}
thing is, we can only use the availability_template on the Mqtt sensors with a real topic, and not like in template:
or should I replace the 'Unavailable' with None maybe? see https://community.home-assistant.io/t/how-to-set-the-available-on-this-mqtt-sensor/429399/2 for some bckground
thing is, if I test this: {% set value = 'no_number'%} {{iif(is_number(value), min(value|round(2,none),2500),'Unavailable')}} I get the ValueError on round..... 'but no default was specified' even though it is? And can only get that to work if I feed it a number {{iif(is_number(value), min(value|round(2,default=-1),2500),'Unavailable')}} which is what I was trying to prevent... it should error as Unavailable on Not number..heck.
No, you have to use the pythonic in line if statement because iff resolves all values, where the pythonic in line if statement only resolves what is executed.
{{ min(value|round(2,none),2500) if value | is_number else none }}
thx, been struggling here, because even the additional comparison below needs a default... {% set max = 2500 %} {{iif(is_number(value) and value|float(-1) > 0, min(value|round(2,default=-1),max),'Unavailable')}}
would be {{ min(value|round(2,none),2500) if value | is_number and value|float(-1) > 0 else none }} ?
{% set maximum = 2500 %}
{{ [ value | round(2), maximum] | min if value | is_number and value | float > 0 else none }}
you don't need defaults if you check for it in order
ok let me try that, thanks!
to be sure, did you purposely change my 'max' to 'maximum' ? reserved word maybe?
yes, and yes
👍
on the float filter: neither yaml checker nor ha core check find that, and let one restart without it. With all failing sensors as a consequence, and a lot of errors in the log....
right, so apart from my obvious mistake the sensor should also be allowed to be 0... I now see None W as state on those. Shouldnt I see Unavailable in the Dashboard for an unavailable entity? The dev states also show None, and not 'Unavailable'.
Any idea how to stop the first block [530, 630, 65] from providing a next_start of 1730 [1730,1845,64] when it should be 630 from [630, 740, 69]. I assume it has something to do with h[2] == this.state as I have 2 65s in h[2] one at [530, 630, 65] and one at [1500,1730,65]? The rest works.
For context next_start is to use the hours list in a script to check the weather conditions during the time between now and next_start
hi I have a snippet of code to trigger when the current time = my alarm time set by the HA app as below:
{{now().strftime("%a %h %d %H:%M %Z %Y") == (((state_attr('sensor.ha_app_next_alarm', 'Time in Milliseconds') | int / 1000) + 0*60 ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}
It looks like this is now broken with the latest 2022.6 update.. probably due to timestamp_custom function not having a default value.. any suggestions on how to fix this? thanks
if you know of a better way to do it i'm happy to switch, i think i took this code from somewhere in the web.. the 0*60 was probably an offset I set to 0
I figured as much
Like I said, I suggest putting it in
-> Templates and seeing what's wrong
ValueError: Template error: int got invalid input 'None' when rendering template '{{now().strftime("%a %h %d %H:%M %Z %Y") == (((state_attr('sensor.ha_app_next_alarm', 'Time in Milliseconds') | int / 1000) + 0*60 ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}' but no default was specified
i pasted parts of it and the bit that's error-ing is the timestamp_custom function, I thought adding default=X in it will work but it still fails
probably need to understand what this means https://community.home-assistant.io/t/updating-templates-with-the-new-default-values-in-2021-10-x/346198
thanks - looks like it works and it was because I was not putting in the right sensor name.. sorry about it.. but the templates function was very helpful in debugging.. so many thanks for that 🙂
is there no switch { case: .. } syntax in jinja2? i have to use if elif ... ?
yes
@ocean marsh posted a code wall, it is moved here --> https://hastebin.com/inicuzuroc
damn indention 😦
Any idea how to stop the first block [530, 630, 65] from providing a next_start of 1730 [1730,1845,64] when it should be 630 from [630, 740, 69]. I assume it has something to do with h[2] == this.state as I have 2 65s in h[2] one at [530, 630, 65] and one at [1500,1730,65]? The rest works.
For context next_start is to use the hours list in a script to check the weather conditions during the time between now and next_start
Rob are you talking about me?
no, the person who deleted their misplaced post
Oh ok lol.
Images of text are evil and not useful. Please share the actual text
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
@cyan pier posted a code wall, it is moved here --> https://hastebin.com/asayigaves
yes, however did not see the 15 line max limit
uh... so whats your question...
was deleted
probably something like this:
{% set data = [{"a": "foo", "b": "bar"}, {"a": "blah", "b": "floop"}] %}
{% for item in data -%}
{{ "a: " ~ item.a ~ ", b: " ~ item.b }}
{% endfor %}
I wish there was a way to use format() as a filter to output different pieces of an incoming data structure without the need for a for loop
basically writing a for each departure in departures, print line, time. manually referring to each index would be clumsy
I cant seem to find in the documentation how to use home_assistant_start in a template. I'd like to create a condition like this:```
{% set val = now() %}
{{ ((as_timestamp(val) - as_timestamp(states.home_assistant_start.last_updated))) > 180 }}
https://www.home-assistant.io/integrations/uptime/ add uptime sensor to your config and use the datetime it provides
Awesome! That will do the trick - Thought I might get away with leveraging off the event...
Is it also possible to add specific days of the week for Example. It would filter through what day of the week is today and the time to find the correct match {{h[3]}} and correct next_time.
[weekday,530,630,65],[SatSun,630, 740, 69],[weekday,530,630,65],[MWFSS,740, 1500, 66]
Something along the lines of?
{% set MWFSS = [0,2,4,5,6] %}
{% set weekday = [0,1,2,3,4] %}
{% set SatSun = [5,6] %}
any idea why this trigger won't work:
- platform: template
value_template: "{{ today_at(states('input_datetime.sleep_time')) - timedelta( minutes=5 ) }}"
any pro templaters here?
its my first time using them and im trying to put the value of my next alarm sensor into a text helper but modify the text before writing it to the text helper
it sets the helper to this now:
Fri Jun 10 06:45:00 GMT+02:00 2022
and i want to make it set like this:
Friday 06:45
Where the day and time will ofcourse vary based on the original 'next alarm' value
Heya!
I use this template sensor:
state: "{{ state_attr('weather.smhi_home', 'wind_speed') | float / 3.6 }}"
And it returns a value with a lot of decimals. And if I just want to show 1 decimale shouldn't I just add "| round(1)" after 3.6 in the code? I tried that but it doesnt return anything.. what am I doing wrong? 🙂
tried also:
{{ now() == today_at(states('input_datetime.sleep_time')) - timedelta( minutes=5 ) }}
still nothing
I think it's round (1)
Right! wrong of me, was suppose to be "round(1)" 🙂 But yeha it still doesnt show any less decimals
"{{ state_attr('weather.smhi_home', 'wind_speed') | float / 3.6 | round(1) }}"
it still return : 1,944444444444444444 in Template tool :S
just want that 1.9
if I remove "(1)" and just go "round" it give me 1,75
Hm not sure. Will need someone with more experience lol.
Yeha.. probably something we're not seeing here hehe
I am trying to figure out the best way to add/remove alerts into the dashboard I created based upon data from an html table. The catch is I only want certain items. The table has 4 columns, two of which I will use to filter the results I want to work with.
What is the best way to add/remove items to a sensor (figure logbook or markdown as best option?) based on the “alerts” that I want to see from the data source?
Same problem as your previous issue with as_local: as RobC said, you need brackets () around state_attr...3.6 before you apply | round(1), otherwise the round will just apply to the term before it i.e. 3.6.
Hm, I did try around with brackets! Ok then I will try harder, thx! :)
i know at the end of the day, its minutely easier, but any possibility of doing this? (using a template in a service call)
"{{'switch.turn_'~states('light.lamp')}}"
now() is in millisecond, that is too precise to ever match exactly, try {{ now() > today_at() - timedelta() }}
service: switch.turn_{{ states('light.some_light') }}
might be a bit easier for the eye
hi all, i was wondering if a template can be made to set a rolling shutter position by using some sort of time based button pressed and convert it to percentage
i have a zigbee rolling shutter that does not have a cover.position working, the only exposed working things are open/close/stop button
from what i can see, the close button stops the movement, and the open/close move up and down the shutter for XXsec, lets say 180sec (you can hear the relay click after that amount of time).. the shutter goes from fully open to fully close in maybe 25sec
my idea was to do something like:
-> i know that my shutter is fully open ->
-> i want 50% of my shutter closed ->
-> use close button for 12sec ->
-> report in HA slider that is 50%
some sort of time based calibration, dunno how to call it
Should be possible with a template cover
Hey TheFes Is it possible to filter for specific days of the week. It would filter through what day of the week is today and the time to find the correct match {{h[3]}} and correct next_time.
[weekday,530,630,65],[SatSun,630, 740, 69],[weekday,530,630,65],[MWFSS,740, 1500, 66]
Something along the lines of?
{% set MWFSS = [0,2,4,5,6] %}
{% set weekday = [0,1,2,3,4] %}
{% set SatSun = [5,6] %}
Not like this I guess, but your hours also don't work like you did them now, you should let it start at 000 and end at 2359
now it won't work after 1845
didn't see that yesterday as I was on mobile, but it does explain why it wasn't working for me at that time (it was after 1845 for me)
Yep the state is broke but next_start works. So change it to this?
hours: "{{ [[530, 630, 65],[630, 740, 69], [740, 1500, 66],[1500,1730,65],[1730,1845,64],[1845,2359,63],0000,530,63]] }}"
next_start works because I added a default there
This would be more clear (to me) "{{ [[000, 530, 63], [530, 630, 65], [630, 740, 69], [740, 1500, 66], [1500, 1730, 65], [1730, 1845, 64], [1845, 2359, 63]] }}"
Yes more clear to me too lol.
any hint where to look in the docs or somewhere?
Got it :
"{{ (state_attr('weather.smhi_home', 'wind_speed') | float / 3.6) | round(2) }}"
Learning bit by bit 🙂 Thanks for help!
Do note that you can put an entire script sequence in the actions fields, you do need to add a dash then:
open_cover:
- service: cover.open_cover
target:
entity_id: cover.some_cover
- delay: 25
- service: cover.stop_cover
target:
entity_id: cover.some_cover
Check out this custom component, sounds like it does what you describe. https://github.com/nagyrobi/home-assistant-custom-components-cover-rf-time-based
I understand, unfortunate that wont work because that means:
every time I change that input date time automation triggers (I had it setup like this before, this always happen)
any other good way to implement an offset of 5 minutes or so before a input date and time?
i think i found a way
trigger:
- platform: template
value_template: "{{ (today_at(states('input_datetime.damian_sleep_time_school_day')).timestamp() - 300) | timestamp_custom('%H:%M:%S') }}"
yah this will work for sure
That's not a trigger, that's providing a timestamp
a template trigger should evaluate to true or false
Hey TheFes, do you think what we were talking about earlier is possible or should I have separate template sensors for different days? Here's the dpaste with the revised hours
https://dpaste.org/G9EFr
Your hours attribute is incorrect on that one, the last one is not a list, and I thought we agreed the other order was a bit more understandable
I pasted the wrong one whoops. It is more understandable how you set it up.
"{{ [[000, 530, 63], [530, 630, 65], [630, 740, 69], [740, 1500, 66], [1500, 1730, 65], [1730, 1845, 64], [1845, 2359, 63]] }}"
I think it would be easier if you add different attriutes, so an attribute hours_weekday and hours_weekend
And then determine in the state and next_start templates which should apply
Whatever you think is easiest/cleanest. I am not the wizard lol just thinking of the possibilities not exactly as capable as you are in realizing those possibilities.
Well do that then.
Then assign the right attribute with a template like this:
{% if now().weekday() < 5 %}
{% set hours = this.attributes.hours_weekday if this.attributes.hours_weekday is defined else [] %}
{% else %}
{% set hours = this.attributes.hours_weekend if this.attributes.hours_weekend is defined else [] %}
{% endif %}
And If I wanted to get specific such as Tuesday and Thursday. Would that be now().weekday() in (1, 3) for example?
I would use [1, 3] but a tuple should also work. But you'll have to create a sepearate attribute for that as well then
Perfect thank you as always. Does the use of "{{ [[000, 530, 63], [530, 630, 65], [630, 740, 69], [740, 1500, 66], [1500, 1730, 65], [1730, 1845, 64], [1845, 2359, 63]] }}" fix the issue after 1845 of not returning a state?
yes, because you were checking if this in your previous version 1845 < 2100 < 530 That is never true, as the 530 is lower as 1845. Now your are checking 1845 < 2100 < 2359
Makes sense, thank you.
maybe this will work?
trigger:
- platform: template
value_template: "{{ (now().timestamp() | timestamp_custom('%H:%M')) == (today_at(states('input_datetime.sleep_time_weekend')).timestamp() - 300) | timestamp_custom('%H:%M') }}"
That could work, this is a bit shorter.
trigger:
- platform: template
value_template: "{{ now().strftime('%H:%M') == (today_at(states('input_datetime.sleep_time_weekend')) - timedelta(minutes=5)).strftime('%H:%M') }}"
Does this look right? Spacing might be messed up.
https://dpaste.org/1HtGi
Yep I would have to do that. Just making sure that part is correct.
triggers just need to resolve false to true, you don't need to go that crazy with the syntax
"{{ now() > today_at(states('input_datetime.sleep_time_weekend')) - timedelta(minutes=5) }}"
now() always resolves slightly past the minute, like ~15 microseconds
I suggested that, but according to Hellcry it would trigger when changing the value in the input_datetime
which is true when you change if from something after now() to before
This would also work:
"{{ now().replace(second=0, microsecond=0) == today_at(states('input_datetime.sleep_time_weekend')) - timedelta(minutes=5) }}"
Thefes or Petro. Now that I'm past the scheduling part. I would want to use next_start to evaluate the time between now and then against weather conditions. The goal is to make a dynamic HVAC Schedule. This is not proper formatting just thoughts and placeholders for temperatures so that I can fix in the future as I figure out what I want. Is this possible to evaluate the weather conditions in the time between now and next_start. I brought in some stuff from a previous script you guys helped with related to the weather.
I missed this part from the previous script. {%- for hourly in forecast[:6] the :6 would need to be a variable i Assume.
:6 is the first 6 items from the array
Yep I know. But I wouldn't use that if the next start is only 2 hours away for example. So it would need to be a variable? (The weather forecast is hourly). I'm just guessing as to how this could be done.
oh great gonna check it out asap! thanks!
holy $$$$ it works GREAT
that went really faster and better then expected 😮
I added a template sensor to a yaml. I then changed the type of the sensor from sensor to binary sensor. There is no reference in the yaml to the sensor any more, but I'm still seeing the entity..... How do I get it to go away?
I tried restarting....
And it isn't selectable in the entries settings page
this wont work, this triggers when i change the input_datetime.sleep_time_weekend
You can probably delete it from the GUI now, it will be recognized as an orphan entity
👍
I'm using an automation which is basically a while loop that decrements an helper input_number.irrigation_timer until it is 0 (zero) and the loops stops .
The decrement I use the following YAML
- service: input_number.set_value
data:
value: '{{ (states(input_number.irrigation_timer) |int ) - 1 }}'
target:
entity_id: input_number.irrigation_timer
and this is the trace log output
Error: Error rendering data template: Undefined Error: 'input_number' is undefined
What is cooking here?
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
value: '{{ (states("input_number.irrigation_timer") |int ) - 1 }}'
You missed quotes around the entity
Don't forget you can test in
-> Templates
Yep , this works.
You know, I'm an archaic UNIX guy , but this stuf is more pickier about quotes " , ' , ` 🙂
Not any worse than a UNIX commandline 😉
That part is straightforward. Strings are surrounded by quotes, and other things are either functions or variables
Pretty similar to any other language
I do not agree, Unix does not care about the amount of (white) spaces, this does. 😦
yeah. so quotes is "the same", but spaces makes this a hell
I wish you luck with Python
I find the whole “whitespace is bad” argument ridiculous. Every IDE in the past 20 years formats whitespace for you, exactly the same way that python does. You just don’t have brackets that define the start and end.
Exactly that. If maintaining consistent whitespace is a problem, then I contend that other code that you've written is probably hard to read and would benefit from attention to whitespace and indentation
In other words, it enforces conventions that really should be used anyway
After writing a Python integration, it was annoying to have to add all the curly braces in the accompanying JS-based card
I want to toggle my kitchen lights together with secondary lights in the kitchen area. If I just do toggle then if not all switches are in the same state I will not have all on or all off. I am trying to script it so it toggles only the main lights and sets the other lights to match. I think its done right but it does not work, the switches are out of sync.
- service: homeassistant.toggle
entity_id: switch.kitchen_lights
- service: homeassistant.turn_{{ states('switch.kitchen_lights') }}
entity_id:
- switch.kitchen_accents
- switch.kitchen_porch
Could it just be that the state does not get changed right away in the first service call?
After the update to 2022.6. Sensor -template: rest with resource are not working. Is there any breaking changes to update the format?
The services are processed immediately after each other, it is quite possible the results of your service call hasn't been processed yet.
I would suggest you set a variable with the current state before the toggle action, and do the opposite of that state to the other entities
I think you're right, because I added a delay: 00:00:01 and it worked. I was looking into some kind of wait_for_... to detect when the state changes do the delay does not need to be noticeable.
Why not the variable?
sequence:
- variables:
current: "{{ states('switch.kitchen_lights') }}"
- service: homeassistant.toggle
entity_id: switch.kitchen_lights
- service: homeassistant.turn_{{ 'on' if current == 'off' else 'on' }}
entity_id:
- switch.kitchen_accents
- switch.kitchen_porch
Yeah, I'm doing that now. I didn't realise about variables so I was thinking that before I read your message.
Ah, okay 👍🏼
You basically don't need the toggle action then, you can add the kitchen lights to the other action
that's a good point, I am anyway doing the toggle logic...
Is there a way to debug scripts? It was not working at all without the toggle service, and with it only the main lights are toggling nothing else. 😦
variables:
initial_state: "{{ states('switch.kitchen_lights') }}"
sequence:
- service: homeassistant.toggle
entity_id: switch.kitchen_lights
- service: homeassistant.turn_{{ 'off' if initial_state == 'on' else 'on' }}
entity_id:
- switch.kitchen_accents
- switch.kitchen_porch
The scripts also have a trace
Well I'm on mobile, the app doesn't show the colors then. But the built in YAML validation is also nice
Its working, I am not sure what was wrong but the script was not reloading because of an error, but it didn't notify me (usually in automations that have an error I get a notification that its not reloading). I think I needed to switch the quotes on the template of the variable.
I now have single quotes on the outside and double inside. and its working
I've noticed that as well, that it sometimes doesn't really notify on errors in scripts, and just keeps the script as it was before the changes. A config check works though.
The quotes shouldn't be the problem though
Hey TheFes this is rendering a next_start of null?
https://dpaste.org/3mdsb
im have a list of entities that match certain attributes, lets make it 3 for simplicity's sake: [front door, side door, front window] How can I change this to a string that say "front door, side door, and front window"?
full use case, to avoid xy problem. i want to send a single notification when I leave my home zone, for all entities that match a condition, to say "x, y, and z" are open
The 'and' is going to be annoying, but |join(', ')
{% set data1 = ['foobar'] %}
{% set data2 = ['foo', 'bar'] %}
{% set data3 = ['foo', 'bar', 'blah'] %}
{% set data = data3 %}
{% if data|count == 1 %}
{{ data|first }}
{% else %}
{{ data[:-1]|join(', ') }} and {{ data[-1] }}
{% endif %}
Anyone around who is good with multiscrape ?
thanks. whats the : mean in [:-1], all except?
All except the last one
Because you don't check for the correct hours list in the next_start template
Oh yes, what would that be to fix it? Just reuse this? Or a more elegant way?
{% if now().weekday() in [0,2,4] %}
{% set hours = this.attributes.hours_mwf if this.attributes.hours_mwf is defined else [] %}
{% elif now().weekday() in [1,3] %}
{% set hours = this.attributes.hours_tt if this.attributes.hours_tt is defined else [] %}
{% else %}
{% set hours = this.attributes.hours_weekend if this.attributes.hours_weekend is defined else [] %}
{% endif %}
this.state.hours?
Just use the same as for the state template.
Or create an attribute hours and select the right one there
Sounds good. Any idea how to use the next start in a script to check the weather conditions between now and next_start? https://dpaste.org/TAnAg
Yes, but you've made a bit hard on yourself by the way you build your list for the hours
But I don't have time right now to go into that further
because there's no :? Ex. 530 vs 5:30? I'll check back another time not a problem.
Is there any way to reject all entities that does not have area defined? I tried this, but I don't think it works:
| rejectattr('entity_id', 'in', area_entities(''))```
@iron bison posted a code wall, it is moved here --> https://hastebin.com/juzumiliju
the main question there is:
- if: **# How do I check the wait.trigger = none?** - condition: template value_template: ''
any help is appreciated
hi guys,
Where can I find what's the syntax for using templates?
i.e. why there are 2 {{, what other actions/checks/methods are available besides e.g. "{{ is_state(... "?
I'm a bit lost in the documentation and the examples are not always applicable to my use-cases
I'll repeat
Jinja Template Designer Documentation
Much of the power of Jinja comes from its filters and tests.
For more examples and samples, visit see this page.
thanks
Because that's the syntax...
I understand any programming language has a syntax, I didn't know where to look, or what programming language that is
so everything from jinja is available in HA?
@inner mesa so is following correct to check if wait.trigger = none?
- if:
- condition: template
value_template: '{% if wait.trigger is none %}'
- condition: template
thanks a lot!
{{}} returns/outputs something, {% %} is for logic
appreciate the help!!
Can someone explain why this is evaluating true when it should be false? Everything looks right to me.
Trigger information below:
https://www.toptal.com/developers/hastebin/yulayudavo.apache
Can someone please assist me with adding the current time to the end of this template? I'm trying to make something to display on the home page of my tablet home view.
friendly_name: "TOD Greeting"
value_template: >
{%- if now().hour < 12 -%}Good Morning, the time is now
{%- elif now().hour < 18 -%}Good Afternoon, the time is now
{%- else -%}Good Evening, the time is now{%- endif -%} ```
Because you're not surrounding strings in quotes
lock and manual are strings
{{ now() }}
Ok thanks
Thanks Rob, that's definitely progress, any idea how I can format it to be something more easily readable at a glance, something similar to 10:23 AM Saturday, June 11
Yes, with strftime
I'll start googling, thanks!
Nice it looks like something like now().strftime('%H:%M')
Yep
Alrighty, one final question and then I'll have this nailed down, I ended up with this, how can I force the time/date bit to be on a seperate line? My end goal is to display this in a card. tod_greeting: friendly_name: "TOD Greeting" value_template: > {%- if now().hour < 12 -%}Good Morning, the time is now {%- elif now().hour < 18 -%}Good Afternoon, the time is now {%- else -%}Good Evening, the time is now{%- endif -%} {{ now().strftime("%H:%M%p on %b %d, %Y") }}
After googling it looks to be problematic to add a new line to a template, maybe adding it to the card markdown is a better bet.
Depends on the card. <br> may work, or \n
I'm trying to put this into a button card at the moment, i'll give that a shot
@inner mesa Adding <br> to my template worked and shows a new line in the button card. I appreciate your help.
value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Sunrise"] | timestamp_custom("%H:%M") }}'
After the core update above template for sensor is showing error with ‘no default was specified’ Please, anyone help me on this template working.
Mqtt?
if I used this as a trigger:
- platform: event
event_type: timer.finished
event_data:
entity_id: timer.mailbox
Can I use this as a condition template:
{{ trigger.entity_id == 'timer.mailbox'}}
entity_id is not an option
You can get to it through event_data, but you might as well use a trigger id
So I would define id: in the trigger and use trigger.id == my_trigger_id`
Or a regular condition that checks the ID
i made a template to say when the rain will stop/start but i feel like there might be a way to make it work better internally, does anyone have any ideas?
https://hst.sh/aqiliguwag.txt
im working on smth on my own rn
how do I do a 'less than 10 for 1 minute':
{{ states('sensor.energy_monitor_smartplug_watts')|float < 10 }}
Create a binary sensor using this template, and then use last_changed
ah - is that the only way?
Yes, because if it changes from 9 to 8 for example, your template is still true, but last_changed will get a new timestamp
ah good point - thanks
{{ as_timestamp(now()) - as_timestamp(states.sensor.washer_dryer_watts_10.last_changed) < 60 }}
does that look right?
I want it to trigger the automation after the watts go above 10 for 10 minutes (that makes it certain the the washer/dryer is on)
then I want it to wait for the watts template sensor to be true for 60 seconds before sending the message
No need to use timestamps, I would expect a binary_sensor here
{{ (now() - states.sensor.washer_dryer_watts_10.last_changed).seconds < 60 }}
does it matter that its not a binary? it will still show False/True right?
Binary will be on or off, but sure, you can use a normal sensor as well
With a binary sensor you could also add a delay in turning it on (10 minutes) and off (1 minute) and just use the state changes
But based on your explanation you want it to be < 10 for more than 60 seconds, not less
You can simply use holding the state as well then
I've changed it around a bit:
- name: "Washer/Dryer Status"
availability: "{{ not is_state('switch.washer_dryer_smartplug', 'unavailable') }}"
delay_on:
minutes: 10
delay_off:
minutes: 1
state: "{{ states('sensor.washer_dryer_smartplug_watts')|float > 10 }}"```
hi all. i have this template in the dahsboard card
{% if is_state('light.office_fan', 'on') %}
orange
{% elif is_state('binary_sensor.frontdoor_contact', 'off') %}
grey
{% endif %}
is there anyway to get the current bulb color to show instead of a static orange etc?
thx alot!
templates aren't available in the frontend, so you must be using something custom. Secondly, the light has RGB attributes and you can convert them to a color.
rgb({{ state_attr('light.office_fan', 'rgb_color') | map('string') | join(',') }})
how can I make this work:
{{ as_timestamp(state_attr('calendar.holidays','start_time')) - timedelta(hours = 3) }}
I'm getting error; "TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta':
I want to use it with {{ now() }}
as in:
>=
as_datetime(state_attr('calendar.holidays','start_time')) - timedelta(hours = 3) }}```
?
Yes, but calendar triggers support offset in 2022.6
I need it in a condition - theres no offset for condition right?
this is my code:
https://www.toptal.com/developers/hastebin/jadulupide.yaml
I am using the offset for the trigger but I need it for the condition
{{ now() >= as_datetime(state_attr('calendar.holidays','start_time')) - timedelta(hours = 3) }}
get me: "TypeError: can't compare offset-naive and offset-aware datetimes"
Add as_local then
{{ now() >= as_local(as_datetime(state_attr('calendar.holidays','start_time'))) - timedelta(hours = 3) }}```
ah that works great - thank you
for my Option 2 - can I just have
as_local(as_datetime(state_attr('calendar.holidays','end_time'))) + timedelta(minutes = 1) }} without the now() ?
or should I just have
{{ now() >= as_local(as_datetime(state_attr('calendar.holidays','end_time'))) + timedelta(minutes = 1) }}
What is option 2 again? If it is a condition, it has to evaluate to true or false
cool @mighty ledge ! indeed im using the custom mushroom card. im still a bit unclear though on how to use the rbg attribute you pointed out. is this the correct way:
@proper ore posted a code wall, it is moved here --> https://hastebin.com/upewekidij
It went to "true" but it didn't trigger:
https://www.toptal.com/developers/hastebin/jonudaricu.yaml
@dark rock posted a code wall, it is moved here --> https://hastebin.com/vajotesudo
What went to true? There is no template in your trigger
the condition went to true but the trigger didnt fire even though its basically the same as the condition
If I use a trigger for a template sensor
- trigger:
- platform: state
entity_id: sensor.foo
sensor:
- name: Bar
state: >
{% if is_number(trigger.from_state.state) and (float(trigger.to_state.state,default=0) > float(trigger.from_state.state,default=0)) %}
where sensor.foo is a REST entity. Why I'm getting UndefinedError: 'None' has no attribute 'state' during startup. If it has no state, the state trigger should not fire, shouldn't it?
And which part is causing the error? Is there any way to see it?
Hi. Didn't found in HA documentation - is there a Python file counterpart for automation, script filenames (or automation/script id or name) to use it in error messages or templates?
default:
- service: persistent_notification.create
data:
title: "!!! script.maindoor_handler - unknown command: '{{command}}'"
replaced to
title: "!!! {{file}}} - unknown command: '{{command}}'"
test_msg:
sequence:
- service: persistent_notification.create
data:
message: "script: {{ this.entity_id }}"
Script variables that may be used by templates include those provided from the configuration, those that are passed when started from a service and the
thisvariable whose value is a dictionary of the current script’s state.
Many thanks :-), this is exactly what I'm looking for. I have noticed 'this' object in manual, but never try to read about it. My fault.
Any chance that there is also ... C language assert() macro counterpart?
You could do an if/then with stop: https://www.home-assistant.io/docs/scripts/#stopping-a-script-sequence
On startup your rest sensor will get an initial state, the from_state will be empty then
Add not_from: [ 'unavailable', 'unknown' ] to the trigger
Thanks. Can somehow understand and thought this, but do not really "agree" to the logic, because if there is a state trigger = state change, it is not logical, that there is no from_state.state. If it would be None or whatever, but completely no state of from_state or no from_state seems to be not logic. Same problem in my mind with you not_from. If there is no from_state, why can I check with not_from to a value, if there is no from_state?
I don't think testing the value will work if there's no previous state. This is what I do:
condition:
- "{{ trigger.from_state is not none and trigger.to_state is not none }}"
- condition: template
value_template: >-
{% set to_state = trigger.to_state.state|int(0) %}
{% set from_state = trigger.from_state.state|int(0) %}
{{ (from_state != to_state) and (from_state > 0) }}
Currently I have a if trigger.from_state and trigger.to_state around and it is working now. But still curious that in such cases from_state.state is not there instead of e.g. "intial", "n/a", None
All of those things are arbitrary
if there's no previous state, there's no previous state
Is it allowed to up questions? At least perhaps one time after some days as here?
you cannot get translated states in a template
Grrrrrr. What a pity. But thanks for the info/confirmation. Any Improvement requests I can vote for? 😉
you can look
If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.
you can do your own translation for display, but using consistent states makes more sense in logic
Did that ofc before. Should be only a joke. At least didn't find.
Aaah. Found this one now.https://github.com/home-assistant/core/pull/65743 Hopefully reviewed and merged somedays.
Hi, I'm here again seeking for help. I was doing a condition to run an automation every two days (found here https://community.home-assistant.io/t/automation-every-2-days/321327 ) and when I paste the condition it shows this error:
Message malformed: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['condition'][0]['value_template']
Automation yaml in here: https://pastebin.com/DSuEUBRr
You're using the same type of quote inside and outside the expression
how do you use an input selector in a blueprint automation in a jinja template?
{{ (state_attr('sun.sun', 'elevation') - !input 'min_sun_elevation') / (!input 'max_sun_elevation' - !input 'min_sun_elevation') * (!input 'max_color_temp' - !input 'min_color_temp') + !input 'min_color_temp' }}
is that valid?
you can't
can I make a variable with the input to use?
the only option is to plop the selector into a variable and then use the variable
@mighty ledge so is this how I'd set the variables in the blue print?
variables:
- min_sun_elevation: !input 'min_sun_elevation'
- max_sun_elevation: !input 'max_sun_elevation'
- min_brightness: !input 'min_brightness'
- max_brightness: !input 'max_brightness'
- min_color_temp: !input 'min_color_temp'
- max_color_temp: !input 'max_color_temp'
no, remove -
then {{ min_brightness|int }} ?
thanks, it's helpful having your experience to get me over this hurdle
np
I had one other weird issue w/ selectors maybe you've seen before
I used:
input:
min_color_temp:
name: Minimum Color Temperature
description: Color Temperature to use with lights when the sun is lowest on the horizon.
default: 370
selector:
color_temp:
min_mireds: 173
max_mireds: 370
And the color temp picker says undefined* up where in other areas of the UI it says 'Color Temperature' on other color_temp inputs like on a device's settings.
Sorry, cant help with that one
#blueprints-archived perhaps
Hey Petro. I want to use next_start to evaluate the time between now and then against weather conditions. The goal is to make a dynamic HVAC Schedule. This is not proper formatting just thoughts and placeholders for temperatures so that I can fix in the future as I figure out what I want. Is this possible to evaluate the weather conditions in the time between now and next_start? I brought in some stuff from a previous script you helped with related to the weather tts script.
https://dpaste.org/C02yr
yeah makes sense @inner mesa I started there for the issue @mighty ledge helped with
Hello guys,
i am just a bit lost. I searched the web upsidedown but cant find an answer. So i like to try it here:
I cant get my "wait_for_trigger" working. I try to compare two sensors and if thats true, it should trigger the trigger.
I currently have:
action:
- wait_for_trigger:
- platform: template
value_template: >-
{{ states('sensor.innen_temperatur') | float >
states('sensor.aussen_temperatur') | float }}
continue_on_timeout: false
timeout: '12:00:00'
- platform: template
first:
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
second, that won't "trigger" if it's simply true, it has to transition from false to true
Developer menu shows that the value template returns true / false, so that does not seem to be a problem.
I see. I will formate in the future.
Ok i see the problem now.
Thanks for helping.
So seems like this should work, however i just can not test it because i can not make the value change.
you can always test by changing the value(s) in
-> States
ah nice, i did not know that.
One last question: What happens if the "wait_for_trigger" gets probed while the value template is already true? Is the timeout still active and waiting for a transition from false to true? The step details do not seem to show that the timeout is running. So i assume it just gets canceled?
Is the timeout still active and waiting for a transition from false to true?
yes
you told it to wait for a trigger and the trigger hasn't happened
The continue on timeout needs to be true to continue.
Thanks again!
I think got everything figured out with your help!
Nice evening to everyone!
@mighty ledge thanks, I submitted my blueprint with your help: https://community.home-assistant.io/t/motion-sensing-and-illuminance-threshold-based-lights-automation-that-dims-and-changes-color-temperature-according-to-sun-elevation/430415
It seems when using "utcnow" in the template editor in dev tools, you ALWAYS have to wait for one minute for the template to evaluate. I understand why but surely it should re-evaluate whenever you edit the template? There seem to be some cases where it does evaluate or even partially evalute the template on edit, but I cant follow the logic. Really confusing when your edit immediately results in an error, but one minute later is correct.
And there also appears to be some weird browser caching issues where I return to a browser tab that previously evaluated utcnow correctly and now it shows the results from a previous template, then after one minute -evaluates correctly again.
OK This seems to be a minefield when using sensors and times that update at different times. I'll just try to be aware of it and not get misled by unexpected results. Restarted my browser (and PC to be safe) and issues disappeared. I wish I had figured this out 6 months ago. Has probably cost me days and much frustration. Live and learn.
why does the following evalute true in dev template for an entity_id of null: {{states.group.person.attributes.entity_id==None}}
but in an automation '{{trigger.from_state.attributes.entity_id==None}}' evaluates as false for the follow from_state:
from_state:
entity_id: group.person
state: home
attributes:
entity_id: null
order: 0
friendly_name: home group```
So, what should i change? I'm really lost here 😔
Use double quotes outside and single quotes inside the template
Or the other way around
If i put the automation like this:
"{{ as_timestamp(now()) - as_timestamp(state_attr('automation.riego', 'last_triggered')) > 172800 }}" or
''{{ as_timestamp(now()) - as_timestamp(state_attr('automation.riego', 'last_triggered')) > 172800 }}''
(First is double quote character and second is two single quote char)
Error is: Error occurred while testing condition
template value should be a string for dictionary value @ data['value_template']. Got None
If i put it the other way (single outside, double inside), error is the same. I'm sure I'm doing something wrong, but i can't find what.
Automation code is here btw: https://pastebin.com/DSuEUBRr
@marble jackal
Check the first pinned post here
Just checked the pinned post.. You meant the issue on github, right?
The template on template editor is ok, it's just the test button then. Thanks
It's not working sadly
What is not working?
The template works in
>Templates you just said right?
And you are using different quotes inside and outside the template now
You are not in the code you linked above
Condition under automation is not working. If i put the template under the template checker it says "true" (which indeed is beacuse the now time - last time triggered is greater that the delay).
I have runned the automation in order to check if it's going to work and it gets "rejected" because the condition is marked as false. Maybe is something with the formating?
"New" code is here:
https://pastebin.com/qJrvGVyL
@dark rock No, it's because you are checking if your automation has triggered over 1000 seconds ago in the same automation which has just triggered
that will never be true
Fortunately this.attributes.last_triggered will contain the timestamp you actually need
This template returns "Result type: list", as can be seen in the link below.
{{ state_attr('weather.home', 'forecast') }}
Result: https://dpaste.org/mVWV5
How can I extract from this entire result only certain lines, eg. line 3,5,6 (tomorrows weather).
Thx.
{{ state_attr('weather.home', 'forecast')[0].temperature }} for temperature 🙂
thanks a lot. very hard to find that out via google 😄
well, with [0] you take the first item out of the list (which is tomorrow). And then you can take out the different values by using the key
easy to see now, that someone (you) pointed it out. now its obvious 😄
Do you have time to assist me with this today or another time?
Well, it's a getting more complicated every time I help you add something. What are the plans after you have the weather in?
@marble jackal That's it. I just needed to get the temperature from the first part. Then off that see if any adjustments are made based off when the next start is and the weather. The rest I can handle as they aren't super complex variables.
Well, if you replace your current hour format to "07:30" you could just use today_at on the next_start variable
and then you have a timestamp which you can use to get the weather conditions
I copied that state template format from a post on the forums from taras, I didn't know if 7:30 could be used in [07:30, 08:30, 63]
{% set t = now().strftime('%-H%M') | int %} change this to {% set t = now().strftime('%H:%M') %} in both templates (for state and next_start) to have them working with the new time format
use quotes
and a 0 like the example I just gave
otherwise a string comparison will not work
Like that? 07:30
["07:30", "08:30", 63]
Yep I just realized what you meant by quotes. That's also more readable than 630 lol
You might want to use single quotes though (or replace the quotes outside the template to single quotes)
I see and will going all the way to 00:00 ["18:45", "23:59", 63] still be necessary, ["00:00", "05:30", 63]
Yes
I see, I wasn't sure if changing to a proper format negated the need for that.
Well, you totally have to rebuild the hours format to something else to remove that need
It's ok
you can change {{ (hours[index + 1] | default(hours[0]))[0] }} to {{ (hours[index + 1] | default(hours[1]))[0] }} so it won't report 00:00 as next_start
I'll do that
That is not true. Time now - last triggered is 1832819 as estated by template editor
Oh, i just understand what you're saying here.
So, would you mind sharing how the template will be? I don't know how to write it :(
In the ha forum post I shared the solution seemed to work for the fella asking there 🤣
Use this.attributes.last_triggered instead of state_attr('automation.riego', 'last_triggered')
Same thing :(
"{{as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1000}}"
hi, im trying to cost up the energy consumption "live" for a device in the house ive currently got this template
£ {{(states('sensor.plug_this_month_energy') | float * 0.07319) | round(2)}}
which is using a harcoded unit cost and thats working fine
however ive built a helper to do this for me so i dont have to change it in a million places
which is input_number.electricitycost
so i thought i could do this
£ {{(states('sensor.plug_this_month_energy') | float * states('input_number.electricitycost') | round(2)}}
but this doesnt work?
Are you sure it didn't already trigger less than 1000 seconds ago
What doesn't work, the whole calculation, or rounding it to two digits?
{{as_timestamp(state_attr('automation.riego', 'last_triggered')) }} on developer tool reports 1653282000.005644.
now reports 1655116963.71484
difference is 1834974.4528038502
the rounding works fine without the helper, but with the helper i just get this
i cant paste image haha
well it just seems to ouput the template
so just £ {{(states('sensor.plug_this_month_energy') | float * states('input_number.electricitycost') | round(2)}}
.share the entire yaml
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Ah you actually fixed the round, and that broke the template
because now you are not casting the input_number to a float
{{(states('sensor.plug_this_month_energy') | float * states('input_number.electricitycost') | float) | round(2)}}
in this one you were missing a closing bracket
i thought i was missing a float but couldnt work out where or how to format it
youre a star
How would I implement this? To get the weather conditions between now and next_start? Not just the weather at next_start but between now and then. That way I could say if between now and next_start ever goes above 80 degrees do x.
Hmm, there is something fishy here in that condition.
{% set this = {
"entity_id": "automation.zz_automation_for_quick_tests",
"attributes": {
"last_triggered": "2022-06-01T06:37:40.686363+00:00",
}
}
%}
{{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1000 }}
This is using the data from the test condition trace I just created
in
>templates is returns true however in the condition it returns false
yep
been stuck there for about a week before asking here
I know how to do this in a different way, with two automations and some input_helpers.. but this should be done in a more elegant way 😁
I wasn't sure and I don't want to be the "guys who raises issues just to seek for help"
😁
i just solved it in the more simplistic and idiotic way possible
if the template value is wrapped around int casting it just works 😮
{{ int(as_timestamp(now())) -
int(as_timestamp(this.attributes.last_triggered)) > 1000 }}
maybe its unable to compare as_timestamp to 1000 as it returns a float ?
No, it wouldn't have worked in devtools then
yeah, that is. i just checked with value_template: '{{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1.0 }}' and it also works
Great Scott! (and @marble jackal for all your help)
Does that work in your automation?
hmm, strange
but okay
still a bug I would asy
say
Todays date is {{ now().date() }}
Last time the vacuum robot ran was {{ states('input_datetime.staubilastruneingang')[0:10] }}
It would be great to get the delta/difference from these two dates. eg: 1, when it was running the last time yesterday.
Any idea how I can compare two dates, or any other template-idea on how to extract the information how many days it has been since a certain script was run?
You know why this isn't working?
becasue you put quotes around your template and you are also using the multi line notation
yes, it is.
not me, it putted like this automatically.
Then you put quotes around the template in the GUI
but that is why that one isn't working
hasn't got anything to do with the int
i did that already in the guy. then changed to yaml mode and its automatically set like that
Check the trace for a faulty one, it probably has something like value_template: '"{{ template }}"'
yes, you should not put quotes around your templates in the GUI
the GUI will do that for you, if you also do it, it will double quote it, and treat it like a string
Yes, that's what I said, don't put quotes around it
https://ibb.co/VSpLzhW a faulty one
condition:
- condition: template
value_template: >-
"{{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1000 }}"
ok
That one is incorrect
condition:
- condition: template
value_template: >-
{{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1000 }}
condition:
- condition: template
value_template: "{{ as_timestamp(now()) - as_timestamp(this.attributes.last_triggered) > 1000 }}"
these 2 are
great, thank you so much. Just understood the difference
as the gui/yaml was different it was weird and lead me to not be sure
thanks again for your help
also, when i started doing this automation I tried the test button without knowing that it was bugged as you reported
{% set weather = 'weather.climacell_hourly' %} {# change to your own weahter entity #}
{% set next_start = '15:00' %} {# replace with a reference to the attribute of your sensor #}
{% set forecast = state_attr(weather, 'forecast') %}
{% set n = today_at(next_start).astimezone(utcnow().tzinfo).isoformat() | string %}
{{ forecast | selectattr('datetime', '<=', n) | map(attribute='temperature') | max > 80 }}
That returns true if there is a temperature between no and next_start above 80
If I wanted to add multiple conditions (if, elif, else) to this rather than just above 80 what would I need to do?
{% set weather = 'weather.climacell_hourly' %} {# change to your own weahter entity #}
{% set next_start = '15:00' %} {# replace with a reference to the attribute of your sensor #}
{% set forecast = state_attr(weather, 'forecast') %}
{% set n = today_at(next_start).astimezone(utcnow().tzinfo).isoformat() | string %}
{% set temp_max = forecast | selectattr('datetime', '<=', n) | map(attribute='temperature') | max %}
{% set temp_max = forecast | selectattr('datetime', '<=', n) | map(attribute='temperature') | min %}
use temp_max and temp_min in your statements
If 80 is <= temp_max or >= temp_min for example?
for example
you could also do someting like
{% set temp = forecast | selectattr('datetime', '<=', n) | map(attribute='temperature') | list %}
it will list all temperatures between now and next_start
I just based it on the information you've given, that you wanted to check if it ever went above 80
I know I only gave 1 temperature I am not 100% sure how I want to do it, just good to have options. If I use the list, what would the if,elif statement be?
I would not know without you telling me what you want to achieve
Let's say
{% if the temperature between now and the next_start is <= 55 and > 50 %}
{{ operating_temperature - 1 }}
{% elif time between now and next_start <= 50%}
{{ operating_temperature - 2 }}
{% else %}
{{ operating_temperature }}
{% endif %}
what is the temperature? there could be multiple temperatures between now and the next_start
I see, so I need to figure out max and min as you stated and then determine if any are leas than or equal to 55 and greater than 50 for example.
using the list option, you could do this:
{% if temp | select('>' , 50) | select('<=', 55) | list | count > 0 %}
And if > 0 then it returns true right?
yes
Perfect. This is exactly what I needed thank you as always. You need to have a buy me a coffee link or something.
There is one on my Github profile (which I link to from my profile here) if you really want to, but don't feel obliged
Hi Everyone!
This is probably a pretty stupid question, but I’m a bit at a loss.
I followed a guide how to use license plate recognition in HA.
I got everything up and running. When I run the service in Developers Tools I get this output in states:
https://imgur.com/a/VP5uc7O
Now I would like to use this information to check if it’s a plate that is allow so I trigger my gate.
Trigger: When last_detection is changed
Condition: Plate is true to some value
Action: Open Gate
The trigger and action I figured out.
But I’m not sure how I would go and check if it’s the correct plate
https://imgur.com/a/PirxWvl
https://imgur.com/a/CATctwg
what is your actual trigger here? Is it a state trigger?
Yes whenever last_detection changes
you could use:
condition: template
value_template: >
{% set allowed_plates = [ 'abc123', 'def456' ] %}
{{ state_attr('image_processsing.whatever', 'vehicles')[0].plate in allowed_plates }}
Man if this works you are a legend
I tried it, but it does not seem to work. When I click "test" I get this message:
I turned off the Date/Time on the camera stream because I scans it too. Output looks like this now:
https://imgur.com/a/be3GFuv
Check the first pinned post here
Yea I already seeing some mistake I made. Going to copy your code in the automations.yaml file instead of the GUI
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
I think it works. Thanks!
If i have a jinja template like:
{%- if is_state('binary_sensor.person_2_in_bed','on') %}
{{ ' ' ~ name2 ~ ', ' }}
why do I have to concatenate ' ' in front of a variable (name2) for it to work
' ' is just a space but could be any string
you don't have to. You have something wrong with your template and you aren't providing enough of the template for us to answer the question.
it's passing the template to a input_text which sends it off to an aws skill lamba. I think it's just the configuration the way it works
Thought i was going nuts
That info probably would of helped...telepathy again
that still doesn't help, where is name2 coming from and what's it's type
Got this error when I restarted HA. I'm guessing it's because Zigbee2MQTT didn't reregister the object in the MQTT running in HA yet? What do I need to wrap the function with just to avoid the error?
homeassistant.exceptions.TemplateError: ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ (states('sensor.compressor_inside_temp_temperature')|float - states('sensor.sonoff_temp_2_temperature')|float ) > 2.0 }}' but no default was specified