#templates-archived
1 messages · Page 126 of 1
Gotcha, I'll go look. Maybe I am using light.turn_off with a group.
Odd, I use light.turn_off exactly once in automations, against a light and not at all in scripts. I use homeassistant.turn_off for groups. Yet, I get this error in the logs: Error executing service: <ServiceCall light.turn_off (c:f2faf8ad3b870a7fb2535d7e180e9133): entity_id=['light.dining_hallway', 'light.dining_sitting_area', 'light.dining_table_spots', 'light.kitchen_bath', 'light.kitchen_hallway', 'light.kitchen_work_area']>
I'm passing a group to a script that uses the above templates
You’ll need to share what you’re actually doing
automation: ``` action:
- service: script.turn_off_only_if_on
data_template:
entity: group.dining_kitchen_lights
script: ``` sequence:
# make sure the entity is on else quit (condition)
- condition: template
value_template: "{{ is_state(entity, 'on') }}"
- service: homeassistant.turn_off
data_template:
entity_id: "{{ entity }}"
- wait_template: "{{ is_state(entity, 'off') }}"
timeout: '00:02:00'
Far as I know, that's the only place I use that group of entities (shown in the error message). Yea, I only use light.turn_off in one place, against a single light. I'll have to dig more I guess.
Here's the full log entry. It looks like my script, with the group, does get run and somehow homeassistant.turn_off morphs to light.turn_off. Perhaps zwjs is doing this? https://paste.ubuntu.com/p/7Ky2F49NRs/
Could be. It will internally call the turn_off service of light
Try it from
-> Services and maybe file an issue
Hey templates, I am looking for a little bit of help trying to figure out how to build my list of entity ids in my template. I receive the following error when checking my configuration file:
2021-05-12 15:32:21 ERROR (MainThread) [homeassistant.config] Invalid config for [automation]: not a valid value for dictionary value @ data['action'][0]['choose'][1]['sequence'][0]['target']['entity_id']. Got None. (See /config/configuration.yaml, line 35)
https://paste.ubuntu.com/p/MHdZfjRDTx/
Get rid of the leading ‘-‘ in each one. And I’m assuming that target: accepts templates, which I haven’t tried
removing the -s didn't help.
I just tried the group in services, and no go. A single light works fine as a target to homeassistant.turn_off.
Try changing target: to data:
Check for an existing issue and file one if not
slightly similar error:
2021-05-12 15:40:33 ERROR (MainThread) [homeassistant.config] Invalid config for [automation]: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['action'][0]['choose'][1]['sequence'][0]['data']. Got None. (See /config/configuration.yaml, line 35).
You’re missing a %
I see the same behavior as my previous code where it still seems like it's trying run another automation while running this one (I think this is looping itself somehow)
Well, yeah
Using data: it finally turned off, but it took a while...
I want it so if you change either of those entities (on, off, brightness) it would fire and "sync" the other entity. I'm not sure how I am going to set the property of the other entity without it firing off another automation?
the way it's written, it's going to go poorly
do associations sync brightness?
I tried group -- it doesn't sync brightness
light.group, then
Switching to use a group as the entity_id I see the same thing
Groups aren't the same as light groups. Follow the link Rob just shared.
Back to templates, should I use data_template: here for my group entity, or data: in a script? - service: homeassistant.turn_off data_template: entity_id: "{{ entity }}"
Its (recently) been failing this way. If it hurts, change it, I guess. We'll see
@ivory delta same problem using light group. It seems to actually be worse using the light group unfortunately.
So, how do data: and target: differ?
I don't know what the point of target: is. maybe for devices? it's fairly recent, and you can always use entity_id to specify what you want to affect
data: just starts a generic data block
Is service_template deprecated as well?
Thanks, while he's {cleaning up some templates in scripts}
if you use VSCode with the Home Assistant extension, it makes it quite clear that they're deprecated
Hmm, been using vim. I'll look into VSCode.
vim 😍
Big step above ed on a 1200 baud modem
@inner mesa is the extension for vs code the Home Assistant Config Helper? I see syntax coloring, but no intellisense/error highlighting
I need vscode for raspbian buster
I suppose community edition is good enough for us old retired guys (who still use vim).
I'll admit that it lacks the charming snark of Discord, but it's there and it's helpful
GitLens too. Noice.
I love that
I tried adjusting the logic again on this template and what's weird is it turns on one item, but turns off the one that triggered it now 😦
https://paste.ubuntu.com/p/dVW8mDcnnX/
You're just trying to get them to sync?
Yes, sync both on/off and brightness.
While the light group may work via HA app, it doesn't work if I walk up to the wall switch and flip it on.
I do it like this (I don't care about brightness): https://pastebin.ubuntu.com/p/PQYJvZwJsr/
The for: is so they don't get stuck in a loop if I toggle things too quickly (I got bored of my house looking like a disco).
One day I shall have a lounge
You'd use a light group in your action but it's the same idea.
for: "00:00:02"
I think this is the magic piece I'm missing
This bit is also going to save you a bunch of lines:
service: "homeassistant.turn_{{ trigger.to_state.state }}"
Template the service name instead of using a choose:.
The reason why I did the choose is to specify the brightness property. If I leave that in for turn_off I'll receive an error
Do templates support conditional properties?
Maybe not. If it causes problems without a choose, keep it your way.
I think that part (or much) of my issue with passing a group to homeassistant.turn_off is that the group includes both lights and switches (hence my choice of generic service). When HA morphs ha.turn_off into light.turn_off, switches may cause a problem. Grasping here.
No, that service is generic and can perform any generic on/off/toggle on anything in the group.
Okay, Thank you very much. Let me try it now.
Weird, so now I'm seeing new behavior. If I flip the switch on, the other light will go on, but then the switch will flip to off, flipping the other light off.
https://pastebin.ubuntu.com/p/9NF89NcYn8/
I though so too. See the thread above from about exactly two hours ago.
Then you have something else controlling the switch, moo.
Nope... The warning is the same....
Error executing service still? Sounds like the integration can't reach/control one or more of the lights.
@ivory delta this is the only automation I have 😦
@surreal orchid Generally, don't tag people to ask for help - it comes across as bad manners, you’re demanding somebody answers you. It’s different if you’re thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.
Similarly, please don’t DM (direct message) people asking for help. It also comes across as demanding, and means that others can’t learn from what you do.
Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on). When using Discord's new Reply feature it defaults to pinging the person you reply to, click @ ON to @ OFF to stop this - on the right side of the compose bar.
May I ask why my MQTT sensors cannot get values by HA?
They can't? MQTT sensors are commonly used.
I even try to ask for float...
This is my new Configuration.yaml
sensor 1:
platform: mqtt
name: "analog"
state_topic: "M1"
qos: 0
unit_of_measurement: " "
value_template: "{{ value_json.a|float }}"
What's the message on that topic?
My json format message can be heard from the integration
{"id":4CC441123123,"a":1,"a_s":0,"a_1":2,"a_s_1":0,"a_2":1,"a_s_2":0}
When I tried to ask for a gauge, the message on the lovelace is "Instance is not a number".
If I tried to use "Instance" in the lovelace,it will show that the value is unknown.
What's the value of the entity in HA?
sensor.M1
Not its ID. Its current state.
M1
I'd split the 'on' and 'off' parts into separate automations and get it working before getting that fancy.
Where could I show you that?
Dev Tools > States > search for that entity
@drowsy field When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
That's why it's not a number in Lovelace 😉
Uh, then how can I solve it?
IS there anything wrong with my configuraiton.yaml or ?
You probably have the wrong topic.
Uh, I can heard the message with this topic...in Setting->Integration->MQTT setting->Subscribe Topic
That's the full topic? There's nothing before it?
Yes
Have you saved your edits and reloaded MQTT sensors?
I always restart HA
Thanks for the suggestion jumper. Unfortunately, I honestly am so burned out on this and feel so helpless/stupid to use ha I'm at the point of just giving up. It's been two long days of trying and failing and nothing against this discord channel, but I feel like I'm walking on eggshells as it is at this point due to all the rules I've unintentionally broken in these channels.
Don't be so hard on yourself. I found it tricky at first too... at some point, stuff will 'click' and you'll have fun with it.
moo, hang in there. Try indenting your "- platforms:" and children and "- choose: and children. Maybe
I just feel like moo 😥
You could well have triggers that are hitting and causing it all to go wacky. Some delays may help
What is the input of state_topic?
Is it must be "topic"
Or 'topic'
I can see they have difference colors in VS code
Appreciate the words of encouragement, but I'm going to step away for awhile to decompress. One thing I did notice though is if I use the automation ui out of the box, I receive the same "Already running" error... so that tells me that any time a change is made to an entity it will recursively call itself. Would be nice if there was a flag you could add to the template to tell ha to ignore a state change request.
The style of quotes doesn't matter but it's best to keep them consistent.
Take some time out if you need it. Head back to #automations-archived when you're ready to spend more time on it. Mention that 'already running' piece when you continue this.
The problem is I was told to come to this channel from #automations-archived. Which is partially why I feel conflicted responding. I don't want to burn folks out.
Is there any hidden topic prefix possible?
I can really get msg from that topic....Why it can not be get by template?
I think you have the templates part solved. The rest sounds like automations, moo. We try to keep things in the right channels so the right people see it (while answering and for when other people search the history).
You could try using value instead of value_json in your template.
Okay let me try it.
It may be moo that you get into race conditions with these two devices triggering either within the automation. I'd look for a way to have automations for each device separately that gently hit the other one. They may not be instant with each other, but may work.
I got nothing LOL
It's just blank.
Stop tagging me.
I don't know why you're not seeing a value. If the topic is correct, the rest should work.
When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
I know HassBot but where....
Thanks I got it.
Is it possible that my json msg is too long?
No, it's quite short.
Well, actually, I "could" get value from these in Feb...
This was the msg and code I post in here...
#frontend-archived message
I was trying to split my yaml file then.
However, after I update the HA from 5.10 to 5.13.
I even tried to just put all these in the configuration.yaml
HA still can't get any value from it.
I don't know the answer, so I'll let someone else take a look.
Is it possible to use a template for entity_id trigger param in an automation? Like so:
trigger:
platform: state
entity_id: "{{ states('input_select.entity_id') }}"
to: 'on'
input_select.entity_id is just a list of entities
Not to say good news but I may have a clue about this
When I try put publish msg from MQTT broker in HA.
Just purely publish the {"a":10}
Then, the HA can get the value and show it on the lovelace.
Use a template trigger
https://www.home-assistant.io/docs/automation/trigger/#template-trigger or just a trigger for each entity. When you break them out you can do more in your action block depending on which entity triggered the automation.
Yes
Is this the correct syntax?
- platform: template
sensors:
home_secure:
friendly_name: "House Secure"
device_class: lock
value_template: >-
{% if is_state('binary.sensor.doors', 'on') or is_state('binary_sensor.windows', 'on') %}
on
{% else %}
off
{% endif %}
Doesn't seem to be changing the state of the entity.
does it work in developer tools test
should be okay. seems like you want a binary_sensor though
Yeah ^ we're all good in template and no errors in Home Assistant. It just doesn't change anything at all. The windows / doors template changes but doesn't impact the home secure
Ignore my last.
actually, your entities are wrong
It works now
{{ 'on' if is_state(...) else 'off'}}
binary.sensor.doors is probably binary_sensor.doors
^ yeah that's correct
I was hoping to sneak in through a window
Or seems to be the best option just because if a window or a door is open then the house is not secure, the and would mean a door and a window would have to be open no?
depends on what you mean by "on" and "off"
on is open, off is closed.
I just had this philosophical discussion a few days ago, but "on" to me means "closed, secure"
HA agrees with you onthat
it's backward to me
Ah that probably got me too there
@dreamy sinew It didn't work for me. It said entity_id is not valid with the following:
trigger:
platform: state
entity_id: "{{ states('input_select.entity_id') }}"
to: 'on'
I couldn't find any examples with entity_id being computed in an automation
I feel like this would get obnoxious if you add more sensors over time though
Expand to the rescue maybe?
@modern flower what is the output of that template in the tester?
If it works and the logic doesn't make sense 💰
@dreamy sinew switch.living_room
{% set sensors = ['entity1', 'entity2'] %}
{{ expand(sensors)|selectattr('state', 'eq', 'on')|list|length > 0 }}
I don’t think you can use a template in entity_id like that can you? He is trying to use the state of an input_select
Without a template trigger at least
Ah maybe, haven't messed with that in a while
No, I am trying to get the state of the entity that's currently selected in the input_select
like the input_select has a bunch of entities and I want the automation to use whatever is selected as opposed to hard coding it.
Is logic for setting entity_id in a state condition supported in templating? Each time I try to check if my template is valid, it says the value is None but if the logic were to run it would have a value
It does not work for me
I am trying to figure how to do operations on turned on lights only. I want it to be dynamic, and only have this so far https://paste.ubuntu.com/p/xkdq92g3Pr/ I believe I need to "grep" entity_id's into some sort of list to loop through for adjusting the lights?
hey, is it possible to get the device name from device_id or otherway around?
Use the friendly_name attribute.
you mean like that?
{{ state_attr('d0d9f6e7cf75cee5cf1e41692c6b0a3e', 'friendly_name') }}
this does not work
Does it work in the template editor?
Auh, maybe it is not possible
Is there a reason you are using device id over the entity id?
I`m using ESPHome with custom events and want to trigger automations based on these events. The Idea was to send the host name in the event data to determine which ESP sent it
maybe there is a better way
Is last_changed a default hidden attribute for entities?
It's not an attribute. It's a property.
What is the proper format to use it? As this doesnt work -> {{ states('person.bieke.last_changed') }}
I want to use different if statements based on when this person last changed its position
{{ states.person.bieke.last_changed }}
Here's a great post about it: https://community.home-assistant.io/t/automation-based-calculated-variables-times/81285/9
Cheers, that does indeed work
https://paste.ubuntu.com/p/dkd7qxfpkq/
Text is what I want to archive, bottom is what I've tried to make of it. First time ever doing templates so still lots to learn and lots of things unclear to me. How to best handle the time condition? I tried to format as you can see on the bottom but that does not work, any help?
@inner mesa Just wanted to thank you again, and let you know there is a neater way to accomplish this (without a helper) https://paste.ubuntu.com/p/dgf359KJrj/
Sure, that’s only in the context of that script
Noted, but that's all I need. It went belly up when all rooms used the same helper, so instead of creating one for each, I tested this... 🙂
Those are a relatively new invention and I didn’t even think about it
Aha, cool! Really didn't think I invented something, but wanted to let you know I appreciate the help I get and will try to return if I can... 🙂
Look at this
#templates-archived message
Might solve your issue using variables.
Hello everyone. I am trying to set a timer for our airconditioning unit to see how much time left before it turns off. I want the timer to get its duration from the input datetime but i cant get it to work. here's my attempt. thanks
timer:
aircon_timer:
duration: {{states('input_datetime.aircon_timer')}}
name: remaining time
icon: mdi:air-conditioner
You can’t just use templates anywhere, so you need to review the docs to see where they’re allowed
In this case, you should be able to use the timer.start service to set the duration using a template (because it’s in a data: block), but you need to format it as the service expects
Reworked it, removed the weekdays as that is too complicated for now. This gives an error "TemplateSyntaxError: expected token 'end of print statement', got 'has'", why?
You don’t nest {{}} like that
Also, there’s no context for where that string is being used. It may or may not be valid. Further, you’re converting the time to a string and then trying to compare it as though it’s still a time. You’re unlikely to get the right answer
Right, suppose I can find out how to nest IF's but and I suppose you're last remark is just to use something like str(07:30). However not sure what you mean with your first remark?
You’re comparing strings and not times.
If you want to find out if one time is less than another, convert them to timestamps
Or datetimes
Ah I see what you mean, a string 07:30 cannot be smaller or larger than a string 07:31
Otherwise you’re doing a string comparison, and that’s going either lead to an error or at least unpredictable results
It has no idea what that really means
Though I've spent an hour and landed on what I currently have as that was the only one which pulled out the hour and minute from last_changed
Here’s someone else who was trying to do what you’re doing: https://community.home-assistant.io/t/time-based-template/108709/2
Seems like he eventually also just used strftime?
If you can make sure that the string comparison will work, I guess it’s okay. In any case, that thread should be instructive
My other point still stands. If you want to return a string, just return the string. Don’t add more {{}}
Well, going to be honest, no clue what I have to change.
Ok
I understand what you say, but not how to implement that in what I currently have. I've tried some different time conversions but none return the hour and minute from last_changed
That looks like a script. I don't think I can use variables for automations?
The action of an automation is a script, so maybe
Any ideas how I can show (as a card) an entities state "entity_picture" attribute image?
Seems like #frontend-archived
FYI @inner mesa managed to get it working even as a string, not sure how it even works but for some reason it does
This worked beautifully. Thanks for the tip!
Stupid question but cannot seem to find the right answer on google; How do I actually create a new entity when I have my template all written out?
My template returns a string value which returns my girlfriends work shift as a string
So I'd like that as an entity so I can add it to a presence card
So template sensor
I guess? I have it written out in the development tools now but unsure what to do next
Usually one approaches the problem the other way
You'd do this next: #templates-archived message
How is that?
Decide that you need a sensor and then work on the template that goes in it
Aah well, been a HomeAssistant user for a few years but started actively using it for the past half year. Never looked or used the template option till this afternoon so still learning a lot here
It’s kinda semantics, but I would start with the end product and work backward.
So I add the binary_sensor, platform: template to my configuration.yaml right?
Blargh just nevermind, this template/yaml thing ain't my thing. Spending an entire afternoon on a 5 line template which still isn't working is not productive 😋
is there a way to get a automations next trigger date? I want to create template sensor I can show on my UI to say when it's next going to trigger, based on its trigger time setup
No, because for almost every automation, there's no way to tell when it will next trigger.
And if you know when it'll next trigger, you don't need a way to guess it.
Yeah I figured that might be the case, time based triggers are only a subset. It's only really relevant for
- platform: time hours: '/1' minutes: '00' seconds: '00'
Again, that's predictable, so you don't need a way to determine it. If you really want something on your dashboard to show the next time, just use a trigger that shows the next hour.
now().hour+1
Dear mono, I got the problem of the statement from the HA logs. Could you please help me with this?
I can see the whole msg if I comment out the value_template
In my case its going to change the frequency/times based on input_datetimes and input_numbers 😅 I was hoping to not have to duplicate the logic in both the sensor and the automation, but so be it
What I saw in the HA logs is that
Template variable error: 'value_json' is undefined when rendering '{{value_json.a}}'
most timer algorithms only pay attention to the very next thing that will happen. when that happens, they repeat that algorithm
This is why I said to try value instead. One or the other should work.
What does the sensor show if you just use '{{ value }}' as your template?
Just pure '{{value}}' ?
Yes
I'm trying to write a condition that's a template, which extracts using a regex from the trigger variable. I'm getting an error, and wondering if I'm doing it wrong. Can someone take a look? Here's what I'm trying and the error I get:
Message malformed: invalid template (TemplateSyntaxError: expected token ',', got '{') for dictionary value @ data['condition'][0]['value_template']```
{{ is_state(input_boolean.block_notify_{{ trigger.to_state.attributes.entity_id | match("binary_sensor\.([a-z_]+)_person_motion") }}, "off" ) }}
Templates inside templates is a no-no.
If you really must do it that way, just concatenate the values:
{{ is_state('input_boolean.block_notify_'~(trigger.to_state.attributes.entity_id | match("binary_sensor\.([a-z_]+)_person_motion")), "off" ) }}
Or something like that
same values as no value_template!!
I got the whole json msg
What about with '{{ value_json }}'?
thank you! I also asked in the automations channel, before I saw this one. I think this helps.
is ~ a concatenation operator?
gracias
You don't want to concat different data types together without forcing them to both be strings.
Assuming you want a string, that is...
right
My Python isn't great but a lot of languages will screw up if you do something like '0' + 1.
Should the answer be 01? '01'? 1?
I'm getting closer. Now I guess match() isn't the right thing: ```Message malformed: invalid template (TemplateAssertionError: No filter named 'match'.) for dictionary value @ data['condition'][0]['value_template']
You just want to extract a name composed only of the characters a-z?
[a-z_] underscore is valid also
Ah, I missed the underscore 😄
The name of the sensor:
analog
The pattern's always binary_sensor.xxxxxxxx_person_motion and you want to grab xxxxxx?
yes
and xxxx is either text or _ right now
because then I have a input_boolean.block_notifify_xxxxxx
Sorry for the tagging I cancel it right now.
essentially each camera has a matching input_boolean that if enabled, blocks notifications
Is it possible to cancel the tagging by default?
oh, i need to use regex_replace or regex_findall_index
I would keep it simple then... forget RegEx:
{{ trigger.to_state.object_id.split('_person_motion')[0] }}
A state object's object ID is the part after the domain.
oooo,!
Split is more commonly used with a delimiter like spaces or commas but there's nothing stopping you delimiting on an entire phrase.
No, sadly 😂
yeah, totally. i didn't know about object_id. I only knew about entity_id, which includes the domain
If you get back the full value from {{ value }}, that's your starting point. If {{ value.a }} doesn't work, it's because it's not an object, so you can't use 'dot notation' to access keys.
Share the full 'JSON' please.
okay, it looks like this saves cleanly, with no errors: ```value_template: '{{ is_state( "input_boolean.block_notify_"~(trigger.to_state.object_id.split("_person_motion")[0]), "off" ) }}'
thanks for your help, mono
@crimson spoke posted a code wall, it is moved here --> https://paste.ubuntu.com/p/MkhBcqgFWN/
Oof...
@copper venture Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
For sharing code or logs use https://paste.ubuntu.com/.
Yeah, '{{value.a}}' just makes the same thing as pure '{{value}}'
@crimson spoke - read the bot message above... and then move over to #integrations-archived for help with input datetimes.
Wait a moment please.
{"id":4C1223451234,"a_h":0,"s_h":0,"a_b":0,"s_b":0,"a_l":0,"s_l":0}
That's all
You have no 'a' in there...
Sorry for the truncation but I have definitely add a_h after the value and value_json
Ok. I don't think what you have is valid JSON. The ID doesn't have quotes but it isn't a number.
How is it being sent to MQTT?
is there a way to add a line break to a template so when the sensor is pulled into lovelace, the break is preserved?
For example, this template outputs into a single line in a button card.
{% set x = states('sensor.time') %}
{{ day[now().isoweekday()] }}
{{ now().strftime("%B %d") + now().strftime(", %-I:%M %p")}}
I was hoping to have [Day of week], [Month] [Date] on one line, then [Time] right under it:
Thursday, May 13
2:45 PM
Looks fine in the dev tools. Might be a quirk of that card.
I'm new to jinja and templates - would it normally be output on two different lines according to the code I posted?
Okay, that's what I thought should happen. Thank for the verification!
Thank you so much I have done!!!!!!!
How about adding possibility to save debug templates in Dev Tool? It seems to reset sometimes, and it would be helpful to be able to choose what's displayed there? Could be though of as a "working templates bank"...
it resets if you clear your browser cache, or use another browser
annyone have a clue why this isnt working
friendly_name: "Journey gallons left"
value_template: >-
{% set F = (states('journey_fuel_percent') | round(2))}
{% set M = '(0.2)'}
{% set G = (F*M)}
({-G | round(2) -})
i followed a differnt formula template and made some changes for my needs, the other one is working fine
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['sensors']['journey_fuel_gallons']['value_template']. Got "{% set F = ((states('journey_fuel_percent') | round(2)))} {% set M = (0.2)} {% set Gallons = ((F*M))} {{-Gallons | round(2) -}}". (See /config/sensors.yaml, line 17). Please check the docs at https://www.home-assistant.io/integrations/template
you need to close each {% with %}
and this set M = '(0.2)' might be a string instead of a number
use https://my.home-assistant.io/redirect/developer_template for checking the syntax of your template
might be useful to create a new pinned message with a link https://my.home-assistant.io/redirect/developer_template
omg the answer is in front of me but im so dumb. didnt even see that when typing it out tunnel vision from working on a bunch of sensors i guess.
Exactly. Which is why a save would be a good thing so it would stay as I need it....
Hi, I am trying to create a template sensor which contains a date value of type date so I can trigger push message based on that. I have a pretty big if/elif statement to extract Norwegian month strings which is working, and I end up with this on the final line of my value template of my sensor:
{{ strptime(strdate, '%d %m %Y') }}
I have validated that the template works in the Template section, but I am not sure if I am returning a date value, and I am bit unsure how to verify. Any suggestions?
As the docs states: https://www.home-assistant.io/blog/2017/10/15/templating-date-time/
Use a time_date sensor and a template {{ strptime(states('sensor.date'), '%Y-%m-%d').year }}.
The sensor I am using is not time_date though, it is only a string value. But I am under the impression strptime returns a date, per the docs here: https://www.home-assistant.io/docs/configuration/templating/#time
All templates in HA return a string.
The stuff within a template cares about the data types but the value that's eventually returned by the template is always a string.
does the script.my_script service call require data_template (vs just data) if the parameter value is using {{ template.stuff }}?
data_template was deprecated almost a year ago in 0.115
See the Templates part here: https://www.home-assistant.io/blog/2020/11/18/release-118/#breaking-changes
I would hope they're on at least 0.118 and yet they still weren't seeing datetimes returned.
I had my own trials with strptime and trying to get templates to return datetime types. I wonder if it has something to do with datetime not being JSON serializable, so those get converted to strings on return
but, it's not true that templates always returns strings anymore
@burnt silo I'm not sure what you're trying to achieve that can't just be done like this:
{%- for value in list -%}
{{ value }}
{%- endfor -%}```
But your way works fine in the Dev Tools.
That was just a simple example to demonstrate it, the sensors which use it are mainly more complex. They were working in the Dev Tools for me as well until I updated to 2021.5.3
I've been able to refactor them to avoid using that now though, so everything is working now.
Hi Folks! I have what should be a really easy question...
How do I cast this incoming data from IFTTT as a number in the data_template in my automation?
area: '{{ trigger.event.data.area }}'
cycles: '{{ trigger.event.data.cycles }}'```
"cycles" is a number while "area" is a string
You'd just pipe them to an int or float.
{{ trigger.event.data.area | int }}
Although you'll get really weird results trying to cast a string to an int if it's not just a number inside quotes.
haha not weird, just 0
Most people would say that's weird 😄
{{ 'bananas' | int }}
Not as weird as the old JavaScript favourite... ('b'+'a'++'a'+'a').toLowerCase()
yep - it's a number. thanks!
Hey Everyone, I have been trying to figure this out and i'm getting lost. I'm trying to create a template to pull the HVAC_Mode that my Climate control is in so i can setup an automation depending on the season. I have the season automation setup, just cannot figure our how to get it to pull the 1 Mode that the unit is set to. Currently my sensor template is pulling the whole list... I.E. Off, Cool, Heat, Fan Only, etc...
it's just the state of the climate.xxx entity
if you just want the state, then states('climate.xxx'). If you want one of the attributes, state_attr('climate.xxx', 'yyy')
sorry, i forgot to add that these are being pulled by MQTT, When i created the sensor to pull the "hvac_modes" attribute, this is what it displays as the state: ['off', 'heat', 'dry', 'cool', 'fan_only', 'auto']
< office_hvac_mode:
friendly_name: 'Office HVAC Mode'
value_template: "{{ state_attr('climate.office_a_c', 'hvac_modes') }}">
that is my sensor pull setup.
because that's the list of available states
it doesn't sound like what you actually want
so find what you want in
-> States
and access it using the functions above
Thanks, i'm going to keep digging. Appreciate it!
awesome, got it working. Thanks again @inner mesa . You're my hero!
hi ppl
need a little help to retrieve a value from a attribute
alexa media player has a attribute called <id>_next_timer.sorted_all
and it looks like a json
but state_attr(sensor.my_echo_next_timer, "sorted_all") seems to return a string
i failed to convert it to a json while trying to use a |to_json
Share what it looks like and explain what you want to get from it.
sure! 1 min
i would like to get the "timerLabel" value
should i paste it directly here?
That's exactly how it displays? Two pairs of square braces around the whole thing?
yes
Try: {{ foo[0][1].timerLabel }}. What does that give?
Awesome. Do you understand why it worked?
haha, now i see what i did wrong
i had tried foo[1], but only got a "[" and thought that it was misprinting
yes, get the element 0 of the list and then the element 1
Ah. If you haven't converted to JSON yet, accessing by index gets the character at that index from the string 😄
thank you!
i want to use it as a condition for a automation. Hopefully i should be able to use "alexa timer tv 10 minutes"
Hi guys, I’m trying to figure out if I can have a template that is like “if state was xxx < 1 min ago” how would I achieve this?
Look up relative_time and the last_changed property
But that only works if the state hasn’t changed in that time. If you want to trigger on some past state, you can’t do that without saving the state
You could create an SQL sensor that has the state from 1 minute ago https://www.home-assistant.io/integrations/sql/
I have managed to set that up, but I would like to see what the state was before its most recent update. What I’m trying to do is detect if somebody changed from away to home in the last 60 seconds. I wonder if I could create a virtual switch that changes via automations.
Thanks that might work. I’ll have a look into it with my Maria DB database
Trying to use this template to have it return either number, but it is rather static. Using a greater range works fine. Is there a better method for this?
{{ (range(5,6)|random|int) }}
Hi can anyone help me with this wierd things regarding getting automaton attributes.
so
last_triggered: '2021-05-15T10:06:37.910321+00:00'
mode: single
current: 0
friendly_name: fan on```
however when i do
```{{states.automation.fan_on.last_triggered}}```
i get ```unknown``` i need the time stamp.. why is it unknown ? its right there
@fossil hearth try {{ state_attr('automation.fan_on', 'last_triggered') }}
Thanks man! ❤️
is this considered a timestamp ? coz i want shorten the output
for example {{ state_attr('automation.fan_on', 'last_triggered') | timestamp_custom("%m/%d/%Y")}} changed nothing in the output
I’m not sure sorry, I’m not too good at templates yet.
Try {{ state_attr('automation.fan_on', 'last_triggered').strftime("%m/%d/%Y") }}
Thanks you soo much 🙂
Well, I jumped to fast. This one is more like it {{ states.light.floor_ct.last_changed.strftime("%m-%d-%Y") }}
I have a template I want to run exactly once a day. How can this be done please?
You don't run templates. Templates just evaluate what's inside them.
Explain what you're trying to do.
My god... That's awesome!
If we're going to be pedantic, that's still a sensor. The template doesn't have a trigger 😄
hehe, true. I will give it a shot, thanks a bunch! 🙂
Ok, well, I'm creating this template https://paste.ubuntu.com/p/7JvtBtFVgn/ and need to feed the result into a input_text helper... I first thought of using a script for this, would that work?
Why does it need to be an input_text, and not just the sensor state?
Because I think I need it as a string value to compare later on. I will have more of these that will decide the outcome of the automation...
States are always strings
ah... then it may well work... 🙂
You saw the link I posted, right?
yes, did I miss something?
🤷♂️
I'll read that again...
A template sensor takes a template and returns the result as its state
With an optional trigger
A few of these and I believe it will do nicely...
This was tricker than it sounded... I have this sensor in configuration.yaml https://paste.ubuntu.com/p/mSfZb667yp/ But it returns Unknown....
Yes, I googled and thought that should update every minute. I know you gave me /24 to use for once a day
Have you reached the top of the next hour since setting it up?
Nope
Then it won't have a value... yet.
I wanted to speed it up...
Wait a couple of minutes and see if it changes.
Yeah, I figured it might be the case, thanks for confirming 🙂
You can probably do homeassistant.update_entity to force it
cool, will try
Did it change since hitting the hour?
homeassistant.update_entity did the trick. Now I know it works and can relax a little... Thanks guys!
I have a template sensor defined with a value template, and would apart from that also show last_changed in Lovelace. Will I need to define another template for that?
last_changed is a property
Ideally, you’d use a card that allows a template to access that
True, that seems like the way to go, will look for a suitable one, thanks!
why does input_number have a decimal that i cannot get rid of?
dev, explain yourselves.
recockulous.
If you want to display an input_number as an integer, you can
And some manners wouldn't go amiss.
Hi guys, when HA is restarted sensors are read correctly, but the timed one did not seem to work... Or to be more precise, the property 'last_changed' hadn't updated as expected, it still shows a date/time from yesterday. Don't figure why... And as defined in configurations.yaml, how to debug that consistently?
template:
- trigger:
- platform: time
# This will update nightly
at: "03:00:00"
- trigger:
- platform: homeassistant
event: start
Did the state change? Go read the state objects blurb about last changed and last updated
I have devided my room in 6 zones and want to vacuum the livingroom according to the segments i select. I was thinking of making 6 input booleans that i can turn on to select the zones i want and then press vacuum in which the selected zones are pushed to the script and the xiaomi roborock s5 max starts its thing. The real question now is, can i put in a template in the segment part of the script and if so how would i start?
- service: xiaomi_miio.vacuum_clean_zone
target:
entity_id: vacuum.xiaomi_vacuum
data:
zone: [[30914,26007,35514,28807], [20232,22496,26032,26496]]
Just to explain: "[30914,26007,35514,28807]" is a single zone. So when a boolean is selected it needs to add those 4 numbers to the line. its something like the nanoleaf petro helped me with a few weeks back
Hi, no, state did not change either
I was just digging in the logs to find if it fired at all... But can not find anything, should it show in the log if it did?
It's a triggered template sensor that should only update once a day. Maybe there are better ways of doing that...?
Well your syntax is completely wrong but you'll want to ask about integrations in #integrations-archived 😉
Leave it up, it's had responses now and always makes conversations look odd when one person deletes their comments 😄
When reading the last_changed using this template, it don't take summer time into account. How can I adjust it to do that?
{{states.sensor.period_of_day.last_changed.strftime("%Y-%m-%d, %H:%M")}}
i have a script like this: https://pastebin.com/tQ03wHPq
but i get the error: "Test vacuum zone: Error executing script. Invalid data for call_service at pos 1: expected list for dictionary value @ data['zone']"
when i test the template in developers tools it makes a perfect list. Can someone tell me what im doing wrong?
I also tested if zone can have a template. things like zone: "{{ [27337,26227,29737,27477] }}" do work. So i guess im making an error in my template somewhere
Your template will return strings. Just because you're writing something that looks like YAML, doesn't mean it's correct.
The YAML syntax for lists actually gets parsed into memory as a list structure. That's what your template should return (a list/array).
any thoughts on how i can do that? Or is there a webpage i can read that explains how to do this?
The search function on Discord is great.
Easy enough to get from that example to this:
{% set ns = namespace(result=[]) %}
{% set list_a = [1,2,3] %}
{% set list_b = [4,5,6] %}
{% set ns.result = ns.result + [list_a] + [list_b] %}
{{ ns.result }}```
You'll do some extra work to replace the middle 3 lines.
thanks ill try this
Above wont check for input booleans. I read on the forums that the best way to do something like this is to write a python script and run that. Never did that before though...
What do you mean it won't check? It'll do whatever your template says.
What have you tried?
Are templates 'naive' (not timezone aware)? I see on Dev Tools that States are returned in local time, but templates in UTC... Is there a trick to it or templates can't do it?
You can convert to local time: https://www.home-assistant.io/docs/configuration/templating/#time
Wow, that was easy. I was looking here (https://www.home-assistant.io/blog/2017/10/15/templating-date-time/) which didn't mention as_local() Thanks! 🙂
The blog isn't the docs. Always check the docs 😄
Shoot... lol, hadn't noticed that to be honest... Thanks for pointing that out... 👍
A blog post from 2017, no less
heyy guys
why cant i have the new "templates" integration inside a pkg? the same configuration gives error inside a package but not in configuration.yaml
Discussion about that from yesterday: #integrations-archived message
Thanks. I also find a issue on github discussing it as bug vs feature
Hey, how can I solve this:
{% if states('sensor.home_temperature') | int >= 7 and <= 20 %}
It tells me: TemplateSyntaxError: unexpected '>='
{% if states('sensor.home_temperature') | int >= 7 and states('sensor.home_temperature') | int <= 20 %}
got it
Oh that's nice, will take yours 😉 thanks
fixed off by one
anyone know why this won't work?
wait_template: >-
{{ is_state('light.bathroom_front', 'unavailable') or
('light.shower_lights_smartplug', 'off') or
('light.shower_lights_smartplug', 'unavailable') }}
timeout: '00:45:00'
ah perfect! thanks 🙂
can you get to a sensors state as the type it was created as? eg, if the state value is an int, can i get to it as an int in a template without having to do states('sensor.thing')|int
No. States are strings
ok
i thought i was being very clever by doing value_template: "{{ timedelta(minutes=value|int) }}" in an mqtt sensor, but it's hurting now that i want to do a comparison against it
Yeah, timestamp would be better
i'll just keep it as an int
thanks for the info
how do I access an array from a template? I have {{state_attr('weather.home_2', 'forecast')}} which returns [{'datetime': '2021-05-17T06:00:00+00:00', 'temperature': 12.2, 'templow': 6.4, 'precipitation': 4.5, 'precipitation_probability': 55, 'wind_speed': 7.4, 'wind_bearing': 284, 'condition': 'lightning-rainy'}, {'datetime': '2021-05-18T06:00:00+00:00', 'temperature': 15.9, 'templow': 5.6, 'precipitation': 1.9, 'precipitation_probability': 40, 'wind_speed': 13.0, 'wind_bearing': 277, 'condition': 'lightning-rainy'}, [bla bla bla...] ].
How do I access a specific entry? {{state_attr('weather.home_2', 'forecast[1]')}} as I expected to do returns "None"
oh, state_attr('weather.home_2', 'forecast')[1] works, makes sense
@quaint pond posted a code wall, it is moved here --> https://paste.ubuntu.com/p/QWmDFZ3DCy/
Can anyone tell what is wrong with my template?
Error: Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got [OrderedDict([('name', 'Season')]), OrderedDict([('state', '{% if now().strftime("%B") == "February" and now().strftime("%-d")|int == 14 %}\n VALENTINES\n{% elif now().strftime("%B") == "July" and now().strftime("%-d")|int > 04 %}\n INDEPENDENCE\n{% elif now().strftime("%B") == "October" %}\n HALLOWEEN\n{% elif now().strftime("%B") == "November" and now().strftime("%-d")|int > 27 %}\n CHRISTMAS\n{% elif now().strftime("%B") == "December" %}\n CHRISTMAS\n{% else %}\n OFF\n{% endif %}')])]. (See ?, line ?).
It broke after an upgrade. I know there was a change to templates but I am trying to find what to do to fix it.
your definition is a weird amalgam between the old and new styles
this is closest to what you have: https://www.home-assistant.io/integrations/template/#legacy-binary-sensor-configuration-format
I cant get the new style to work.
ok, then use the old one. what you have now is in between them
Only reason i was changing is because the old one is broken for me too 😄
ok. you presented it as "I updated and they broke". So you updated and changed some stuff?
ohhh sorry. I mean I updated HASS.
I get that, but it sounds like you also messed with the definition that you shared.
it's definitely wrong
Oh yeah I did. Want me to share the old version?
no, you have an example of the right way to do it above
mine are all the old style and they all worked fine with no changes
Here is my old version: https://paste.ubuntu.com/p/HQNMt5mf2G/
The error with this version: Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'integer') for dictionary value @ data['sensors']['season']['value_template']. Got '{% if now().strftime("%B") == "February" and now().strftime("%-d")|int == 14 %}\n VALENTINES\n{% elif now().strftime("%B") == "July" and now().strftime("%-d")|int > 04 %}\n INDEPENDENCE\n{% elif now().strftime("%B") == "October" %}\n HALLOWEEN\n{% elif now().strftime("%B") == "November" and now().strftime("%-d")|int > 27 %}\n CHRISTMAS\n{% elif now().strftime("%B") == "December" %}\n CHRISTMAS\n{% else %}\n OFF\n{% endif %}'. (See ?, line ?).
"OFF" is probably being interpreted as 0 now that templates can return native types
change that string to something else
"NOTHING" or similar
Changed it to "NOHOLIDAY" and I still get that error.
Bad template?
You're a genius. That worked for me in the template editor. Let me try in the file now
I just started with the first "if", which worked, and then added the second, where it failed
your choice
the new way doesn't work with packages, so if you're using packages, stick with the old way or migrate the definitions to configuration.yaml
I will leave it for now then. Upgrade when I am forced. Thank you so much for your help @inner mesa
I want to have a random number in a certain range, but exclude some numbers (which will eventually be stored in a input text as comma separated values)
I have the following now, but that gives an TypeError: object of type 'generator' has no len() in the template checker. How should I fix this?
{% set exclude_list = '1, 3, 4, 7' %}
{{ (range(0, 11)| reject(exclude_list | list)| random) }}
If I make a template sensor that is trigger based, which I want to update once a day at midnight-ish, it will show unknown after reloading templates (or restarting ha) until the time pattern is reached again. Can I get around this somehow?
Restart I can manage by another trigger I just realized. But reload remains
This should work I think, but how do I get what service_call_id I need to use for the reload template services? https://www.home-assistant.io/docs/configuration/events/#event-service_executed
I tried listening for the event in dev tools, but it doesn't seem to fire 🤔
workaround: trigger on state change to unknown for the template sensors instead
Hi, I've got an issue, I've made a template and it's working fine on Developer tools, however, when I make it into a real thing on configuration.yaml I get an error upon reboot
ERROR (MainThread) [homeassistant.setup] Setup failed for template: No setup function defined.
what are the relevant yaml lines?
The yaml that I used in configuration.yaml is this
- sensor:
- name: "Diferencial Temperatura Zona 1 Exterior"
unit_of_measurement: "ºC"
state: >
{% set exterior = states('sensor.temperatura_exterior') |float %}
{% set interior = states('sensor.temperatura_zona_1') |float %}
{{ ( interior - exterior ) | abs }}
and did you run the config check?
the - name indentation could be better with two more spaces
I'll try fixing that and restarting, just a sec
nope, same thing
Source: setup.py:138
First occurred: 11:57:41 AM (1 occurrences)
Last logged: 11:57:41 AM
Setup failed for template: No setup function defined.
I got that error on the log
Shouldn't state be value_template?
Not with the new template integration
Oh, okay :) I have some reading to do :)
any clues as to what might be happening here though?
I'm thinking maybe it's a broken install?
What version of ha are you on
core-2021.3.3
You need to be on 2021.5 or higher for the new template integration
Are there any plans to remove the legacy template sensor and template binary_sensor formats? Wondering if I should start moving my template sensors over to the new format.
the new format doesn't work in packages, so removing it would cause some breakage
But if the devs get it working with packages...?
it was seemed like more of a feature than a bug, from their perspective
When in DevTools testing {{ states.light|selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }} it also returns light groups. Can these be excluded somehow?
I don't think so unless there's something unique about them you can filter against
Ok, was afraid of that, thanks. Will figure another way then 🙂
You could set a custom attribute against them and use that to reject them.
Cool! I found this which works too ```
{% set domains = ['light', 'vacuum', 'switch', 'sensor', 'binary_sensor', 'zwave', 'lock'] %}
{% set filter = ['binary_sensor.remote_ui'] %}
{{ states | selectattr('domain', 'in', domains) | rejectattr('entity_id', 'in', filter) | selectattr('state','eq','on') | map(attribute='name') | list | join(', ') }}
How would the custom attribute work?
you could have to add an attribute to the entities through customization
Ok, could be one way, will check it out. I believe I briefly saw another suggestion about changing type of the group?
No idea. I had no time to check out what it was. post was removed
I'll check out the attribute, thanks! 🙂
Once you've set an attribute, you'd select/reject like this:
{{ states | selectattr('attributes.room', 'equalto', 'study') | map(attribute='entity_id') | list }}```
Nice, thank you!
Hey guys and gals, I think i need a template sensor, but not sure, I have a bulb energy meter that i have managed to get into HomeAssistant, but it only shows the total usage, How do i go about showing the usage for the month and day?
You don't use templates for history. You use #integrations-archived. Namely the integration integration and the utility meter integration.
Why do some config have to be under key homeassistant in configuration.yaml? As for example customize: !include customize.yaml
Just because
does anyone have a more elegant solution for this?
{% if 0 <= now().hour <= 11 %}
{% set start = (now() - timedelta(days=1)).strftime('%Y-%m-%d {}%z').format(states('input_datetime.master_bedtime_start')) %}
{% set end = today.format(states('input_datetime.master_bedtime_stop')) %}
{% else %}
{% set start = today.format(states('input_datetime.master_bedtime_start')) %}
{% set end = (now() + timedelta(days=1)).strftime('%Y-%m-%d {}%z').format(states('input_datetime.master_bedtime_stop')) %}
{% endif %}
{{ strptime(start, '%Y-%m-%d %H:%M:%S%z') <= now() <= strptime(end, '%Y-%m-%d %H:%M:%S%z')}}```
basically the start time is something like 22:00 and the end time would be 07:00 the next morning
since the hour wraps can't do a simple start < now().strftime('%T') < end
well you could if you just added 2 hours to everything right?
add two hours to start, end and now and then start < now().strftime('%T') < end
might work for that one but there's another that starts much earlier (toddler's bedtime)
well another option is just work in unix timestamps
the input helpers do not have dates
yea I know but it looks like you give them dates based on now
or were you hoping to get rid of all that?
right, that's the bit to simplify
if it always straddles midnight
to use timestamps i'd still have to do all the same work
then what about just two separate comparisons?
now().hour >= start or now().hour < end
drop the dates entirely
hour is an attribute of the helpers so yea
now().hour >= state_attr('input_datetime.master_bedtime_start', 'hour') or
now().hour < state_attr('input_datetime.master_bedtime_end', 'hour')
yeah, that's a lot simpler
haha yep, as long as they all straddle midnight that works great
any after midnight just adjust to the way you had it start <= now().hour < end
if you wanted to have the template ready to handle start being moved after midnight then you could throw in a conditional:
{% set start_hour = state_attr('input_datetime.master_bedtime_start', 'hour') %}
{% set end_hour = state_attr('input_datetime.master_bedtime_end', 'hour') %}
{% if start_hour > end_hour %}
{{ now().hour >= start_hour or now().hour < end_hour }}
{% else %}
{{ start_hour <= now().hour < end_hour }}
{% endif %}
thanks!
i have a bad tendency to get overcomplicated in my templates 😛
for even more context this is for my fan control automation
need to bypass occupancy detection during sleeping hours to keep the fans from shutting of from sleeping too still
yea that makes sense
though i could probably just tap into my thermostat instead...
I have smart outlets next to the beds on the phone chargers. When they are in use between 10pm and 10am it assumes the corresponding person is asleep and turns off normal presence lights stuff in that room. When all are in use it assumes everyone is asleep and turns off al presence lights stuff until someone is awake again
Well I guess I should say when all are in use for all the people at home. Anyone not at home is excluded from the calcuation of figuring out when everyone is asleep
i already have 'kid bedtime' and 'Sleep' modes on my thermostat which is hooked in to HA, probably much easier to just key off of that
let it deal with the schedule
no plans
i have this in my configuration.yaml to read out my p1 meter for what i take from the net
but is it possible to have a longer timeout?
Since the p1 reader has a bad wifi connection atm
it could help to get the data i think now its saying unavailable
sensor:
- platform: rest
resource: http://myip/api/v1/smartmeter?limit=1&json=object&round=on
name: Huidig Electriciteit verbruik Netafname
value_template: '{{ value_json.0.CONSUMPTION_W }}'
unit_of_measurement: "W"
I don't think you can control the HTTP timeout, no.
oh ok np tx for the answear
Is there an easy way to just subtract a couple of minutes from a input_datetime that has both date and time?
Tried this but for some reason it is two hours wrong to begin with {{ ( state_attr('input_datetime.morgon_alarm', 'timestamp') | int - 600 ) | timestamp_custom('%H:%M', False)}}
EDIT: setting it to True instead of False sovled it 👍
Doesn't look very template related... but your formatting is a mess. Maybe try #integrations-archived?
I have a script switch-presence.py that outputs {"result": {"state": "on", "id": 72251383255146496, "name": "MONSTER HUNTER RISE"}} on the command line. I was thinking it should work as a command line sensor like so:
- platform: command_line
name: Switch Presence Python
command: python3 /config/configs/commands/switch-presence.py
json_attributes:
- result
value_template: '{{ value_json.result.state }}'
However this results in an unknown state and only the Friendly Name attribute being defined.
If I remove the json_atttributes and value_template parameters, the state matches the output from the command line, except that "s are replaced by 's. So the command_line integration seems to work with this script but has an issue with the JSON... Any suggestions to make this work?
I had been trying to mess around in the template editor, but it seems like that's going to change the formatting to string regardless
I noticed both of these syntax's work - Which one is the most correct?
1. "{{ states('sensor.period_of_day' in ['day', 'morning', 'evening']) }}"
2. "{{ states('sensor.period_of_day') in ['day', 'morning', 'evening'] }}"
The first shouldn't work.
🤔 And you are correct. Both checks let that through so (wrongly) just assumed...
It's syntactically correct. It just that it will evaluate to states(false) which will give an error.
- data:
data:
photo:
- caption: Motion is Detected
file: /media/doods_lenovostick_screen_0_latest.jpg
message: Motion is Detected
service: notify.mobile_app_moto_g_6```
trying to push an image to my phone notification via the has app, the text appears but not the image. am i doing it wrong with "file:" ?
i have to say, i'm really enjoying the choose action
@bright quarry you will probably be better off asking in #android-archived
{{ states|selectattr('entity_id', "search", "fr_")|map(attribute="entity_id")|join(",") }}
running this in the dev tools results in this error
TemplateRuntimeError: no test named 'search'
any idea why?
which version of HA are you running?
that was new in 2021.5
and obviously adjust based on your actual entity_id values
is there a good way to stick json in the template editor and use that to test out rest sensor value templates
{% set value_json = jsonstuff %}
@inner mesa yep, updating HA fixed it. now when I go to add it to my Logbook card, I get a different error that I didn't get in the dev tools
type: logbook
entities: {{ states|selectattr('entity_id', "search", "abode")|map(attribute="entity_id")|join(",") }}
hours_to_show: 24
Configuration errors detected:
missed comma between flow collection entries at line 2, column 62:
... r('entity_id', "search", "abode")|map(attribute="entity_id")|joi ...
you probably can't use a template there
you could create a template sensor with that and use it instead
man, being able to inline those templates into lovelace card config would be great
like I'm trying to also make a dashboard summarizing all People, and I could create different entity cards that use the same search on someone's name
yay my rest sensors are all showing unknown 🙃
if you had something working in the template editor, it's usually that there's an extra level of encapsulation or an extra data: tag or something
here's the json i'm working with: https://paste.ubuntu.com/p/fpSdkGpfHB/
and value templates like so:
value_template: "{{ value_json.0.devices.0.real_power_w }}"
value_template: "{{ value_json.0.devices.1.real_power_w }}"
value_template: "{{ value_json.0.devices.2.real_power_w }}"
seems to work here, but maybe the data isn't available yet for your sensors
ah, was using the wrong authentication
apparently this endpoint uses digest instead of basic auth
"didn't actually get the data" is always an option
interesting. looks like the new template: syntax doesn't work in packages
Package envoy setup failed. Component template cannot be merged. Expected a dict.
yup, that's a thing
that makes me make this face: ☹️
i keep hearing about new template syntax but never looked in to it, have a linky?
oh interesting
There doesn’t seem to be an appetite for fixing the package support either
There’s an issue for it
can you create a template camera? e.g. I have a Eufy camera and a smart plug that I want to use to control the "on/off" state of the camera
Custom component / set state manually are the only ways I know of for that
how to handle when float(states.sensor.something.state) is "unknown"?
doing a sort/first and get TypeError: '<' not supported between instances of 'str' and 'float'
{{ states('sensor.something')|float }} will return 0 when unknown.
{{ states('sensor.something')|float(n) }} where n is a number, will return n when the sensor state is unknown.
nice, and how about if I have a list of values, how can I remove the unknowns (eg: I want average but discount the unknowns to not skew the result)
I have this currently {% set temps = [ states('sensor.temperature_upstairs_hall') | float, .... states('sensor.temperature_bedroom_3') | float ] %} {{ ((temps | sum) / (temps | length)) | round }}
You would have to use conditional statements. {% if states('sensor.something') not in ['unavailable', 'unknown', 'none'] %}
how would that work in a list? I'd expect something like listOfThings | filter('unknown')
Does this approach look sane - to cope with unknown from states('sensor.hall_sonoff_temperature')
value_template: >
{% set offset = states('input_number.hall_temperature_offset') | float %}
{{ states('sensor.hall_sonoff_temperature') | float( states('sensor.hall_corrected_temperature') | float - offset ) + offset }}
It's attempting to return current value if unable to calculate new value
ok so here's another one
how can i do something like this, but with a list of entities?
{{ ((now() - states.binary_sensor.front_door.last_changed).seconds < 300) or ((now() - states.binary_sensor.back_door.last_changed).seconds < 300) }}
that does, yeah
but say i wanted to give it like... ['binary_sensor.front_door', 'binary_sensor.back_door']
probably need to create a loop
this works:
{% set sensors = ['binary_sensor.izzy_bedtime', 'binary_sensor.master_bedtime'] %}
{% for sensor in sensors %}
{% if (now() - states[sensor].last_changed).seconds < 300 %}
{% set ns.changed = True %}
{% endif %}
{% endfor %}
{{ ns.changed}}```
i don't think you can get it to work with existing filters
hah nasty but it works
i just toggled 2 input_bools on and both these examples return true right now
{% set sensors = ['input_boolean.living_room_fan_override', 'input_boolean.master_bedroom_fan_override'] %}
{% for sensor in sensors %}
{% if (now() - states[sensor].last_changed).seconds < 300 %}
{% set ns.changed = True %}
{% endif %}
{% endfor %}
{{ ns.changed }}
{{ states|selectattr('entity_id', 'in', sensors)|map(attribute='last_changed')|map('as_timestamp')|select('gt', as_timestamp(now() - timedelta(seconds=300)))|list|count > 0 }}```
note that both are using the sensors var there
right on, i'm checking these out now
template tester is returning
True
True```
the one with the loop was giving me errors on setup
second one doesn't so we'll see how it works when the automation runs
both work in the template tester so you probably did something wrong in your automation
same here, both worked fine in the tester
can you not use templates in a condition entity_id? like:
condition:
- condition: state
entity_id: "{{ whatever }}"
state: 'on'
i think you need to use a template condition for that
ah yeah ok that makes sense
the docs (https://www.home-assistant.io/docs/scripts/#wait-variable) say "wait.trigger will be none if no trigger happened before timeout expired"
should that be {{ not wait.trigger }} or {{ wait.trigger == "none" }} or {{ wait.trigger is none }}?
not wait.trigger and wait.trigger is none would be equivalent and correct
oh wait! i can use the automation tracer to check this more easily now
cant find any docs (jinja site messed up). how to sum a list? [1,2,3] | sum without attributes? All the docs are summing up attributes in a dict
ok, in the correct channel: I am trying to pick fields out of a sensor.
"{{ state_attr('sensor.next_launch','Launch_time') }}"
"{{ state_attr('sensor.next_launch','Agency') }}"
are returning None in the template editor
are those the correct attribute names?
these things don't typically have capital letters
you have an "_" where there's a space in your attribute list for "Launch_time"
Launch time 2021-05-20T17:09:00Z
Agency China Aerospace Science and Technology Corporation
Agency country codeCHN
Stream false
there should be colons there somewhere
Just setup a new zigbee thermostat and I get a heat ‘on’ or ‘off’ in the state attributes. I want to use that to somehow create an energy used sensor. I know that each hour of being ‘on’ is 3Kw but no idea where to start to create something to track that. Ideally by hour then on to day/week/month. Any pointers please?
is == a valid string comparison operator? specifically i'm using a condition template, kinda like: '{{ trigger.event.data.action.split("-")[0] == "CAMERASNOOZE" }}'
yep
Hey I'm new to JS, how can I convert this into a JS template? {{ now().hour < 8 or now().hour > 20 }}
It's going to look almost the same:
new Date().getHours < 8 || new Date().getHours > 20
MDN should be your first stop for anything related to JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Thanks a bunch! I got a somewhat hang on Jinja templates, but there is not so much HA related examples on JS templates so that is a lot harder to learn. Thanks for the link, will save it!
You won't find many JS templates for HA because HA doesn't care about JS. The few things that accept JS templates are some custom cards.
You might get some help with it depending on who's around but it's not really a HA thing.
Like I'm trying to only show my media player card when it's actually playing but it won't accept this
[[[
var state = states['media_player.sovrum_hogtalare'].state;
return state == playing;
]]]
Oh damn the formatting did go wild here
[[[
return states['media_player.sovrum_hogtalare'].state == playing;
]]]
Something like this is my first guess
That'll also be wrong. In most languages, you need quotes around strings else they'll be treated as a variable (which doesn't exist in your case).
return states['media_player.sovrum_hogtalare'].state == 'playing';
]]]```
Ofc lol, thanks a lot
When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
If I'm here, I'll answer. If I'm away, I'll ignore notifications from strangers anyway 😂
So how does that work actually... you do a reply but ends the message with an @off?
Click @ ON to @ OFF to stop this make me confused
There should be a return on the time template right? Something like this?
[[[
return new Date().getHours < 8 || new Date().getHours > 20;
]]]
Does not seem to take it, like it's always false
It might now like the way it's creating and returning the value at the same time. I don't use any custom cards that I can test it with but you could try this instead:
const now = new Date();
return now < 8 || now > 20
]]]```
Seems to work either way as far as JS is concerned. Might be something weird with your formatting or the custom card. https://jsfiddle.net/nzg0ma85/2/
Explain to me how today’s date is greater or less that 8?
getHours is a method, you’re missing ()
D'oh... I messed up in that example 😄
Yes, it should be like this: https://jsfiddle.net/o453d60u/
I'd go with the simpler one-liner since you're probably not bothered about the instantiation of a second object. Performance difference will be negligible.
[[[
const now = new Date();
return !(8 <= now.getHours() <= 20);
]]]
Or this, slow on mobile
[[[
return !(8 <= new Date().getHours() <= 20);
]]]
I didn't think this was valid in JS: (8 <= now.getHours() <= 20)
That's Python land.
Thanks to you both! Will try it out 🙂
Hi, how can I get a new line in a template sensor after evaluating a condition. Something like this
{% if is_state('somenthing', 'on') -%}
write somenthing
NEW LINE
You'd just write something on a new line 🤷♂️
What are you trying to output and why do you think it doesn't work?
Also, that's not a complete template, so it's hard to guess where you might be doing something wrong.
the new line is rendered well in the Developer Tools Template, but when i try to see this sensor in a entity card in lovelace I get all the text in one line
here is the link to pastebin for the template: https://pastebin.com/EeSQkLTJ
I don't think this is necessary: {{ '\n' -}}
You're already writing a multi-line template, so linebreaks should be preserved.
If I simplify your template for testing:
Siren: Active{{ '\n' -}}
Gateway: Active
{% endif %}```
I get this:
Line break is preserved. What makes you think it's not?
Same outcome without the {{ '\n' -}} too, you just have to pay attention to the whitespace before each line then because you're missing the -.
where I missing the "-"?
If you remove {{ '\n' -}}, you don't have the - that strips whitespace.
The '\n' is pointless, since the linebreak exists anyway.
however I also get the new line in the template testing area in Developer Tools, but the new line is not preserved in the entity card in lovelace
Right... so that's not the template. That's the way that card displays the info.
Something like the markdown card would handle multi-line values. I don't know if many of the others do.
ok so the entity card is not capable to render the new line.. Good to know.. I'll try to use the markdown card
thanks for the help
\n means nothing in html
And yet the invisible linebreak introduced by spanning a value across two lines in a template is... wait for it... an \n
It's all down to how the card interprets that and builds the DOM.
I'm looking to build a simple binary sensor for outside light/dark. I want to use my tempest weather sensor lux levels (sensor.smartweather_brightness_2)... Greater > 0 = light, otherwise dark... Don't know the syntax for value template greater than or equal to.
I got it
ok... maybe not.. can I get help debugging this?
- platform: template
sensors:
light_outside:
friendly_name: "Light Outside"
value_template: >
{%- if {{ states("sensor.smartweather_brightness_2")|int > 0 }} -%}
"on"
{%- else -%}
"off"
{%- endif -%}
Gets this error: Invalid config for [binary_sensor.template]: invalid template (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['sensors']['light_outside']['value_template']. Got '{%- if {{ states("sensor.smartweather_brightness_2")|int > 0 }} -%} "on" {%- else -%} "off" {%- endif -%}\n'. (See ?, line ?).
no squigglies around states
fixed
you're nesting {{ }} inside the template, and you shouldn't do that
- platform: template
sensors:
light_outside:
friendly_name: "Light Outside"
value_template: "{{ 'on' if states('sensor.smartweather_brightness_2')|int > 0 else 'off' }}"
- more compact version
@dull bloom
how does one parse this json in a sensor?
https://pastebin.ubuntu.com/p/t6WHGn8V4R/
I know how to do get data from named attributes but this is just a array
no key available to grab from
e.g
{%- for x in value_json -%} {{x['name']}}{%- if not loop.last %}, {%- endif %} {%- endfor -%}
doesn't do nothing
if its actually json
if its not getting converted properly you can try this:
{
"name": "test",
"id": "206272a5fee04101a7d426db92622b2c",
"complete": true
},
{
"name": "rest",
"id": "b66af7f9081f4eafac3917ddb0a974fa",
"complete": true
}
]' %}
{{ ', '.join(value|from_json|map(attribute='name')|list) }}```
oh, you can get rid of the |list it isn't needed
hm, trying to get that to work with the shopping list integration but no success
- platform: file
file_path: /config/.shopping_list.json
name: ShoppingList
value_template: >
{{ ', '.join(value|from_json|map(attribute='name')) }}```
I'm not sure how the file integration works
Hi all how to calculate numbber of entity is in particular state en filter just on entity group ?
example : how many light is on on entity group.light ?
@radiant dock posted a code wall, it is moved here --> https://paste.ubuntu.com/p/SF67q68jSW/
but have the problem : String does not match the pattern of "DEPRECATED"
you've specified a bunch of entities and you can't/don't need to do that anymore
get rid of them
or add them as triggers
Ok thank's for your respond 🙂 what should i do then i don't understand
plug that template into
-> Templates and see what it's listening for. If it lists all those entities, just get rid of the whole entity_id: block
Ok I test this code :
- platform: template
sensors:
number_lights_on:
friendly_name: number lights ON
unit_of_measurement: "On"
value_template: >
{{ states.light|selectattr("state", "equalto", "on")|list|length }}```
and is OK but count all my light and no just in specify group
Ok I test and the result is
This model listens for the following state change events:
Entité: light.light_bureau
Entité: light.light_chambre_lenzo
Entité: light.light_chambre_parent
Entité: light.light_salon
Entité: light.light_sdb_mirroire
Entité: light.light_sdb_plafond
Entité: light.light_toilette```
It's normally to listens on group light and all the light in the group ?
🤷
finally is the same no ?
if you're happy with that, then go with it. if you want to list entities instead, you can do this: https://www.home-assistant.io/integrations/template/#trigger-based-template-sensors
with this code :
sensors:
number_lights_on-2:
friendly_name: number lights ON-2
value_template: >-
{{ expand('group.light') | map(attribute='state') | map('float') | sum }}
unit_of_measurement: "On"```
ok but is it normal for him to look in the entity group + all the entities inside the group at the same time? it may be logical ....
it's okay
OK
I test to reload ha and view the result
ho...
error on check config
Invalid config for [sensor.template]: invalid slug number_lights_on-2 (try number_lights_on_2) for dictionary value @ data['sensors']. Got OrderedDict([('number_lights_on-2', OrderedDict([('friendly_name', 'number lights ON-2'), ('value_template', "{{ expand('group.light') | map(attribute='state') | map('float') | sum }}"), ('unit_of_measurement', 'On')]))]). (See ?, line ?).
it tells you what's wrong and what to do to fix it 🙂
ok the error is -2
change to _2 and it's ok
ha check result OK
thank's @inner mesa for your help
The good code is :
- platform: template
sensors:
number_lights_on-2:
friendly_name: number lights ON-2
value_template: >-
{{ expand('group.light')|selectattr("state", "equalto", "on")|list|length }}
unit_of_measurement: "On"```
and the result is fine 🙂
great
I'm using the command_line senor to get some text/symbol/numeric garbage from a curl get call. I'm trying to do an if then to set the state of the sensor to True or False.
I'm guessing with {%- if value == 'bbblah123!' -%}, I'm using value incorrectly.
{%- if value == '{"cmd":"$G0","ret":"$OK 1^31"}' -%}
Connected
{%- elif value == '{"cmd":"$G0","ret":"$OK 1^30"}' -%}
Disconnected
{%- endif -%}```
i think you don't need the from_json
hmm, not working for me either... i get a file: Error on device update! error
has anyone got a yaml template for "good morning, good evening etc"?
🤔
Yeah i worded that terribly
Templates take data and spit out other data. You need to explain exactly what you need... and what you've tried already 😉
I have a template that works, but whats the best way to output that to a value I can use in Node-Red when using TTS
{% if now().hour < 5 %}Good Night!
{% elif now().hour < 12 %}Good Morning!
{% elif now().hour < 18 %}Good Afternoon!
{% else %}Good Evening! {% endif %}
I still don't understand. If it works, what are you asking for?
And if NR has some special requirements, that's a #node-red-archived question.
I dont want to have to keep using that template code in all my automations
i just want so i can query say idk, value.time_of_day
or whatever the correct type would be
So make it a template sensor.
ahhh its a sensor entity
ok right thats what i was after. Didnt really know what i was asking so was struggling a bit 😆
perfect thanks. The announcement that the dryer has finished is a bit politer now 🤣
hey, maybe someone can help me. i want to build a tv remote with my harmony hub. if i choose a input select like tv, all my buttons should work for tv, when i choose firetv all buttons should work for fire tv. is it right to use templates for this?
@upbeat gust I think you use a harmony remote for that...
i have a harmony hub, yes. i dont know if i should use automations and scripts or if i should use templates
There’s no one answer for that
I'd set up activities in the harmony app, then use the harmony integration
you can switch between activities, it creates switches for you
I mean that is what I've done
for example my input select is tv und i push direction up it should work for tv, when using other input i want to chane the button function for the specific device
what do you mean? no best way? 🙂
cant use the activities 😦 so i need the send commands
why not?
so are you trying to build a virtual remote inside HA to use to interface with your physical hub?
because i'm not statisfied with the activities.
hmm
so you can use them lol they're just not what you want
or potentially more accurately, you haven't got them set up the way you want
my problem is, i have 5 devices and when i create a "direction up" button i have to create 5 scripts for my input select, than i can use it with an automation
but maybe its easier to create
is there a way to put this both scripts together in one script? https://pastebin.com/YwnLDsd1
You'll want to ask in #automations-archived about scripts. I don't see a template in sight in your paste.
ok i will try, but maybe its a better idea to create a template for that?
hey
I was hoping to be able to print out the sun rise and sun set just like the entities details
for the entity sun
but
I don't know how to add that card like that to my lovelace interface?
Well it wouldn't be with templates. You want #frontend-archived
right
But that's the more info popup, not a card.
well I got something to work
right i want to make that popup in to a card - meaning it can't be hard to do I wouldn't think
but i have found it challenging
🤷♂️ Head over to #frontend-archived
Hi y'all! Anyone have a solution for how to convert a timestamp in YYYY-MM-DD-HH-MM-SS to unix timestamp? Or even better, is there a way to calculate a time difference for such a timestamp?
as_timestamp(strptime(‘xxx’)), where xxx is the time format
Thank you so much!!
Seriously, I swear I googled and checked the docs, but I must be blind as a bat, thanks Rob!
Np. Time/date conversions are all trial and error for me
That worked flawlessly, thanks again dude, y'all in the community helping out are what makes HA so great
https://paste.ubuntu.com/p/rppTW6P3WK/ - What am I missing here ? it hits the else and the value is "locked"
Your entity ids are wrong in the first 2 checks
Should it be states.sensor.nuki_local_webapi.attributes.stateName ? I copied sensor.[entitty]_[attribute] from somewhere
You should be using the is_state_attr method
HI all. I'm fiddling around a bit with templates in the developer tools and I'm looking to convert a string time (e.g. "13:20") to a datetime object. What I find online is that I should use strptime(str, format), but if I do that I still can't call any of the datetime object methods (e.g. .isoformat(), .hour, . minute etc). I get an error stating 'str object' has no attribute 'isoformat'. Any ideas on what I'm doing wrong?
Scroll up a little, you'll see another conversation about datetimes and a link to the docs.
If strptime returns a string, that means your format is wrong
I had found those docs, but failed to click the "format" link in there. And I was indeed using the wrong format 🤦♂️ Thanks!
The time stuff is probably the hardest stuff to get right with templates but the docs are pretty good.
my googlefu isn't with me tonight - can I string multiple is_state calls in one if statement (with or's between)?
https://paste.ubuntu.com/p/MqSx8v3rFT/
Furthermore will the template renderer in developer tools actually check the state of input_selects and resolve the template appropriately?
......
for those wondering, the answer to both my questions is yes - if you get your entity names correct!
Is it possible to have a template reverse the state of an entity? In this case, a cover that is showing as open when it should be closed
yes it is
Will it show the original entity as reversed, or does it create a new one?
a template cover creates a new entity
Ah cool. Thanks 🙂
I just noticed on the jinja docs that there's multiple versions (2.10.x, 2.11.x, 3.0.x), how do I know what version Home Assistant is using?
- platform: template
covers:
bedroom_blind:
friendly_name: blind
value_template: "{{ is_state('cover.bedroom_rollerblind', 'off') }}"
open_cover:
service: switch.turn_off
entity_id: cover.bedroom_rollerblind
close_cover:
service: switch.turn_on
entity_id: cover.bedroom_rollerblind
stop_cover:
service: switch.turn_{{ 'on' if is_state('cover.bedroom_rollerblind', 'off') else 'off' }}
entity_id: cover.bedroom_rollerblind```
does that look right?
or perhaps I have to change the off to closed
- condition: template
value_template: >-
{{ trigger.entity_id == fan_trigger }}
why is this not allowed as choose condition in a blueprint?
because fan_trigger isn't an entity id of the form domain.object_id
It's currently 2.11 see: https://github.com/home-assistant/core/blob/dev/homeassistant/package_constraints.txt
@autumn grotto if you're checking one entity for multiple states i find its easier to use {{ states('my.entity') in ['state1', 'state2'] }}
i used a variable here
@stark wolf posted a code wall, it is moved here --> https://paste.ubuntu.com/p/BGcvC42tyf/
Hey y'all! Trying to figure out templating. Gathering some info from a video endpoint to determine current call status. Not quite sure how to take this XML data and stick it into a sensor. Trying to snag the 'NumberOfActiveCalls' attribute in the above code snippet.
Assuming value_json parses XML (which from memory it does), you need to provide the full path to the field you're interested in:
{{ value_json.Status.SystemUnit.State.NumberOfActiveCalls }}
hello world!
its me of the weird questions, again. I am trying to unpack NWS_alerts
{{ state_attr('sensor.davidson','alerts') }} gives:
[{'area': 'Robertson; Sumner; Macon; Dickson; Cheatham; Davidson; Wilson; Trousdale; Smith; Hickman; Williamson; Maury; Rutherford; Cannon', 'certainty': 'Unknown', 'description': 'The Tennessee Department of Environment and Conservation has issued a\nCode Orange Health Advisory for the Nashville area...in effect until\nmidnight CDT Monday night.\n\nA Code Orange Air Quality Alert for Ozone means ground level Ozone\nconcentrations within the region may approach or exceed unhealthy\nstandards. The general public is not likely to be affected. Active\nchildren and adults, and people with a respiratory disease such as\nAsthma, should limit prolonged outdoor exertion. For additional\ninformation...visit the Tennessee Department of Environment and\nConservation site at http://www.tennessee.gov/environment.', 'ends': None, 'event': 'Air Quality Alert', 'instruction': '', 'response': 'Monitor', 'sent': '2021-05-23T13:32:00-05:00', 'severity': 'Unknown', 'title': 'Air Quality Alert issued May 23 at 1:32PM CDT', 'urgency': 'Unknown', 'NWSheadline': ['AIR QUALITY ALERT IN EFFECT UNTIL MIDNIGHT CDT MONDAY NIGHT'], 'hailSize': 'null', 'windGust': 'null', 'waterspoutDetection': 'null', 'effective': '2021-05-23T13:32:00-05:00', 'expires': '2021-05-25T00:00:00-05:00', 'endsExpires': '2021-05-25T00:00:00-05:00', 'onset': '2021-05-23T13:32:00-05:00', 'status': 'Actual', 'messageType': 'Alert', 'category': 'Met', 'sender': 'w-nws.webmaster@noaa.gov', 'senderName': 'NWS Nashville TN', 'id': 'urn:oid:2.49.0.1.840.0.c75ef2fe8bfb1a7a07b346b1ee9fa49c1b0aad14.001.1', 'zoneid': 'TNZ027,TNC037'}]
how do I pull out the individual alerts/fields?
the [{ and }] make me thing it's an array of one entry?
Good call on the full path. Missed that. Still no dice.
2021-05-24 14:11:05 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'value_json' is undefined when rendering '{{ value_json.Status.SystemUnit.State.NumberOfActiveCalls }}'
How/where are you testing it?
Tested the curl command on my HAOS host.
gets a successful return so this tells me I am just templating the returned data wrong
which I am a complete newb at templating in HA
What happens if you just don't use the template in your command line sensor? What does it pull back as its state?
You access arrays (lists) using square brackets and a number indicating the index of the item you need. You access keys (named values) from an object using their name.
To access the severity from the 5th item, you'd use value_json[4].severity (assuming value_json represents the entire object).
It returned the XML string. So that tells us that it is working in the sensor dameon. Just need to filter the state?
Note.....I want it to just store 0 or 1 so I can take a particular action when I am in a video call.
thanks mono!
Looks like it's not converting it to JSON for you. Is there a reason you're using the command line sensor instead of the RESTful sensor? Seems like the latter would work here and that mentions it converts XML in the documentation.
'mono: still pushing against a mountain.
Will the restful sensor refresh on an interval? I looked through that documentation as well.
Yes, it refreshes. I don't recall what the default interval is but it may be customisable.
You can specify it: scan_interval: 60
ok, mono, will admit that the json bit is driving mer buggy
i don't understand how to access the json payload, in the templating console??
i am trying this: {% set value_json= {{state_attr('sensor.davidson','alerts')}} %}
That’s wrong
Don’t nest {{}}
You’re already in a template, so it’s just a function call
i know that much, just can't get to whats right..
you mean like -->>>> {% set value_json=states('sensor.davidson') %}
or {% set value_json=state_attr('sensor.davidson','alerts') %}
Whatever contains the JSON
it keeps giving error messages... this time about result-type string
{% set value_json=state_attr('sensor.davidson','alerts') %}
{{value_json}} gives me the correct block of data, sort of
value_json[0] is closer, but still erapped in { }
@ivory delta - rest sensor worked perfectly! woohoo!
Just FYI - what I am doing is setting the mood in my office whenever I hop into a video call. Turn off overhead lights, turn on video lights, pause echo, turn on echo DND, pause appleTV.....
whoa. it was double wrapped
{% set value_json=state_attr('sensor.davidson','alerts') %}
{% set vj=value_json[0] %}
{{vj.NWSheadline[0]}}
For: {{vj.area}}
{{vj.description}}
works
can you use that in markdown?
Try it
If I have an entity whose state is a question and an answer and the question ends with ? How can I split them up. I have gotten this far
{{ states.sensor.dad_jokes.state.split('?') }}