#templates-archived
1 messages Β· Page 120 of 1
it works, i got the sensor but its not reacting to my movements π¦
i see it trough the ssh, and terminal tho
i got the hang of template at least π
oh it gets so much worse lol π
so, switch.motion_sensor_10981222 - is that reacting to your movements?
like, does the source device connected to tellstick change state?
noo the switch is not reacting
i only see it working trough ssh terminal
when i wave my hand
ok well, that's another problem to tackle i guess.
are other tellstick devices working?
i just had to google WTF a tellstick is so... probably not going to be much further help lol
try #integrations-archived or maybe on the forums.
but now you know how to make a template!
thank you anyways π
yes
i have like 4 other motion sensors i can make a template from
π as soon as i get this one working
gonna try and add a unique id to the one i just made
the name of the sensor contains a dot. Remove it
binary_sensor:
- platform: template
sensors:
switch.motion_sensor_10981222:
^
|
REMOVE THIS, NOT ALLOWED
friendly_name: "Motion Sensor1"
device_class: motion
value_template: "{{ states('switch.motion_sensor_10981222') }}"
They had a slightly different misunderstanding, they've got it handled now
works great, thanks π
Is it expected that values in Helpers ( eg input_number & input_select) are not usable in templates?
In the template editor I input something like this {{ states.input_number.test_number}} and my output is:
<template TemplateState(<state input_number.test_number=27.0; initial=None, editable=True, min=1.0, max=100.0, step=1.0, mode=box, unit_of_measurement=pokemons, friendly_name=test_number @ 2021-02-20T05:51:31.623445-06:00>)>This template does not listen for any events and will not update automatically.```
my desired output would be 27
Not usable... π€
They are. And you're not using the proper method of retrieving states.
So what object would I be looking for, also tried using {{ states('input_number.test_number') }}
which is what the documentation says should return as a string
Hi, I would like to log the wattage used by a HS110 via the tplink integration and would like to send the wattage to influx DB. Wattage shows up in the entities attributes but does going to influx. Can anyone point me in the right direction?
That looks fine. I have no idea why it's saying it won't update.
#analytics-archived for data stuff
i think the real question here is how does unit_of_measurement=pokemons render in the UI
Or not.
and I thought I'd go max crazy by connecting my toothbrush to HA
Make it set off the house alarm when you don't brush long enough.
apparently i don't understand lists very well because i have what i suspect is a simple use case but just can't seem to come up w/ a solution.
i have a list, it might look something like this:
{% set testlist = ['binary_sensor.plate02_connected', 'light.plate02_backlight', 'sensor.plate02_sensor', 'number.plate02_active_page', 'light.plate02_selected_foreground_color', 'light.plate02_selected_background_color', 'light.plate02_unselected_foreground_color', 'light.plate02_unselected_background_color'] %}
in that list, the _plate02 bit will be different each time. I want to select sensor.plate02_sensor from that list, and i don't know the value plate02 ahead of time
so, regex ^sensor\..+_sensor$ if that makes sense
So use regex π€·ββοΈ
But since you haven't said what you're actually trying to achieve, it's going to be hard for anyone to help.
goal is to capture the value sensor.plate02_sensor from the list presented above
Just the string for that entity ID?
correct, the string is fine. the list is a jinja list, each contains an entity name, but that's kind of irrelevant. it has a list of strings, i want to apply a regex test against each item in the list, and return the item that matches.
if there is more than one match, either return them all or just the first or whatever
some things i'm trying: {{ testlist| regex_search("sensor\..+_sensor") }} returns true, as it's a test
adding regex to match start of line and end of line makes that test return false: {{ testlist| regex_search("^sensor\..+_sensor$") }}
{{ testlist| regex_findall_index("sensor\..+_sensor") }} returns sensor.plate02_connected', 'light.plate02_backlight', 'sensor.plate02_sensor which tells me it's processing the entire list as one long string (not handling each element in the list separately)
which i suspect is my problem here. tl;dr - i'm doing it wrong but not sure where
here's one approach that feels a little gross but does the thing
{% for entity in testlist -%}
{%- if entity|regex_search("^sensor\..+_sensor$") -%}
{{entity}}
{%- endif -%}
{%- endfor %}
This works just fine to replace everything after the first match with nothing:
list | regex_findall_index('switch\.bedroom.*') | regex_replace('\'.*', '')
is it possible to disable sensors to get data? i'm working on an template in dev tools and have to set some data to test it. but every minute the sensor gets its date from integration?
No, you can't 'pause' them. They're enabled or not - and if they're not, you can't even find the entity.
Why do you want to pause it? What's giving you trouble?
as i said. i working on a template and wants to test it
so i have to test with hard values instead of sensors?
That depends what you're doing...
i would like to add a binary sensor depending on some other sensors.
can i fake/set their values in the template?
You can fake anything... but you might end up with something that looks completely different to what you need.
Share what you have so far and explain why it's a problem.
{% if is_state('sensor.superb_iv_charger_max_ampere','Reduced') %}
{{ states('sensor.charging_current_winter') | float >= 0 }}
{% endif %}
{% else %}
{{ states('sensor.charging_current_winter') | float >= states('input_number.threshold_reduced_charging') | float }}
{% endif %}```
thats what i have
Triple backticks to format as a block please. Easier to read π
Gimme a sec
you'll get two, if you need π
As long as I've not made any mistakes, this should have the same meaning:
{% set charging = is_state('switch.superb_iv_charging','on') %}
{% set reduced = is_state('sensor.superb_iv_charger_max_ampere','Reduced') %}
{% set winter = states('sensor.charging_current_winter') | float %}
{% set threshold = states('input_number.threshold_reduced_charging') %}
{{ winter >= 0 if charging and reduced else winter >= threshold }}```
And now you can just change the right hand side of any of the first 4 lines for testing.
look good.
i will try with that. thanks
does the if statement work with the condition before "if"?
never seen
It's basically Python's version of the ternary operator.
a if x else b
This will check if x is a 'truthy' value, returning a if it is. Otherwise, it'll return b.
Truthy values are things like non-empty strings, as well as the boolean True.
got it.
is there another option for a short if then else?
without lots of bracket as i did before?
just want to be sure, that I understand it when i read it in a month or further future
That is the short option to avoid if/else π
If you're doing multiple checks, sometimes you need more... like if you're going to do: 'if Monday, do this, else if Tuesday, do this, else if... end if'
But with only two possible options? Use ternary π
okay what about this? two more values (maximum and threshold_maximum) and one more if.
{%- if is_state('sensor.superb_iv_charger_max_ampere','Maximum') -%}
{{ states('sensor.charging_current_winter') | float >= 0 }}
{%- endif -%}
{%- if is_state('sensor.superb_iv_charger_max_ampere','Reduced') -%}
{{ states('sensor.charging_current_winter') | float >= (states('input_number.threshold_maximum_charging') | float - states('input_number.threshold_reduced_charging') | float) }}
{%- endif -%}
{%- else -%}
{{ states('sensor.charging_current_winter') | float >= states('input_number.threshold_maximum_charging') | float }}
{%- endif -%}```
doesn't work with ternary, does it?
are there another notation for those multiple checks. or do i have to use jinja-if-then-else?
There are probably a hundred ways to write your template. The more detail you add, the more that number grows.
But yes, you'll probably have to use some if/else in there at some point.
And you should keep it simple like the version I gave you. That template is hard to read because you have such long names everywhere.
Use variables π
I got that point. But searching for the shortest way of if-then-else.
{% set reduced = is_state('sensor.superb_iv_charger_max_ampere','Reduced') %}
{% set maximum = is_state('sensor.superb_iv_charger_max_ampere','Maximum') %}
{% set winter_current = states('sensor.charging_current_winter') | float %}
{% set threshold_reduced = states('input_number.threshold_reduced_charging') | float %}
{% set threshold_maximum = states('input_number.threshold_maximum_charging') | float %}
{% if charging and reduced %}
{{ winter_current >= 0 }}
{% else %}
{{ winter_current >= threshold_reduced }}
{% endif %}
{% if charging %}
{% if maximum %} {{ winter_current >= 0 }} {%- endif -%}
{% if reduced %} {{ winter_current >= (threshold_maximum - threshold_reduced) }} {%- endif -%}
{% else %}
{{ winter_current >= threshold_maximum }}
{% endif %}```
Now I have this. First block I could write in ternary, too. But I want to write both in the same way. any suggetions for shortening?
What's the difference? Are they going to be different templates or are you hoping that returns one valid template? π€
Do you just want the last 6 lines to be shorter?
In a lesson on how not to write templates... you wanted short:
{% set s, i = states, is_state %}
{% set a = i('switch.superb_iv_charging','on') %}
{% set b = i('sensor.superb_iv_charger_max_ampere','Reduced') %}
{% set c = i('sensor.superb_iv_charger_max_ampere','Maximum') %}
{% set d = s('sensor.charging_current_winter') | float %}
{% set e = s('input_number.threshold_reduced_charging') | float %}
{% set f = s('input_number.threshold_maximum_charging') | float %}
{{ (d >= 0 if c else d >= (f - e)) if a else d >= f }}```
Made your last 6 lines tiny π€
Good luck maintaining it now π
Can I somehow include which user that executed a script?
Like "The alarm was activated {{ now().strftime('%Y-%m-%d %H:%M:%S') }} by {{ < triggered by user > }}
I found this: https://developers.home-assistant.io/docs/frontend/data/#hassuser but need help to actually use it..
Ah, the dev docs... the docs for devs.
It's the front-end that knows who's logged in, not your script.
And I can't pass it on?
If you want to provide that information to your script, the card/whatever that's calling the script needs to provide it.
Does your card provide it?
No idea, but it would be exactly that I want. Don't really see where to start looking.
Found a few community posts, but only questions, no answers
Because it's not currently possible.
that are to templates for two binary sensors depending on the same variables.
maybe a bit too tiny. but thanks. i will take a look what to do.
Don't do what I just shared. It's stupid.
It's an example of how you can optimise code too much and make it too difficult to read π
Your 'long' one is fine if you can read it and understand it. Shorter isn't always better.
i won't do that a, b, c, d thing. but maybe that one-liner with former variables.
but i got the point, thanks
Can i make a light entity with template? I only see examples with a "sensor:"
If there's an #integrations-archived for it, sure
I have a wall outlet that is a switch entity in HA. I'd want it to be a light so its easier to make automations
That's a question for... #integrations-archived
loef - I've saved you another 50 characters:
{% set s, i = states, is_state %}
{% set x,y,z = 'switch.','sensor.','input_number.' %}
{% set t,u,v = 'threshold_','charging','superb_iv_charger_max_ampere' %}
{% set a = i(x~'superb_iv'~u,'on') %}
{% set b = i(y~v,'Reduced') %}
{% set c = i(y~v,'Maximum') %}
{% set d = s(y~u~'_current_winter') | float %}
{% set e = s(z~t~'reduced_') | float %}
{% set f = s(z~t~'maximum_'~u) | float %}
{{ (d >= 0 if c else d >= (f - e)) if a else d >= f }}```
I jsut need to know if i can write light: instead of a sensor:
Holy crap. Ask in #integrations-archived
You're not asking for help with a template, it doesn't belong in #templates-archived
You want to know how #integrations-archived work, so ask in #integrations-archived
i Am making a template dude
You will eventually need a template for what you're doing. Your question is about the integration. π€¦ββοΈ
In fact, based on what you said, you don't even need a template... #templates-archived message
100% #integrations-archived material.
Hey guys, I'm struggling to use jinja2 to split an area into individual entities for the snapshot_entities variable in scene.create. I think part of my problem is it's just hard for me to test and see the output I'm getting and what dictionary keys I have access to when handling an area of entities.
What I have is basically this:
{% for entity in expand(area) %}
# filter entities if I don't want them
# If I just 'print' entity here, it doesn't work because it's not presented as a list in the yaml, and I don't think what I have below is the correct way to expand it to a list, but it's an example of something I tried
'{{ "- " + entity + "\n" }}'
{% endfor %}
Consider it pseudo-code, I just wrote it from memory and I know it's not right, my focus is on expanding the area to a list of entities that is valid yaml.
Hi Dom. For testing it's a good idea to use TEMPLATE in the developer tools
oh yeah I saw that a while ago but I completely forgot about it, thank you
And if area is a list of entities then you can probably do area|select() . If it's a list of dicts rather than strings you can then chain that with |map()
Check the list of built-ins in the pinned posts
Yeah I'm expecting an area from a selector
Not sure I understand
ok the templating developer tool is helpful, I'll have to poke some more with this template debugger and make sure everything I'm doing is what I thought I was doing π
Excellent
a blueprint selector is what I mean, so I enter a room in a blueprint, and that's what I'm parsing in the jinja
I don't think you can play with area's in the template developer tool
Yeah that's what I'm finding, part of my disconnect was also that I didn't realize the selector I was using was returning a 'target'
So I don't think what I wanted to do is going to work
Maybe scene.create can take a target as an argument for a snapshot? I can't find much documentation on the individual scene modules other than https://www.home-assistant.io/integrations/scene/
https://github.com/home-assistant/core/blob/dev/homeassistant/components/scene/services.yaml
ah yeah no dice. I guess what I'm actually looking for is mapping a target to a list of entities then
I may be digging this hole too deep. I'm still new to scripting/templating in hass, so maybe I'm missing something, but it seems like there should be a better way to create a scene on the fly that can take a target as well as discrete entities.
is it possible to regex match entity ids in a states()?
Or any sort of wildcard?
well my immediate need escapes me now, I've switched focus. But how is it possible? I've tried a regex in there, I've tried map filters and select filters
No-one can possibly answer 'how is it possible' without first knowing what 'it' is.
There's so many ways you could apply regexes and they'll all be completely different depending on what you're trying to do.
Right, let me try to find an example
I could give you an example... but there are going to be hundreds more π
{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list | count }}```
The catch is that you have to pay attention to what each filter or map is doing and the data type returned. You can't get back from that one to the names of the entities it found.
Ah, ok. Something like states('binary_sensor.light_profile__.*')|select_attr('state')|map(attribute='entity_id')|list[0]
No, nothing like that
afaik, you can't wildcard in states(), and your filters aren't going to return what you think they are.
But... you have the Dev Tools to experiment in.
yeah, i've been trying all sorts
at the moment it just seems easier to use an sql sensor
If that's what works for you, go for it. There's no 'best' solution.
A I supposed to be able to use the value from value_template in an attribute_template in the same template sensor?
The value returned by value_template becomes the state. Why would you want to have the same value in an attribute?
I want to use the value in an attribute to calculate other stuff
Give me an example of what you're trying to do
Hi people! I'd like to set the value of an entity at a certain time. How can I do this with a template? I would like to store the state as "value_yesterday" at 23:59
what kind of data is value_yesterday? a number? a date/time? a string of text?
in general, what i think you'd probably want to do is to create a helper object to store your data, then an automation which triggers at 23:59, reads your entity value, and saves that value into the helper object
thanks! how do I create an automation trigger?
time trigger
value_yesterday is a number
float? integer? range of possible values?
in most cases, you could probably use an input_number, see here: https://www.home-assistant.io/integrations/input_number/
automation time trigger: https://www.home-assistant.io/docs/automation/trigger/#time-trigger
the template itself is OK, I am just after the time trigger!
thank you!!!
do you always use YAML for this or do you ever use node-RED?
will this work?
sensors:
power_cost_yesterday_total:
friendly_name: "Total kost i gΓ₯r"
unit_of_measurement: "kr"
icon_template: "mdi:cash-multiple"
value_template: >-
{% if is_state('sensor.time', '23:59') %}
{{ (states('sensor.power_cost_today_total')) }}
{% endif %}```
ahhh, no it won't. some more research. thanks luma π
Can't wrap my head around this. How can I trigger a template like the above with a timed trigger?
You don't trigger templates. Templates just are.
Triggers are an #automations-archived thing...
ah, thank you mono π My always guiding light π
Hi all, I have a template sensor that works perfectly in the template editor, passes the config check, but doesn't work in production. I get the following error: TypeError: 'NoneType' object is not callable. Any ideas?
Without seeing it? Nope.
What's the best way to send a large text block?
A code share site like the ones linked in the topic.
huh i'm trying to use this hastebin one but it won't give me a url to share
one sec
The UI reports 'Unknown' but the template editor shows the correct states
hastebin sucks, tbh. Doesn't always work, even after the UI loads. I prefer hatebin.com
Prettier too π
agreed!
Your YAML looks okay to me. What's the full error you're getting?
the error occurs when I call the homeassistant.update_entity on that sensor i created
i'll copy , one sec
again, I copy and paste the sensor data into the template editor and it works perfectly
but when I call to update the sensor to get the latest value, I get that error
You could try stripping the whitespace inside your template but I don't think it should cause that error.
This will remove the whitespace in whatever precedes or follows this line:
{%- something something -%}
Although I think your >- is supposed to do the same.
I'm not sure what else it could be. I'll leave it to the big brains.
thanks for taking a look
ding ding ding i think I found it
In my sensor setup in config.yaml, i had too many platform templates setup independently rather than nested. this thread explains it better and seems to have worked for me https://community.home-assistant.io/t/solved-template-sensor-giving-unknown-but-developer-template-shows-true/57433
how do I round a value within a template? {{ (value_json["service"]["storage"]["/media/frigate/recordings"]["used"] / value_json["service"]["storage"]["/media/frigate/recordings"]["total"]) * 100 | round(0) }}
I think this is working value_template: '{{ ((value_json["service"]["storage"]["/media/frigate/recordings"]["used"] / value_json["service"]["storage"]["/media/frigate/recordings"]["total"]) * 100|float)|round(0) }}'
thanks
Hey all! I've got an automation with a zwave scene trigger for a battery operated switch. I'd like to just use 1 automation but need to route to perform different actions based on values in the triggering scene_id and scene_data. Does anyone have any examples of what that might look like from a syntax standpoint?
Is there a way to reference the entity name in a template sensor's value_template and attribute_templates? Or the area that the entity is in? Eg:
- platform: template
sensors:
lounge_lux_difference:
unit_of_measurement: lx
value_template: >-
{% set room = self.entity_id|regex_search('^sensor.([_a-z]+)_lux_difference %}
{{ states('input_number.'+room+'_lux_target')|float - states('sensor.'+room+'_lux')|float }}
Reason: I've got the same thing in multiple rooms and I want to use the same yaml block for each
Again, as phnx said, think about the order of operations. You're telling it to convert 100 to a float (100.0) unnecessarily. If the value_json values are already floats then it'll still be a float when you * 100. You could get rid of the |float and just change the round(0) to an int
hi, a question with templating a sensor, im wondering if it is possible to do the following checks
- check iff (states('now().day()')==X , where x is todays day of the week
- based on that check in 1 pick time from an input_datetime., in total i have 7 different input datetime for each day of the week
I can make it work if i just use one, but im creating a schdeule with different times like to have it so that i can pick different times based on the weekday. So would i need to have 7 different sensors or can i template it into one to avoid the massive bulks of code ?
So I'm doing a similar sort of thing and what I went for was having a schedules.json file with a top level key of data, a command_line sensor to run jq on the file and giving it json_attributes of data. Plugging in your use case that would allow me to use state_attr('sensor.schedules', 'data')[now().day()] to get the schedule data
If the schedules aren't going to change much and you don't need to configure them in the UI of course.
Hi, thanks for the response, that sounds like a nice solution however im not the only one that will use it and it has to be quite easy and flexible so im going to use the ui for each of the time each day, but i think i found a simple "not so good looking" solution for it now, just need to test it out over a couple of days now to see if it triggers correcly π
There's a scheduler integration on HACS
π
Hi guys, my plan is to write a template which will change the rgb colour dependant from the humidity measurement. My first problem is where to put this template. (its my first try with a template). Will it just be entered in the configuration.yaml ? and if so how can I set value for the 3 rgb parameters and how can I get them back in the automation?
At the point your template is first read by HA, that sensor doesn't exist, so you can't reference any kind of 'self'. Besides, if you know the name of the sensor (you're writing it on the third line), you'd just hard code it in your template.
Trying to get clever and have self-references for something like that seems pretty daft.
You're going to copy/paste that block with a new name. It'll take you an extra two seconds to use that name in the other places it's relevant.
But 2 seconds (likely at least 10) done for multiple rooms over and over (while still testing and getting things set up correctly) gets time consuming quite quickly
But yeah, I'll just modify my bash template
Just wanted to confirm if there was a way or not
Nope. The scope for templates is the entire state machine of HA.
But I don't think it's daft if it's possible
There's no 'self', even once the sensor is initialised.
Cool cool, fair enough
hi, is there any execution order between the value_template and attribute_tempate? Can I rely on that I can update somehow the value of the sensor if the attributes were updated? (in a custom mqtt sensor integration)
If anything changes, the sensor is considered changed. If you're using that sensor in an automation, it'll check the triggers whether it was the state or the attributes that change.
I have two data sent separately, depending on which one was updated, these are the hue and the saturation. I want these as attributes of my color sensor and from this I want to make a hex rgb value as the sensor value regardless which one changed
That should be fine
hello, I am trying to change the value of an input number based on the difference between two values
currently, the code looks like this
is there anyway i can compress the action template to use trigger.to_state.state instead of the difference between the two sensor values ?
I have tried setting the action template to this:
however I am getting the following error: invalid template (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['action'][0]['data']. Got None.
please do not post codewalls
use paste.ubuntu.com and remove this. the server rules do not allow more than 15 lines for a reason
sorry, done, any hints?
Yeah, that's not how you do a multi-line value in YAML π
Use the > symbol and remove the quotes.
I changed it to this https://paste.ubuntu.com/p/dkmTKV3m73/ but i am still getting the same error
Now you need to fix the indentation of line 5 π
thanks mono, but it's not that, paste.ubuntu is actually screwing the indentation. Here is a copy-paste of the complete automation, which shows correct indentation
Then you're not getting the same error as before.
This is the error i am getting when reloading automations: Invalid config for [automation]: invalid template (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['action'][0]['data']. Got None.
if i replace {{ trigger.to_state.state }} with state_attr('climate.termostat_living', 'temperature')|float - states('sensor.multisensor_living_temperature_air')|float everything works fine
Oh... you're nesting templates π€£
{% if trigger.to_state.state > 1 %}
{% %} to 'calculate' something
{{ }} to return something
ok, getting closer
now i can reload the automation without any erros
however when i am triggering the automation i am getting Error while executing automation automation.automatizare_trv_living_procentaj: Error rendering data template: TypeError: '>' not supported between instances of 'str' and 'int'
States are always strings. You need to convert then using | int
i need to use float, something like this, right?
{% if trigger.to_state.state| float > 1 %}
Or use what I just said... convert to int.
not supported between instances of 'str' and 'int'
So make it int and int.
any idea why the automation only returns 30 even though the trigger is 2 for example?
when running the following code through the developers > template section i get 30 output in case the trigger is a string, could this be the cause?
Hello can someone tell me if it's possible to pass in the entity_id of the google speaker you are trying to initiate a script in Home Assistant from so it plays back on that speaker on not a speaker group. I have tried using the trigger.entity_id and this fails to work which I could got from the article https://www.home-assistant.io/docs/automation/templating/
This is my script right now that I am passing the the TTS service:
entity_id: trigger.entity_id
message: >-
We have received {{ states('sensor.rainfall_today') }} mm today and based on
the time between the last 3 tip rates it's raining at {{
states('sensor.rain_pr_hour') }} mm per hour
You can compare a float with an integer. In case the state will be e.g. 1.4, state|int > 1 will be false, and state|float > 1 will be true
If @fleet wyvern really wants to use int, I think {% if trigger.to_state.state| int >= 1 %} would be better.
Not completely sure, but I would expect that you can only use trigger.to_state.state when you actually use a state trigger.
I've been thinking about this as well, but when you start a script there is no trigger like in an automation. And Home Assistant just receives a command to start the script, there is no way for HA to determine from which device this was initiated as far as I know.
Actually that makes sense now regarding the piece about the trigger. Youβre right all I am doing is turning on the script. I am really interested to see how this can be done as you may have echo / google devices all round your house and if you want to call scripts that read back template values I would think you would want it to play back on the speaker your talking too and not a pre set speaker group. Hopefully someone will read this and propose a solution π
- service: script.myscript
data:
entity: "{{ trigger.entity_id }}"
In your script...
script:
myscript:
sequence:
- service: ...
data:
entity_id: "{{ entity }}"
As far as I understood @fleet tinsel SteveA correctly (and how I also would like to have it) is when I talk to my Google Home, and say something like "Hey Google, next garbage day" the Google Home will start a so called routine, which will start a script in HA. Included in this script is a TTS action which will respond to the Google Home something like "next Monday you need to take out the paper waste".
It would be great if HA somehow knows I'm asking this to the Google Home in the kitchen, and respond to that specific Google Home, and not to all, or to a predefined one in the script (e.g. Google Home Livingroom).
But as far as I know there is no way to determine from which Google Home/Google Nest device in your home the routine was started, and to send the TTS to that specific Google Home.
Hi, trying to figure out how to get the name attribute to be sent in the notify message..
The automation works, meaning the Trigger works, but I'm getting an error about the message as follow:
Error while executing automation automation.automation_44: Error rendering data template: UndefinedError: 'dict object' has no attribute 'item'
https://paste.ubuntu.com/p/X4F2qfcF58/
Any help will be much appreciated. π
Never mind, got it! π
trigger.event.data.item...
I am trying to set up a bond light to have multiple "states" for the brightness, in much the same way that there are speeds for a fan.
Getting a functional light working with bond that only does ON/OFF was trivial. But I can't quite seem to grasp how to set an attribute to a light that persists so I can compare current brightness to the brightness I am setting it to.
Where have I gone sideways?
This fails silently.
If however I do a light.turn_on without setting a brightness as part of the command I am told template rendered and invalid service curl <snip command>
Update: By wrapping the curl commands in a shell_command I can get the turn on / off logic working.
However it is still not reading the brightness accurately as it seems to default to the "Brightness is currently 0" control block
your brightness statements are whacky
- you're getting an attribute 'brightness' back from the set_level
How do I unwhack them?
you do not need to access it from the state machine
2 you should completely remove the logic of the input_number inside that
that light will contain it's own slider. If you want a slider to adjust the light, then you should make an automation
if you need the input_number so that the light can have a slider, then you need to add a service that sets that
you also need a level_template
nevemrind, it was above
I don't need a slider explicitly. I just need the option to set the state to OFF, DIM, BRIGHT
so, where are you getting the state OFF, DIM, and BRIGHT from?
This particular light has (with a bit of fudgery) 2 buttons set up in Bond, one toggles Bright / Off, the other toggles Dim / Off
I am trying to wrap those 2 buttons into a single 3 state light.
yes, but can you read the state of those devices?
no
ok
In my head cannon (without knowing all the tools available in HA), I need some variable to store the assumed state of the object (which I am attempting to use the input_number to do).
but, doing it poorly to say the least.
your set_level should be:
set_level:
- service: >
{% if brightness > 128 %}
...
{% endif %}
data:
brightness: "{{ brightness }}"
- service: input_number.set_value:
data:
entity_id: input_number.master_bedroom_fan_light_level
value: "{{ brightness }}"
but I don't think you need the data: brightness for your shell commands unless you use brightness in the shell command
I do not. The shell commands are just button toggles
then it's simply:
set_level:
- service: >
{% if brightness > 128 %}
...
{% endif %}
- service: input_number.set_value:
data:
entity_id: input_number.master_bedroom_fan_light_level
value: "{{ brightness }}"
Don't use the input_number in your logic for calling the shell commands
and don't put the input number in your UI
how do I get the previous brightness level as part of my command then?
the light will control everything, not the input number. The input number is to simply store the current brightness for the light
That is my end goal, so I appreciate the confirmation.
as an example:
If the light is currently dim, and I want to make it bright.
toggle dim, and toggle bright.
If the light is currently off, and I want to make it bright.
toggle bright
the steps I take are dependent on the current state.
I think your intended use case is going to be wonky
if that's what you want, you should just make buttons in the UI
no point in making a light template
My use case is "I have a stateless dimming light that I want to be able to control into 3 known states"
and what happens when you are on the upper state and restart?
you'll now have 3 known states 1 which is useless
or worse case, you're at the upper limit and it thinks your on the lower limit
now you have 1 state with 2 useless states
agreed, it is imperfect. But I have a manual override in that event (via the remote)
not to mention a slider won't work like that
once you increase the slider to max, it's not going to magically drop down
I am not following
the range of your brightness is zero to 255
I would be fine if it was 0-2
not possible, lights inherently have 0-255 in HA
no problem
so, you're at 0, 255/2, and 255
yep
ok, if you increase it from 255/2 to 255. The slider position will now be at 255. You can't increase it anymore
im following so far.
Ok, so if that's what you want then what I posted is all you need and you don't need the previous state.
i still don't see how I would not need the previous state
0 on the slider is zero
if brightness = zero run script a
if brightness = 255/2 run script b
if brightness = 255 run script c
nothing more
if you want the values between, you have to do math
and I can help you with that
in this case is the slider and brightness representing different values?
the slider would be set to 24 and you'd have to decide how you'd want that to translate to script a
is script a 0 to half of 255/2?
you have a full range of numbers. 0 to 255, how does each number map to the script you want to run?
the first 33% is script a?
the second 33% script b?
you follow?
If I set the slider to anything between 1-255/2 I want the exact same thing to happen>
HOWEVER: If the current brightness value was 200... it does different stuff than if it was 100
yes
Put another way
200 -> 0 runs script A
100 -> 0 runs B
{% if brightness < 84 %}
script.a
{% elif 84 <= brightness < 168 %}
script.b
{% else %}
script.c
{% endif %}
that simple
I am like 99% sure that doesnt work
i'm 99% sure that does
I am putting it in now just to smoke test it, but I need to run different commands based off the previous state of the light.
and I cannot logically see how that works here.
set_level:
- service: >
{% if brightness < 84 %}
script.a
{% elif 84 <= brightness < 168 %}
script.b
{% else %}
script.c
{% endif %}
- service: input_number.set_value:
data:
entity_id: input_number.master_bedroom_fan_light_level
value: "{{ brightness }}"
remember, you'll be adjusting the brightness on the light, not the input_number.
right, but my script says "toggle this thing that I dont know the state of"
yep
so if I say "turn off the top light, and turn off the bottom light" since they are the same physical bulb... it turns off the bulb, then turns it right back on
what the hell are you talking about?
the part of this that makes this system difficult.
I found that my remote sends 2 different signals based off a hardware toggle inside of the remote itself (after opening it up).
Signal A: Toggles the light between full bright, and off
Signal B: Toggles the light between some preset dimness, and off.
2 input_numbers, 2 lights, then a single light group
I mapped those signals to 2 different buttons. But since they are both the same toggle, turning A on when B is already on actually sets both lights to on, but the physical light is off.
Is that the better way to be doing this? I know nothing about light groups.
wait, no. Don't make a light group, it's just impossible to follow this code and your description.
Can I make a light group with mutually exclusive order dependent lights?
so let me see if I follow this now
You have 4 commands
shell_command.master_bedroom_fan_downlight_off
shell_command.master_bedroom_fan_downlight_on
shell_command.master_bedroom_fan_uplight_on
shell_command.master_bedroom_fan_uplight_off
yes
you want combinations of them to equal brightnesses
you could think of it that way.
Perhaps my naming is poor. They are named as such because that is the name of the virtual button I bound them to using Bond. (Up Light, Down Light)... but they are 1 physical bulb, the names don't matter. It could be mapped to FanSpeed1, FanSpeed8. I just needed buttons.
ok, so does on increase the brightness of downlight?
DownLight is a toggle switch click it, it goes dim. click it it goes black, dim, black, dim, black.
UpLight is a toggle that goes bright, black, bright, black.
There is no brightness adjustment, I have no control over variable brightness
I can toggle between 0 and 50, or 0 and 255 depending on the button.
right i get that, it's a static change
but if you click the up brightness once from off position, is it fully on at max brightness?
yes
ok, then you only have 4 states. [ 0, 0], [ 0, 1], [ 1, 0], [1 ,1 ]
not quite. Logically yes, but things get odd
how do they get odd?
Lets start at brightness 0, both lights off.
DownLight = 50
DownLight = 0
UpLight = 255
UpLight = 0
UpLight = 255
DownLight = 0 <- At this point Uplight and Downlight would be on, but the brightness is 0 because the bulb sees them as the same button, thus toggled it off.
Or more simply
Down: 0->50
Up: 50->0 (But I want 50->250)
only if the other is already on.
ok, then you need to incorporate the previous value
All states start at 0 with both toggles assumed off
D toggles the light between 0 and 100
U toggles the light between 0 and 255
Now:
D -> D: 0 -> 100 -> 0
U -> U: 0 -> 255 -> 0
D -> U: 0 -> 100 -> 0
U -> D: 0 -> 255 -> 0
Goal:
D -> D: 0 -> 100 -> 0
U -> U: 0 -> 255 -> 0
D -> U: 0 -> 100 -> 255
U -> D: 0 -> 255 -> 100
{% set previous = states('input_number.master_bedroom_fan_light_level') | int %}
then perform your logic
but you still need to set the slider
with a service call. It has to be after you call your scripts
like I posted above
- service: input_number.set_value:
data:
entity_id: input_number.master_bedroom_fan_light_level
value: "{{ brightness }}"
this one?
The reason you aren't getting brigthness updates on your light is because you aren't calling the input_number.set_value service where you set the brightness on the slider. This will act as your stored brightness state and your level_template will feed off it and use that as a representation of your current brightness level
yes that one
and how do I use the set previous? it is another input_number?
It makes sense what you are saying about the brigtness not being saved because I was not setting the value.
no, when the template executes, input_last number will have your previous brightness
so just grab the information from that input_number
{% set previous = states('input_number.master_bedroom_fan_light_level') | int %}
{% if brightness > 128 and previous > 128 %}
...
then your service call will update the input_number after that template is executed and your scripts are called. Effectively changing your previous value to a new value.
I did not know I could set variables like that. I assume "previous" gets cleared out once the template is finished executing?
You as a user move the Light slider -> home assistant excutes template with brightness as an incoming variable in the first service call that calls your script -> then input_number is updated with brightness
1 action performed by you. 2 service calls performed in the background.
When there are multiple service calls, it needs the preceding dash?
I am trying to figure out my indentation cause adding in those dashes made it a bit funky
Updated: https://pastebin.com/8bJZG8m3
yeah but you should remove data: brightness for the script call
bad indentation of a sequence entry at line 122, column 40: ... service: input_number.set_value:
done
hold on
I appreciate your help btw.
I am sure you jumped in for an easy win... and this was not that.
set_level:
- service: >
{% set previous = states('input_number.master_bedroom_fan_light_level') | int %}
{% if brightness > 128 and previous > 128 %}
script.noop
{% if brightness > 128 and previous > 0 %}
shell_command.master_bedroom_fan_downlight_off
shell_command.master_bedroom_fan_uplight_on
{% elif brightness > 128 and previous == 0 %}
shell_command.master_bedroom_fan_uplight_on
{% elif brightness > 0 and previous > 128 %}
shell_command.master_bedroom_fan_uplight_off
shell_command.master_bedroom_fan_downlight_on
{% elif brightness > 0 and previous > 0 %}
script.noop
{% elif brightness 0 and previous == 0 %}
shell_command.master_bedroom_fan_downlight_on
{% elif brightness == 0 and previous > 128 %}
shell_command.master_bedroom_fan_uplight_off
{% elif brightness == 0 and previous > 0 %}
shell_command.master_bedroom_fan_downlight_off
{% elif brightness == 0 and previous == 0 %}
script.noop
{% else %}
script.noop
{% endif %}
- service: input_number.set_value:
data:
entity_id: input_number.master_bedroom_fan_light_level
value: "{{ brightness }}"
that should work out of the box
if your logic is correct
to me, it seems like it can be streamlined and simplified becaus eyou have a few noops that can be lumped into 1 if statement
I am still getting an indentation error here.
did you copy/paste what I wrote?
Yes. I 100% can clean it up. It is in an expanded state while I figured out the logic.
Yes
paste the error
bad indentation of a sequence entry at line 120, column 40:
... service: input_number.set_value:
is it the trailing colon?
ah yep
does not match format <domain>.<name> for dictionary value @ data['lights']['master_bedroom_fan_dimmable']['set_level'][0]['service']. Got "{% set previous = states('input_number.master_bedroom_fan_light_level') | int %} {% if brightness > 128 and previous > 128 %}\n script.noop\n{% if brightness > 128 and previous > 0 %}\n shell_command.master_bedroom_fan_downlight_off\n shell_command.master_bedroom_fan_uplight_on\n{% elif brightness > 128 and previous == 0 %}\n shell_command.master_bedroom_fan_uplight_on\n{% elif brightness > 0 and previous > 128 %}\n shell_command.master_bedroom_fan_uplight_off\n shell_command.master_be.... (See ?, line ?).
Every if/else combo is accounted for, and all cases follow that pattern
is it due to the setting of previous?
you can't have double service calls
bummer
make a script
script:
service_caller:
variables:
services: "{{ services | default(['script.noop']) }}"
sequence:
- repeat:
count: "{{ services | length }}"
sequence:
- service: "{{ services[repeat.index - 1] }}"
then, use that as your service
and change your template to...
Im going to need some talking through of this one.
I am not quite following what your script is doing.
It calls in reverse order an array of services?
not sure where you're getting reverse order
it looks like it was recursive counting down (idx-1)
set_level:
- service: script.service_caller
data:
services:
{% set previous = states('input_number.master_bedroom_fan_light_level') | int %}
{% if brightness > 128 and previous > 128 %}
[ 'script.noop' ]
{% if brightness > 128 and previous > 0 %}
['shell_command.master_bedroom_fan_downlight_off', 'shell_command.master_bedroom_fan_uplight_on']
{% elif brightness > 128 and previous == 0 %}
['shell_command.master_bedroom_fan_uplight_on']
{% elif brightness > 0 and previous > 128 %}
['shell_command.master_bedroom_fan_uplight_off', 'shell_command.master_bedroom_fan_downlight_on']
{% elif brightness > 0 and previous > 0 %}
['script.noop']
{% elif brightness 0 and previous == 0 %}
['shell_command.master_bedroom_fan_downlight_on']
{% elif brightness == 0 and previous > 128 %}
['shell_command.master_bedroom_fan_uplight_off']
{% elif brightness == 0 and previous > 0 %}
['shell_command.master_bedroom_fan_downlight_off']
{% elif brightness == 0 and previous == 0 %}
['script.noop']
{% else %}
['script.noop']
{% endif %}
- service: input_number.set_value:
data:
entity_id: input_number.master_bedroom_fan_light_level
value: "{{ brightness }}"
but I could be misunderstanding how it functions
index's in code start at 0
repeat.index starts at 1
so repeat.index - 1
lol, well that solves it
2 quick fixes:
Remove the colon after set value
Add a > after the first services
yea yea
Technically... you can omit the last 2 if statements too
because it defaults to noop
Invalid config for [light.template]: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'integer') for dictionary value @ data['lights']['master_bedroom_fan_dimmable']['set_level'][0]['data']. Got OrderedDict([('services', "{% set previous = states('input_number.master_bedroom_fan_light_level') | int %} {% if brightness > 128 and previous > 128 %}\n [ 'script.noop' ]\n{% if brightness > 128 and previous > 0 %}\n ['shell_command.master_bedroom_fan_downlight_off', 'shell_command.master_bedroom_fan_uplight_on']\n{% elif brightness > 128 and previous == 0 %}\n ['shell_command.master_bedroom_fan_uplight_on']\n{% elif brightness > 0 and previous > 128 %}\n ['shell_command.master_bedroom_.... (See ?, line ?).
I will keep that in mind when I start pairing it down
Oops there was a dropped > in the comparisons.
didnt solve the error, but it would have become one.
is that still the error?
yes
can you post the code?
1 second... I forgot there was a Templete Editor and it was a bit more readable that way.
brightness is undefined is where I am now.
pasteing code
Updated: https://pastebin.com/8bJZG8m3
is the light created?
In the Template Editor I get UndefinedError: 'brightness' is undefined
If I Check Configuration I get the above longer error.
Do you wish for me to reload the templates anyways to check the light?
Sorry... It is a new error now.
Invalid config for [light.template]: invalid template (TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.) for dictionary value @ data['lights']['master_bedroom_fan_dimmable']['set_level'][0]['data']. Got OrderedDict([('services', "{% set previous = states('input_number.master_bedroom_fan_light_level') | int %} {% if brightness > 128 and previous > 128 %}\n [ 'script.noop' ]\n{% if brightness > 128 and previous > 0 %}\n ['shell_command.master_bedroom_fan_downlight_off', 'shell_command.master_bedroom_fan_uplight_on']\n{% elif brightness > 128 and previous == 0 %}\n ['shell_command.master_bedroom_fan_uplight_on']\n{% elif brightness > 0 and previous > 128 %}\n ['shell_command.master_bedroom_.... (See ?, line ?).
brightness won't be defined inside the template editor
because brightness ojnly exists in the set_level environment
still same error? template looks fine
nope all configs fixed.
oh duh
there was multiple if statements when we meant elif
I have a light
Updated Paste with non-erroring code: https://pastebin.com/8bJZG8m3
yep
sliding the slider should perform those actions
now at this point you need to verify your logic is correct
now that you have the format down
the slider can only go from 1-100
Well that's new
the brightness should still be 0 to 255
so none of that should change but the values in your head will change
well, it is going to change the value template logic
nope
do tell
brightness should still come across as 0 to 255
the slider is for the UI
it's translated for the user
you can verify that by looking at the input_number
just don't adjust the input_number
Ahh, I need to also set the input_number when I call turn_on and turn_off
otherwise the number will never hit 0
either way, you should understand enough to move forward
It is actually working. It is a bit janky and there are a few bugs, but it is doing what I want it to do.
My hero petro
nice, i'm not responding next time π
hahaha
I am sorry that was such a nightmare. I will work on trying to more accurately describe the uniqueness of the problem.
not your fault, it's the light
Ah
so, i went a different route
I have a similar fan
I connected a device that uses the current to detect the state
removed that stupid remote
link the device?
I thought about that, but without really tearing the thing apart... I couldnt
nope
we bought the fan and installed it, then went to hook it up to the "dead lightswitch" we had which we thought was a traveller to the fan, just to find it was to an outlet that got removed during an addition.
so we only have a 3 wire going up to fan, not a 4 (hot, copper, neutral)
ah, yeah I have 4
but I had a choice... do I power both lights with 1 input or use the stupid remote
I chose 1 input
for me, I only have 1 light
ah but the fan is the other light in your situation?
you don't have a light that projects out the top and a light that projects out the bottom?
ah
but I have a hardware switch that changes how the remote functions.
so I digitally 'wired' the dim light to that "upper light" you mentioned
dunno
I am, it works as horribly as I could have hoped.
If you have any thoughts in the future about devices I could wire in to make this less stupid let me know.
I'd check out ESPHome devices
Right, the time I lost programming it was greater than my lifetime of hitting the switch!
they are DIY, but you can basically build anything you want
you could also look into sonoff relays
not sure how they are powered though
ESP had the same problem, it was limited to the commands that my fan would take... and it only would take this odd toggle on/off garbage.
now... if there was a super small one I could wire directly behind the lightbulb (microshelly)... I could make something work.
Yea I would need something like 10% the size of a sonoff, or to do some serious re-wiring within the fan to get that working.
But I have 4 more fans to install, so I will look into hardware mods I can make before the install on those.
Thanks again.
Yeah np
If you ever run into me on the street... I'll buy you a coffee, or I dunno... a contact sensor.
Haha no need, just glad to help
(I don't want you to think it was all for naught... but I think it might have been all for naught)
I tested the automation needed to tie it into an working switch... and it was awful... Took like 3 seconds to turn on the light from a switch, and the room goes totally dark for 2-3 seconds when the light goes from dim to bright.
hello, is it possible to test a rest get json template in dev tab? im trying to extract data from a json nested dictionary using an api http get request.
{{ value_json.dump }}```
thanks @dreamy sinew , do i specify the rest platform and http resource in dev tools template?
you using the template tester right?
make the rest call manually and get the response. Dump that response into a var. write a template to process
you don't need anything else
@dreamy sinew understood.. cheers
hi, this gets me the value of' 'n' from a nested dictionary whos key is '1' . how can i get all the keys and corresponding 'n' values if i dont know the key values beforehand?
{{ value_json["1"]["n"] }}
.share the payload you're parsing
bot's dead....
Please use a code sharing site for the response payload
paste.ubuntu or hastebin
@dreamy sinew https://paste.ubuntu.com/p/SnxKhDrXGP/
that's pretty terrible
π ... i know
what key do you want?
the keys are 0, 1, 2, 3 in this example but can be anything like A, BB, 3C etc. I want to read these keys and also their 'n' value from their nested dict. thanks
its the name given to the preset id (key). the preset and name can be any value .
{{ value_json.values()|reject('eq', {})|map(attribute='n')|list }}
gives you a list of the n values
but you want the keys too?
yes, was just about to ask that after testing it , cheers
my light hub gives each light an id and I can then assign that id with a name (kind of like friendly name for entitres in HA). I want to have an input select list of available lights in their friendly name format but then also know which id they correspond to since any put api requests i make need the id for the light hub to execute
yeah this isn't going to work then
probably need a custom component or something to pull this out in python
ok, trying to avoid appd unless absolutley necessary.
if i keep it simple so that the id are just number from say 0 to 20 then I could loop with some sort of incremental count but not sure how to deal with missing ids ie 3 missing in 1, 2, 4,5. is there a way to program next key instead of the counting method?
thanks @dreamy sinew ... shame there isn't a way to just extract keys as that would be more useful than the 'n' values
you can get either and make a list but you can't then put them back together
that may work ... how do I change your earlier code to get just the keys ?
@dreamy sinew this seems to be on the right track for getting key and nested dict. can it be edited to give n instead of the whole nested dict per key?
{% for key, value in dict_item.items() %}
{{key}}
{{value}}
{% endfor %}
{% endfor %}```
that'll print a bunch of stuff out but you won't be able to use it
You could create a dummy template sensor with that as an attribute_template
Or better, format it as json output
Hi there! I need to test for two states like below, but unfortunatelly this syntax is wrong.
How can I accomplish this?
{% if is_state('light.lys_tilleggslys', 'off') AND is_state('binary_sensor.dark_inside_2', 'off') %}
Entire service call in the script:
- service: >
{% if is_state('light.lys_tilleggslys', 'off') %}
script.lys_tilleggslys_on
{% else %}
script.lys_tilleggslys_off
{% endif %}
I think I found the error: must be lower case and
yup
can i "convert" a threshold sensor into a binary sensor using template?
A threshold sensor is already binary. It only shows on/off.
Itβs an alternative to the template binary sensorβs value_template: to get the abnormal/too high/too low states.
But you're using custom cards, right? You can customise everything π
To answer your original question... yes, you can create a template binary sensor... but don't try to convert the threshold sensor, just make a template binary sensor that does what you want.
mono, how do you feel about wrapping sensors in other sensors?
What's the context? π€
Most of the time, there's no need. However, if you're trying to create a binary sensor out of information from a non-binary sensor, that's a valid use case.
Want a binary sensor that you can use everywhere when the humidity is over 80%? Binary sensor wrapping the humidity sensor. Of course, you could use templates everywhere instead... but having the binary sensor makes it explicit and easier to use.
Using the value of the inner sensor to populate data in the outer sensor (for node-red automations)
NR? π€’
I thought NR could do everything so much more easily than HA alone? Why does it need you to wrap sensors?
All the NR fanboys talk like it's a one-stop shop and can do everything π€·ββοΈ
Meh. I like to be in control and I don't need a visual tool holding my hand... but to each their own.
TBF before I wrapped these sensors with the correct data nicely I was mostly writing big blocks of javascript for it
I am intrigued by the automation blueprints though
HI i am getting a warning log which from what i have read relates to templates but i do not have any. PLease somebody help me fix the issue or point me to relevant article?
Logger: homeassistant.components.template.sensor
Source: helpers/config_validation.py:751
Integration: template (documentation, issues)
First occurred: 12:48:21 (2 occurrences)
Last logged: 12:48:21
The 'entity_id' option is deprecated, please remove it from your configuration
Looks like it's about a sensor. Share the config that it's complaining about and we'll have a better idea.
Sorry i have no idea what config is it referring to
Looks like you have a template sensor in which you're setting entity_id . Have you looked through your template sensors?
i donβt use templates
Try using dev tools to set the logger level to debug for homeassistant.components.template.sensor and run the config check
Let me re phrase it i am on week 3 of HA i have not set up any templates
Somewhere in your config, you have something with platform: template written in it. Find that thing.
Ah, week 3. Templates aren't used until week 6 of the course.
Don't skip ahead in the syllabus π
lol
If you're on any Linux based install then cd to your config directory and grep -r 'platform: template' *
You've been here since September... did you fall asleep π€
if you add up all the days on discord, it's 3 weeks
The first few months are the theoretical part of the course. You don't get practical till later
Do template switches use sensors under the hood?
They have to read from something. That something might be another sensor.
sensors use templates under the hood
Indeed, but it's template.sensor that's complaining, not template.switch
yep, so that's where he should be looking for the entity_id field that he needs to remove
There you go
yeah, remove entity_id: sun.sun, pretty self explanatory
and before you ask, no you don't need to alter the template
? Just remove the line from my sensors.yaml file
yes
Although if you look at the style guides in the docs you should probably change states.sun.sun.attributes to state_attr('sun.sun, 'next_rising')
use your eyes and look at the next template
you only removed one of them
there were 2
everything you posted is fine. Also saying "still not liking it" without posting an error isn't really helpful. Lastly, make sure you aren't looking at the old error.
Missing a single quote after sun.sun
i mean config validation
state_attr('sun.sun, 'next_rising') isn't valid π

Totally my fault
/chaosmonkey
missing closing ) on as_timestamp
missing closing ) on as_timestamp
Still
remove the ) at the end after the }} too, that's the wrong spot
Do you understand how () work?
it's like boxes in boxes, you never know what you will get
{{ as_timestamp(state_attr('sun.sun', 'next_rising') | timestamp_custom)(' %I:%M %p') | replace(" 0", "") }}
icon_template: mdi:weather-sunset-up
as_timestamp(state_attr('sun.sun', 'next_rising') |
Count the opening and closing brackets
Also, timestamp_custom(' %-I:%M %p')
Notice the - between the % and I
I think he's given up?
nope
If you're new to templates... test them in the Dev Tools π
Don't keep guessing and having to reload your config.
ok, are you understanding?
trying
ok
confused this has been working for weeks then i remove enitity id and it now is all wrong
so, when you have a method or a function that you call, and it has items that you pass into it, you pass them inside opening and closing ()
It's only not working because @glad geode (evil) suggested making edits to the template
You didn't need to make edits, you could have left the template the same
Evil and pedantic
Lol
anyways, back to the function or method. You have 2 functions you're dealing with
as_timestamp()
and
state_attr()
when you put a function inside another function, you have to make sure opening and closing () exist for each function.
state_attr() π
In my head another )
yup
Right
so where do you put it
remember
you have
as_timestamp(state_attr('sun.sun', 'next_rising')
after next rising
Yes
bigger error now
did you leave the ) after the }} when you made the initial mistake?
You left in all your ) mistakes
you just said i needed to put in 'next_rising'))
Right
but you made a bunch of ) errors when you were trying things out
and you didn't remove them
I count 2
value_template: >
{{ as_timestamp(state_attr('sun.sun', 'next_rising')) | timestamp_custom)(' %I:%M %p') | replace(" 0", "") }}
still see 1
arrh after custom
yep
Invalid config for [sensor.template]: [nextsunset] is an invalid option for [sensor.template]. Check: sensor.template->sensors->nextsunrise->nextsunset. (See ?, line ?).
Do yourself a favor, use a text editing software that highlights opening and closing brackets, quotes and {}
using vsc
But first, fix the indentation π
{{ as_timestamp(state_attr('sun.sun', 'next_rising')) | timestamp_custom (' %I:%M %p') | replace(" 0", "") }}
icon_template: mdi:weather-sunset-down
It thinks nextsunset is a child of nextsunrise
already had done that
config passed now adjusted spaces
but yes it has wrong name
next_rising should it be next_setting?
Yeah, it should
done error gone
i have one more but not sure if it is a template issue
Logger: homeassistant.components.sonos.media_player
Source: components/sonos/media_player.py:692
Integration: Sonos (documentation, issues)
First occurred: 14:40:09 (2 occurrences)
Last logged: 14:40:09
Unhandled favorite 'Episode Five: Cyber Power (Part II) - Hacking ISIS': Unknown UPnP class: object.item.audioItem.podcast
I have checked the Sonos and removed the podcast from the playlist re powered it but error still keeps popping up
That's one for #integrations-archived I think
cheers for you help
π
hello I have a list of sensors with different numeric attributes and I would like to sort the sensors in ascending order on an attribute how can I proceed?
Have you checked the pins? There's a bunch of filters you can use for utility stuff like that.
Hi everyone, I'm having a small problem with a value_template of a mqtt sensor that receives data in the json format. My themplate is the following: "{% if value_json['State'] == '7' %}{{now()}}{% endif %}" THe sensor value is always null. Is there something wrong with the template?
Just found the problem. There should be no '' around 7.
So now the sensor gets updated everytime mqtt message arrives with either now() or None. Is there a way it retains its previous value in case the if evaluates to false?
not unless you save that value somewhere else to pull from
got it!
hello how to have a random time?
Random time of day? Random time from all history?
Of day for presence simulation
I have a template sensor that is retrieving an attribute from a device, and sometimes the value changes quickly from one value to another. Is there a way to make sure every change is captured in the sensor history?
I am using the Uptime Robot integration to pull the online status. The status shows as "Connected", but I'd like it to display "Online" instead. I tried this, but it is displaying Issues when it should be showing as Online.
sensor:
- platform: template
sensors:
my_personal_website_status:
friendly_name: "My personal website status"
value_template: >-
{% if is_state('binary_sensor.my_personal_website', 'Connected') %}
Online
{% else %}
Issues
{% endif %}
Is it because uptimerobot is a binary_sensor & I made the template within sensor?
Put that in your template screen and you will see my_personal_website is not what you expected
I put this into Developer tools > Template:
My website is: {{ binary_sensor.my_personal_website }}
{% if is_state('binary_sensor.my_personal_website', 'Connected') %}
Online
{% else %}
Issues
{% endif %}
I got this result: UndefinedError: 'binary_sensor' is undefined but I am using binary_sensor.my_personal_website to display Connected in LoveLace currently. Why is that? Forgive me, I am very new to this.
since you put it inside {{}} it thinks its a variable which it isn't and fails
{{ states.binary_sensor.my_personal_website }} seems to return:
<template TemplateState(<state binary_sensor.my_personal_website=on; attribution=Data provided by Uptime Robot, target=https://mypersonalwebsite.com, friendly_name=My personal website, device_class=connectivity @ 2021-02-24T19:39:22.361753-05:00>)>
I'm not sure where to find the "Connected" status that binary_sensor.my_personal_website is reporting in lovelace.
AHA, just figured it out.
{% if is_state('binary_sensor.my_personal_website', 'on') -%}
Online
{%- else -%}
Offline
{%- endif %}
It is reporting as On, not Connected.
Hello everybody.
I have this timer:
time_warm_floor:
name: Π’Π΅ΠΏΠ»ΡΠΉ ΠΏΠΎΠ» Π²ΡΠΊΠ» ΡΠ΅ΡΠ΅Π· -
duration: '05:00:00'
Its working, but I need to enter this parameter manually from Lovelace. I create input_datetime:
input_time_timerwarmfloor:
name: Π’Π°ΠΉΠΌΠ΅Ρ ΡΠ΅ΠΏΠ»ΠΎΠ³ΠΎ ΠΏΠΎΠ»Π°
has_date: false
has_time: true
I change the timer parameters to:
time_warm_floor:
name: Π’Π΅ΠΏΠ»ΡΠΉ ΠΏΠΎΠ» Π²ΡΠΊΠ» ΡΠ΅ΡΠ΅Π· -
duration: '{{ states("input_datetime.input_time_timerwarmfloor") }}'
And I get a configuration error:
Invalid config for [timer]: offset {{ states("input_datetime.input_time_timerwarmfloor") }} should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['timer']['time_warm_floor']['duration']. Got '{{ states("input_datetime.input_time_timerwarmfloor") }}'. (See /config/configuration.yaml, line 9).
Help me please.
@iron night put your code on share code site like pastebin.ubuntu
My power supply company has an API from where I can read my power consumption, grouped in 15 min intervals.
But the data is not up-to-date, as they have a time delay of ~8h.
Does anybody know how could I tell HA to time-shift the values?
I apparently made a syntax error, but I can't find it.
as far as my knowledge is very limited in this i can see that offset should be in another format , not jinja, but time
but i cannot help you
@iron night if u want some offset for triggering heat floor maybe this can help https://community.home-assistant.io/t/how-to-use-offset-properly/45823/11
can someone give me a hint? I have an entity with lots of attributes. If I use
{{state_attr('weather.dwd_weather_duesseldorf', 'forecast')}}
it returns
{
"datetime": "2021-02-25",
"condition": "rainy",
"temperature": 18,
"templow": 11,
"precipitation": 1.1,
"precipitation_probability": 58
},
{
"datetime": "2021-02-26",
"condition": "rainy",
"temperature": 11,
"templow": 4,
"precipitation": 2.8,
"precipitation_probability": 74
}]```
however I only want to recieve the value of precipitation_probability for today. how do i do that?
maybe u can try '{{ states.sensor.dwd_weather_duesseldorf.attributes["precipitation_probability"]}}'
{{states.weather.dwd_weather_duesseldorf.attributes["precipitation_probability"]}} gives no result
u put ' ' ?
im trying in the template editor in lovelace
i think the " are only necessary in the yaml or?
{{states.dwd_weather_duesseldorf.attributes["precipitation_probability"]}}``` still no output
hmm...forecast needed...
if i check the entity in lovelace the structure looks like this:
humidity: 66
pressure: 1026.8
wind_bearing: 161
wind_speed: 16.7
visibility: 34.7
attribution: Data provided by Deutscher Wetterdienst (DWD)
forecast:
- datetime: '2021-02-25'
condition: rainy
temperature: 18
templow: 11
precipitation: 1.1
precipitation_probability: 58
- datetime: '2021-02-26'
condition: rainy
temperature: 11
templow: 4
precipitation: 2.8
precipitation_probability: 74```
and i want to template in particular the precipitation probability of today and get it as a number to use it in another system
somebody more experienced could help you π i have something similar except that i use rest and template because is not my sensor , but web sensor https://pastebin.ubuntu.com/p/dtzswkxdXn/
properties are on the same level as forecast for you
and u need an attribute of forecast
Hi all, I'm trying to set up a light template and I cannot understand how to use set_color. This is the code I've done so far but it doesn't work:
set_color:
- service: light.turn_off
data:
entity_id: light.striscia_led_cucina_bianco
- service: light.turn_on
data:
entity_id: light.striscia_led_cucina_rgb
hs_color: "({{ h }}, {{ s }})"
Can someone please support me?
maybe this helps you:
action:
- data:
brightness: '{{states("input_number.hue_sunrise_brightness")| int}}'
color_temp: '{{states("input_number.hue_sunrise_color") | int}}'
transition: '{{(states(''input_number.alarm_clock_tado_wd_fadelight'')| int
*60)}}'
entity_id: light.bett
service: light.turn_on
brightness and color_temp are integers 0-255
what are those input_number?
are somehow "mandatory"?
i have them exposed in lovelace so i can manually set them
ah ok so you use them to change brightness for example. But how can I use color whell in webui for example?
color *wheel
maye use something like this https://community.home-assistant.io/t/light-entity-card/96146
sure but it will be impossible to set color via voice control isn't it?
mhm ok i do this via siri
but never actually use it
homekit & siri natively can set lamps to defined colors
so with siri you can set light color even if values are set via input_numbers??
Hello!
I have the following incoming byte (the following comes all together and keeps updated) through serial as follows for example:
EE 234
AA 1234
BB 4321
CS 1264
SYS ON
HSDS 3321
PID 555
I am successfully decoding the serial and added it as a sensor. It does not show all values at once the hassio but I see it quickly go through all the lines, i.e.:
VoltageFriendly HSDS 3321
How can I parse all the above key values into separate sensors?
I tried the following:
- platform: template
sensors:
mysensororvoltage:
friendly_name: VoltageFriendly
unit_of_measurement: "mV"
value_template: "{{ states('sensor.500w_rs232').split('\n')[1]}}"
value_template: "{{ state_attr('sensor.500w_rs232','PID') }}"
one sensor with the raw values and then individual sensors that parse that one for their targeted values
That is an interesting idea.
- platform: template
sensors:
myrawsensor:
value_template: "{{ states('sensor.500w_rs232')}}"
mysensororvoltage:
friendly_name: VoltageFriendly
unit_of_measurement: "mV"
# value_template: "{{ states('sensor.500w_rs232').split('\n')[1]}}"
value_template: "{{ state_attr('sensor.500w_rs232','PID') }}"
How can I target VoltageFriendly to one parameter in the raw sensor?
what are the actual control charecters in that string? is it \n?
Each byte is sent with the above string I showed as a block. Between each parameter and it is value (separated by tab) there is \n
So for example (from the above string), the goal is to create sensors as follows:
sensorEE = 234, sensorAA=1234, and so on..
yeah, this is kinda tricky to deal with
{{ value.split()[-1] }}
{% endfor %}```
replace sensor with states('sensor.myrawsensor')
replace PID with whatever one you're wanting to pull
that's as concise as i could get it
Thank you! After few hours of tweaking I got it to work but not perfectly because I am getting random zeros. I shall investigate further. Thanks!
Hey everyone! Im a complete beginner if it comes to Home Assistant and i cant get a template to work. I got my Fritz!DECT 210 Today. It works fine with my Fritz!box and i can also turn it on and off on Home Assistant. But i try to get the current_power_w, total_consumption and such. so i can display them better.
sensor:
- platform: template
sensors:
fritz_dect_210_1_watts:
friendly_name_template: "{{ states.switch.fritz_dect_210_1.name}} Aktueller Verbrauch"
value_template: '{{ states.switch.fritz_dect_210_1.attributes["current_power_w"]}}'
unit_of_measurement: "W"
fritz_dect_210_1_total_kWh:
friendly_name_template: "{{ states.switch.fritz_dect_210_1.name}} Gesamt Verbrauch"
value_template: '{{ states.switch.fritz_dect_210_1.attributes["total_consumption"]}}'
unit_of_measurement: "kWh"
fritz_dect_210_1_temperature:
friendly_name_template: "{{ states.switch.fritz_dect_210_1.name}} Aktuelle Temperatur"
value_template: '{{ states.switch.fritz_dect_210_1.attributes["temperature"]}}'
unit_of_measurement: "Β°C"
thats my config, but i always get the error
Invalid config for [sensor.template]: invalid slug fritz_dect_210_1_total_kWh (try fritz_dect_210_1_total_kwh) for dictionary value @ data['sensors']. Got OrderedDict([('fritz_dect_210_1_watts', OrderedDict([('friendly_name_template', '{{ states.switch.fritz_dect_210_1.name}} Aktueller Verbrauch'), ('value_template', '{{ states.switch.fritz_dect_210_1.attributes["current_power_w"]}}'), ('unit_of_measurement', 'W')])), ('fritz_dect_210_1_total_kWh', OrderedDict([('friendly_name_template', '{{ states.switch.fritz_dect_210_1.name}} Gesamt Verbrauch'), ('value_template', '{{ states.switch.fritz_dect_210_1.attributes["total_consumption"]}}'), ('unit.... (See /config/configuration.yaml, line 13). Please check the docs at https://www.home-assistant.io/integrations/template
I cant read what is wrong. Can someone help me out here to understand what the issue is?
The error literally tells you what to do.
just humor me and read the first line of your error
it even gives you a suggestion on how to fix it.
yeah but its literally the same thing, isnt it? i did a search and replace nothing changed
it's not
okay then im blind...
fritz_dect_210_1_total_kWh
fritz_dect_210_1_total_kwh
there's a difference.
go character by character if you have to
no way...
Yes way.
the fing w
always pays to read the errors!
yeah okay now i know why my vscode told me that they are the same...
FYI, capitals are not allowed in any field name for HA
nearly 1h? xD
btw is there a better way to realod the config? i allways read to restart the server
it seams like a inefficient way
for templates there's a template.reload service you can call from the service caller in dev tools
or a restart of the service vs the server
ah thanks
I want to make a copy of a fan, but with it speed in numbers instead of in words so google home/assistant can control it. This is what I have done so far:
fan:
- platform: template
fans:
fan_google:
friendly_name: "Livingroom Fan"
value_template: "{{ if_state('fan.livingroom', 'on') }}"
turn_on:
service: fan.turn_on
entity_id: fan.livingroom
turn_off:
service: fan.turn_off
entity_id: fan.livingroom
It isn't working like this, and I also don't know how to the speeds.
if the original fan is in the fan domain it should work in google on its own
if it doesn't, it might be better off opening an issue to get that sorted properly rather than trying to hack around it
What happens is that as I saw in this post, google home only supports fun with numbered sppeds https://community.home-assistant.io/t/template-fan-shows-always-shows-as-on-in-google-home-behaves-correctly-in-ha-what-am-i-missing/215489
It shows up, but you can only turn it on and off, and it's still a little buggy
And well, I don't mind opening an issue, but I would like to have a workaround until the bug is fixed
you can set the speeds via voice
πͺ
But speeds should show in the google home up right?
I mind, I don't mind, I'm using lovelace, but I want to know so I can submit an issue
i think its a google side thing. We use the trait correctly
the google things with screens show the speeds correctly but the phone apps don't for some reason
Okay, I only wanted voice control out of it anyway, so thank you for saving me the time of creating a workaround
can someone help me? I have a weather entity that has a state attributes that look like this
humidity: 78
forecast:
- datetime: '2021-02-25'
precipitation_probability: 61
- datetime: '2021-02-26'
precipitation_probability: 70```
How can i setup a template that always provides the ```precipitation_probability``` of the first entry (today)
i cant wrap my mind around how to select a particular attribute out of the forecast list...
You access list items by their index. The first list item under forecast would be forecast[0] (don't ask why computers always count from 0...).
From there, you'd access the keys of dictionaries by name: forecast[0].precipitation_probability
i gave you exampel in the morning
@ivory delta thanks, @glossy viper, yes you did but i didt not manage to get it working π₯
mono...if u put state of forecast[3].precipitation_probability it will be second datetime line ?
or the 3rd line that has precipitation_probability?
so {{states("dwd_weather_duesseldorf.attributes.forecast[0].precipitation_probability")}} ??
returns unknown
{{states.sensor.dwd_weather_duesseldorf.attributes.forecast[0].precipitation_probability}}
'None' has no attribute 'attributes'
somehow I'm too stupid for this syntax π«
GOT IT
its not sensor.XXXX but weather.XXXX
wrong domain!
oh...sorry...
π
sorry for not being profficient enough π
{{states.weather.dwd_weather_duesseldorf.attributes.forecast[0].precipitation_probability}}
this is it ?
this did the trick:
{{states.weather.dwd_weather_duesseldorf.attributes.forecast[0].precipitation_probability}}
if u put forecast2...what it returns?
the vlaue of precipitation_probability of the third entry in the forecast list
nice. ty
NP
hey guys looking for some help with this template. I want an icon to change colors from red to green is the script's state is = on or vice versa. I tested this in templates and got no errors but obviously it not doing what I want it to. {% if is_state('script.1577302825981', 'on') %} green {% else %} red {% endif %} }
can anyone help me sort this out
{{ 'green' if is_state('script.1577302825981', 'on') else 'red' }}
probably not liking the extra spaces
so I just tried it out in the new card-mod 3.0 style: | :host { --icon-color:{{ 'green' if is_state('script.1577302825981', 'on') else 'red' }}
but unfortunately it is still not changing the color of the icon.
You know you're setting weather twice, right?
could i be that some " are missing? message: The print is '{{states("sensor.octoprint_jobpercentage_round")}}' completed
this is a message with a template that works for me
message: 'the print is: {{states(''sensor.immax_temperature'')}} completed'
is there a device_class: magnet for magnets?
you have smart magnets?
i have bought one and glued it to the door, now im making a template for it since its a switch
then you use device class door or opening
does it have more than two states?
open and closed
sounds pretty binary to me
Is it possible to create and update an entity with numerous attributes based on different sensors?
Hello, i have a question, hope somebody can help me. I have a Shelly 3EM power monitor, which gives me three values for my three phases power line (so current consumption Phase 1-3). I want to have a power metering over all three phases. I tried the following as a sensor:
- platform: template
sensors:
haupthaus_kw:
friendly_name: "Haupthaus kWh"
unit_of_measurement: "W"
value_template: "{{ states('states.sensor.shelly_shem_3_84cca8ad55d3_1_current_consumption') + states('sensor.shelly_shem_3_84cca8ad55d3_2_current_consumption') + states('sensor.shelly_shem_3_84cca8ad55d3_3_current_consumption') }}"
this did not work.
soo, like
value_template: "{{ states('states.sensor.shelly_shem_3_84cca8ad55d3_1_current_consumption')| int + states('sensor.shelly_shem_3_84cca8ad55d3_2_current_consumption')|int + states('sensor.shelly_shem_3_84cca8ad55d3_3_current_consumption')|int }}"
?
that seems to work π
how do i insert a linebreak in this part of my automation? ex;
- service: input_text.set_value
data:
value: Basement Motion Sensor on {{ now().strftime("%a, %b %d at %I:%M %p")}}
entity_id: input_text.lastusedss
after "Basement Motion Sensor" i want a line break.
just a hunch, did you try \n ? like "Basement Motion Sensor\n on "? \n ist newline in most programming languages.
do i have to put it in apostrophe or quotes?
didn't work. π¦
also put in quotes and doesn't work.
I don't think an input text can have a multi-line value π€·ββοΈ
Test it in Dev Tools.
i've tried quote and apostrophe but it parses in the card view as Justin South Window'\n' on Fri, Feb 26 at 12:56 PM
- service: input_text.set_value
data:
value: "{{ 'Basement Motion Sensor on \n {}'.format(now().strftime('%a, %b %d at %I:%M %p')) }}"
entity_id: input_text.lastusedss
try that
looks good, thank you. @dreamy sinew
need to construct the full string in one go otherwise weirdness happens
Delete that and share it with a code sharing tool, please. The rules are no code walls over 15 lines (see #rules )
Iβm trying to reverse this automation with templates so that it triggers when a device comes back online, does anyone have any advice or should I look at a new automation? https://pastebin.com/Z7u1EjY1
Can anyone help sort this out. I am using this template to change the color of icon elements based on the state of of the entity. It appears that the first 2 conditions work , but for the idle state I want the icon to change to green and that is not working {% if is_state_attr('climate.ecobee_lite3', 'hvac_action', 'cooling') %} 'blue' {% elif is_state_attr('climate.ecobee_lite3','hvac_action', 'heating') %} 'orange' {% elif is_state_attr('climate.ecobee_lite3', 'hvac_action', 'idle') %} else 'green' {% endif %}
I am not getting any error messages when I check it in templates, is there any where else I can validate the the string is correct?