#templates-archived
1 messages ยท Page 28 of 1
but you still need to have properly formatted yaml
which your turn_off service has but your turn_on service does not have
ok
i got what you are saying now
turn_on: service: switch.toggle target: entity_id: switch.lg_tv
something like this?
yeah works
well, keep in mind if you call switch.turn_on again, it will turn off
so are you sure you want the switch.toggle service, or do you want the switch.turn_on service?
also I want to setup something where I give alexa a command and it answers from the ha scripts
well toggle works
yeah but if you turn it on twice, it will turn off the 2nd time instead of staying on
toggle is a toggle
it alternates
on -> off -> on -> off -> on -> off
it does not, there is some problem with that I guess
I can just use that switch to turn on devices
same goes to my pc
so I use hass to work with it on pc
and alexa media player on tv
If you could help me with this
You're going to need to start with a starting place
starting place?
i.e. that's a tall order and I don't have the time to walk you through the whole thing
especially if you don't have nabucasa and you're using the custom alexa media player integration
so, i suggest looking on the forums for posts or using the alexa media player integration documenation
yeah nabucasa make things easier
Sure
is there any way to write a template that would say for all devices (entity of type x) a new value would be created. So say for all lux values from each lux sensor, it would create a word description for each that says "direct sunlight" or "no sunlight" for that sensor, without having to create a yaml file entry for each sensor
Nope, you'd have to create a yaml entry for each one.
states('switch....') or states.switch.....state ?
Well, I solved the wake on lan issue with my LG C2. All I had to do was remove the broadcast IP, leave only the MAC. For some reason the C2 doesn't like it if you input both. Power on and off toggle working like a charm now.
states('...')
only use the other method when you want to get properties of the state object. And if you don't know what that means, don't worry about it ๐
Hass.Agent is awesome btw.
yah, it's super easy
okay, but to get last_changed/updated it's okay to use states.switch...last_changed
heh, last_changed is a property of the state object
so you have to use the other method
I was a little confused. it's a property - now it's clear - thx
yes
state objects are python objects that hold information about the state of an entity
it contains, the state and attributes, both which are properties of the state object
it just so happens that states() gets the state property and state_attr() gets the attribute property's attributes
if you want access to any other properties on the state object, you have to use the states.xxx.xxx. method
If you want to read up on it, I made a post a few years ago that covers it
many thx, now things are more clear ๐
it'll be good the docs/configuration/state_object/ will have your examples or a link to your post
I believe they are in the state object docs
nope, in templating https://www.home-assistant.io/docs/configuration/templating/#states
your post is the better one ๐
Thank you
Hm. This feels like it should be simple but Im struggling, I want to take a time value from a input_datetime, and work out how many seconds it will be from now, till that time
I... came up with this but I.. have no idea what the result means but its not right haha.. ```{{ now() + timedelta(seconds=state_attr('input_datetime.dishwasher_start_time', 'timestamp') |int) }}
(It gives me this in the template editor, I've no idea what Im doing 2023-02-09 15:32:00.146624+00:00
{{ (states('input_datetime.dishwasher_start_time') | as_datetime | as_local - now()).total_seconds() }}
okay, I was way off then..
you were trying to add the total time from 1970 to the current time
so you would have been roughly 50 years off
๐
hm, thats giving me a slightly odd error AttributeError: 'NoneType' object has no attribute 'tzinfo'
Hi, there, i have this message into a calendar entry
6 fรฉvrier 2023 - 8 fรฉvrier 2023
Reservation URL: https://www.airbnb.com/hosting/reservations/details/HMXXMQM449 Phone Number (Last 4 Digits): 7584
AirBnB
Il y a 1 heure
is there any way to grab et 4 digits and add them to a text field ?
does the state/input_datetime contain a date and time or just a time?
Just a time I think, thats what I created it with in the UI
yeah, its just time. has_date: false
Im assuming the problem is the as_datetime but honestly I cnat figure out what filter it hsould be ๐
Logically, at least to me you think as_time would work, but that's not a thing
Ok, then change it to (today_at(states('โฆ')) - now()).total_seconds()
On mobile
Hm, that renders correctly, but behaves oddly after midnight as it converts the 'seconds' into a negative number ๐
So 00:10 which is about 1 hour from now gives -82440
i mean I guess that makes sense as its about that many seconds from midnight this morning
Thatโs because you donโt have a date attached to your datetime
Hm, Is there a way to make it implicit that its 'past' that time to automatically make it the next day? this is going ot be part of an automation if I need to set the date/time manually each time it would rather defeat the point ๐
Is there such thing as a "friendly state"? Retrieving the state via a template for some entities gives a different result to what their entity card will show in a dashboard. Example: weather.home returns partlycloudy while the UI shows "Partly cloudy" and alarm.alarmo returns armed_away when the UI shows "Armed away".
That's a translation, and there's currently no way to get that from a template
creating a dict and indexing into it is a straightforward way to do it
Yeah, there's only a handful of states that need to be remapped though. If it were > 3, would definitely map it via a dict.
@inner mesa did your PR ever go through?
wow, those calendar triggers are limited
Is that a PR for translations?
Nope
Okay, otherwise it would be useful for Voice responses ๐
Is it for the expand thing?
How do you test against UndefinedError: list object has no element 3 I tried to put if not defined, if true, if length, it always explodes and never continues with the else but if I define it to element 2 it will complete fine and toss the if message and carry on.
{{ something[3] if something | count > 3 else 'whatever you want then' }}
Still fails
{% set img = state_attr('sensor.printer_3d_file_metadata','thumbnails')[3].relative_path %}
{{ img[3] if img | count > 3 else 'whatever you want then' }}
It fails in the first line
How do I fix that?
{% set thumb = state_attr('sensor.printer_3d_file_metadata','thumbnails') %}
{% set img = thumb[3].relative_path if thumb | count > 3 else 'whatever you want' %}
{{ img }}
Are there any good guides on Jinga? I'm struggling to make much sense if the official stuff
{% set thumb = state_attr('sensor.printer_3d_file_metadata','thumbnails') %}
{% set img = thumb[3].relative_path if thumb | count > 3 %}
{% else %}
{% set img = thumb[2].relative_path %}
{% endif %}
TemplateSyntaxError: Encountered unknown tag 'else'.
Brute force and perseverance? ๐ Are you using the Developer Tools -> Template in HA?
Easiest way to poke at making templates stuff without restarting HA
you didn't define the if anywhere
{% set thumb = state_attr('sensor.printer_3d_file_metadata','thumbnails') %}
{% set img = thumb[3].relative_path if thumb | count > 3 else thumb[2].relative_path %}
{{ img }}
but it didn't work when I added that thumb[2] there so I tried to expand it out
what does {{ state_attr('sensor.printer_3d_file_metadata','thumbnails') }} return in devtools > templates
Yeah but its like writing in French ๐
Your above worked
- name: 3d_printer_object_thumbnails
unique_id: "IP59b37837-b751-4d31-98c2-516a52edf833"
state: >
.thumbs/pumpkaboo_print-400x300.png
http://IP:7125/server/files/gcodes/some/directory1/directory2/.thumbs/pumpkaboo_print-400x300.png
availability: >
True
icon: mdi:image
attributes:
friendly_name: "Object Thumbnails"
if you wanted to expand that so if now 2 doesn't exist it selects 1 and if 1 doesn't exist it selects 0 and if it doesn't exist at all it doesn't explode how would you manage that?
"thumbnails": [{"width": 32, "height": 24, "size": 1647, "relative_path": ".thumbs/2_Skirt_Clip-32x32.png"}, {"width": 64, "height": 64, "size": 6338, "relative_path": ".thumbs/2_Skirt_Clip-64x64.png"}, {"width": 400, "height": 300, "size": 186843, "relative_path": ".thumbs/2_Skirt_Clip-400x300.png"}],
There is only 0 1 2 (basically different size of thumbnails)
People are having issues as apparently their slicers don't conform and spit out a different quantity of thumbnail sizes depending on what they set.
Hard to think about all the way users can break something.
do you always want the last one in the array?
then just use last
{% set thumb = state_attr('sensor.printer_3d_file_metadata','thumbnails') %}
{% set img = (thumb | last).relative_path if thumb else 'not available' %}
{{ img }}
Thank you that is perfect!
hi. Is there a way to manually trigger an update of a trigger-based template sensor?
scan_interval?
I mean I just literally need to do it now by hand, because it's unknown and it will not update itself for another hour.
scan_interval: 3600
I thnk I wasn't clear. I have a trigger-based sensor set up. It update once an hour. I am happy with this behaviour. But it got into a bad state, so I would like to evaluate itself now, once, outside it's automatic behaviour, like triggering an automation by hand. But I can't see how to do that.
add an event trigger and send out that particular event from devtools > events
Is there any way to create template update.some_entity or repair.some_entity so they would show up in the update and repair list of the HA settings? I would love to be able to have all the update and repair issues clustered in the settings.
not that I'm aware of
Pity... But thanks for your fast reply! I guess I have to file a feature request. ๐
Thanks, but this gives me: TypeError: unsupported type for timedelta hours component: str
Did you add | float?
oh wait, you'll have to move the last bracket
{{ now() + timedelta(hours=states('sensor.name')|float) }}
@thorny snow ^
Thanks, just struggling how to use strftime on this. I see in the docs that strptime uses strptime(string,format), but strftime doesn't seem to work that way, this gives me an error:
{{ strftime(a1,'%H') }}```
That strftime is undefined. How should I use this?
Got it!
{{ a1.strftime('%H:%M') }}
One last question. I'm now trying to convert the sensor itself to a nice format %H:%M. Which I supposed would be the easier part, I'd suppose just delete the now() part. However, this gives me an error:
timedelta(hours=states('sensor.tesla_time_to_full_charge')|float).strftime('%H:%M')
UndefinedError: 'datetime.timedelta object' has no attribute 'strftime'
Included in the {{ }} brackets ofcourse, forgot to paste those
you can't format a timedelta using strftime
you can do this
{{ (timedelta(hours=states('sensor.tesla_time_to_full_charge')|float)).total_seconds() | timestamp_custom('%H:%M', false) }}
Thanks, so it works when I add now() to it but not without?
Your script works, thanks! What does the false do?
if you add a timedelta to a datetime, you get a new datetime
the false makes sure UTC time is used, otherwise you will get an incorrect result based on your local timezone
basically you are asking for the HH:MM format of the number of seconds since 1st of January 1970, which will be converted to your local time if you don't add false
@sonic sand I converted your message into a file since it's above 15 lines :+1:
I don't see any template here ๐ But it might work if you put the entity_id under data
so should I remove the target?
You should follow what the documents say for custom:vacuum-card
we are guessing
that card is what determines the yaml format
Well I removed the target and added the same entity id under data and still the same error appears.
In the card documentation he used service to call his vacuum but I don't have that service
yes, so I just looked at the documents of that card, and it doesn't support data, it supports service_data
TLDR, you should use the documents for the custom card you're using, not make up yaml based on your previous experience
thanks man, so generally how do I know to which service_data I should call?
Not sure what you mean
start:
service: vacuum.start
service_data:
entity_id: vacuum.mijia_v2_202f_robot_cleaner
segments:
- 16
- 20
For instance, I used now this.
but getting error :
Failed to call service vacuum/start. extra keys not allowed @ data['segments']
does the vacuum.start service accept a segments key?
Where can I check that?
that'll be on the documentation for the vacuum service
you can also check that in developer tools -> services
well It worked just with the entity id there
yes, but the service itself will tell you all the available options that you can put in data
if it doesn't have a 'segments' field, that service does not accept segments
Okay, thanks!
Thanks for the explanation!
One more question if I may ask,
I have a smart aquarium tank which has attribute to the device when it last fed them.
How can I take out this attribute and make a notification when it fed them
I know that's kinda considered as automation and it's not the right place but how do I use the attribute to do it?
Thanks!
the fish tank entity is
switch.hfjh_v2_eadb_fish_tank_2
the attribute is
event.4.1: {"timestamp":1675792811,"value":[{"piid":16,"value":"2023,2,7,20,0,0,2"}]}
Well, you will actually need a template here
something like {{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1.').timestamp | timestamp_custom('%H:%M') }}
what a crappy attribute key btw
Thanks man should I put it in the configuration yaml or sensors yaml?
In the message you want to send probably
service: notify.mobile_app_your_phone
data:
message: Fish are fed at {{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1.').timestamp | timestamp_custom('%H:%M') }}
as an example
Thanks, I have contact you via DM regard what trigger do I use in this case.
and another template question - I got in my robot vacuum attribute this one
clean_record.clean_area: 2973
the numbers are squared meters but there should be a '.' between the first two numbers to the last numbers (29.73 squared meters in this case).
how can I add this dot to the attribute?
I've kindly ignored your DM request
Okay, thanks anyway for helping!
But for the trigger, that's up to you. When do you want it to trigger?
Whenever it changes (in my case whenever it fed them or failed to do it)
Then do a state trigger on that attribute
but that's something for #automations-archived
Thanks!
And about the dot in the clean_record I sent, is it for #frontend-archived or for #templates-archived ?
at the "finished" automation of my vacuum I want to add data of two attributes
clean_record.clean_time
Which shows how long did he worked
and
clean_record.clean_area
Which showing up how much area did he covered during his clean
How do I write it down in the data section in the automation I already created?
Thanks a lot!
See the examples here; https://www.home-assistant.io/docs/configuration/templating/#states
Thanks! Rob, and how do I add the dot between the two numbers? Is there any solution for that?
#templates-archived message
Divide by 100?
Yeah, how can I show that up in that attribute?
Hi. What's a good way to convert an otherwise increasing sensor which resets to zero every day at midnight into a cumulative one?
My plug reports energy use only as daily
Thereโs a helper for that
Which one?
I basically want anti-utility-meter
Riemann Sum
but I want to just remove the resets, not integrate the whole functions. I already have the energy as the source sensor
I sort of want what the total_increasing state class does
@analog mulch I converted your message into a file since it's above 15 lines :+1:
- platform: template
sensors:
vacuum_clean_area:
friendly_name: "Vacuum Clean Area"
value_template: '{{ (states.vacuum.mijia_v2_202f_robot_cleaner.attributes.clean_record.clean_area / 100) | round(2) }}'
unit_of_measurement: 'mยฒ'
I have created this template sensor but it showing me unavailable although the attribute getting updated by the meters it goes.
What did I do wrong here?
what does the template show in
-> Templates?
is this an actual attribute? clean_record.clean_area
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'clean_record'
if so, it's pretty weird
well, there ya go
figure out what you really want to manipulate
you'll need to handle that differently
Why and how?
Thanks for helping
state_attr('vacuum.mijia_v2_202f_robot_cleaner', 'clean_record.clean_area')
that's how you should access attributes anyway
"why" is that it has a dot in the attribute key
how can I divide by 100
It gives me TypeError: unsupported operand type(s) for /: 'str' and 'int'
then add |float(0)
instead of round(2)?
no
or in addition?
no need to, to be honest.
value_template: "{{ (state_attr('vacuum.mijia_v2_202f_robot_cleaner', 'clean_record.clean_area')|float(0) / 100) | round(2) }}"
it's up to you
trying wait
fixed the quotes
Thanks man works like a charm, now if I want to show up in data within an automation do I just put the sensor in it?
like to show "The vacuum went through (sensor.vacuum_clean_area)"
Is it possible to create sensors from this?
today:
- total: 0.2878
startsAt: '2023-02-09T00:00:00.000+01:00' - total: 0.2592
startsAt: '2023-02-09T01:00:00.000+01:00' - total: 0.226
startsAt: '2023-02-09T02:00:00.000+01:00' - total: 0.2213
startsAt: '2023-02-09T03:00:00.000+01:00' - total: 0.2853
startsAt: '2023-02-09T04:00:00.000+01:00' - total: 0.3511
startsAt: '2023-02-09T05:00:00.000+01:00' - total: 0.4079
startsAt: '2023-02-09T06:00:00.000+01:00' - total: 0.4728
Sure
@cloud flicker I converted your message into a file since it's above 15 lines :+1:
Is there a nicer way to handle duplication of everything in a yaml? If I have multiple 3D printers using this script https://github.com/NonaSuomy/Moonraker-Home-Assistant/blob/main/moonraker.yaml what way would you go about having a second moonraker2.yaml, moonraker3.yaml or in the yaml somehow be able to select multiple printers with one yaml file, then for the multiple file one having to rename all the template variables with a 2 on the end as well or something, seems a little heavy handed?
Check out something called yaml anchors. YMMV depending on how many small changes you have to make to the fields.
YAML anchors are of limited use here, as the IP or entity_id references are unique per printer
What would you suggest @marble jackal ?
I would probably use 3 seperate files and just replace the IP and sensor references
Ok
If you have a json list of plugin names and their versions what would be the best way to display them all at once?
https://codebeautify.org/online-json-editor/y23dafb8a
Something weird is happening. I've installed some new cards through HACS yesterday, restarted HA, emptied browser cache, but they are still not showing up. Anything else I can do?
ask for help in #frontend-archived?
display where? And what would your expected result look like
Basically just a list on one of the dashboard views
Something like this https://imgur.com/a/W701MRC
{% for i in value_json.result.version_info %}
{%- if value_json.result.version_info[i].version is defined %}
{{ i }}
{{ value_json.result.version_info[i].version }}
{%- endif %}
{% endfor %}
What kind of card would you display that on?
a markdown card accepts templates
BTW you need to define value_json and refer to wherever you have this data
Am I allowed to set a variable using the variables: key in the trigger in a trigged-based template sensor and then use it inside my templates for the state?
yes
Confused how to access this printername
{"result": {"namespace": "mainsail", "key": "general", "value": {"printername": "SomeName"}}}
{% set printername1 = state_attr('states.sensor.printer_3d_1_server','printername') %}
{{ printername1 }}
yo, I'm getting this error for some reason on Developer Tools -> UndefinedError: 'None' has no attribute 'timestamp'
the part outside your code tags is the result of that template?
Which part of that do you need
is the attribute currently available?
- platform: rest
name: 3d_printer_1_server
unique_id: "IP1cba6677-02bd-4273-9083-b8301bf6943d"
scan_interval: 1
resource_template: "http://IP:7125/server/database/item?namespace=mainsail&key=general"
json_attributes_path: "$.result"
json_attributes:
- key <= which value should I be putting here?
value_template: "OK"
When I hit this url
http://IP:7125/server/database/item?namespace=mainsail&key=general
it outputs:
{"result": {"namespace": "mainsail", "key": "general", "value": {"printername": "SomeName"}}}
and it worked before?
I forgot to check it on the developer tools after you sent it to me..
service: notify.mobile_app_your_phone
data:
message: >
{% set feed_time = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default({}, true)).get('timestamp') | timestamp_custom('%H:%M', default='unknown') %}
Fish are fed at {{ feed_time }}
there was a . after 4.1 which should not be there
the code above should also work in case the attriubte is not available
UndefinedError: 'str object' has no attribute 'get'
after many attempts i gave up on using attributes in a state template. I undressed my 255+ chars to this to get my head around it
- name: "Calculated Setpoint CS"
unit_of_measurement: "ยฐC"
state: >
{% set CS = ( 1 * 0.075 * (this.attributes.tbuiten - 10)**2 + 50 ) | float(default=55) | round(0) %}
{% if CS > 70 %}
{% set CS = 70 %}
{% endif %}
{{CS}}
attributes:
tbuiten: "{{ states('sensor.buienradar_temperature') | float | round(2) }}"```
this gives me errors
Try this then
service: notify.mobile_app_your_phone
data:
message: >
{% set feed_time = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('timestamp') | timestamp_custom('%H:%M', default='unknown') %}
Fish are fed at {{ feed_time }}
Now no error but it says Fish are fed at unknown even though there is a timestamp on the attribute (like in the picture I sent you)
also what was the problem with the get attribute so I will know for next time?
it only works on dictionaries, not on strings
the dot was back in my last template
I removed it now
Ah right yeah I see
define errors
you probably need to use a default. The state template is rendered first, so the attribute doesn't exist then
I usually use get() for that, but you dan also use the default filter
TemplateError('UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'tbuiten'') while processing template 'Template("{% set CS = ( 1 * 0.075 * (this.attributes.tbuiten - 10)**2 + 50 ) | float(default=55) | round(0) %} {% if CS > 70 %} {% set CS = 70 %} {% endif %} {{CS}}")' for attribute '_attr_native_value' in entity 'sensor.calculated_setpoint_cs'
yes, that confirms it
tbuiten doesnt exist yet?
you can also use an if statement if you don't want an incorrect calculation
shouldnt the default=55 catch the error?
state: >
{% if this.attributes.tbuiten is defined %}
{% set CS = ( 1 * 0.075 * (this.attributes.tbuiten - 10)**2 + 50 ) | float(default=55) | round(0) %}
{% if CS > 70 %}
{% set CS = 70 %}
{% endif %}
{{CS}}
{% else %}
unavailable
{% endif %}
nope, the error occurs before that
why limp version should start to work once buienradar_temp changes?
I have no clue what you are saying here
The error occurs when the template is rendered for the first time (after a reboot or template reload)
is defined:.... when is it defined?
I just want the printername
TheFes any idea why am I getting unknown even if in the state developer tools I can see the timestamp?
you need to change your attributes path to "$.result.value" and then use printername as the key
when does it start to exist, because its a long time after a reboot and still no value CS
I'm out for lunch now
Bon apetit!
Thank you will give that a go.
so i assume the tbuiten value starts to exist once the buienradar ticks to another temp?
Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer_server') for dictionary value @ data['sensor'][0]['state']. Got '{{ states.sensor.3d_printer_server.attributes["printername"]}}'. (See /config/packages/moonraker.yaml, line 113).
Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer_1_sensor') for dictionary value @ data['binary_sensor'][0]['state']. Got '{{ states.sensor.3d_printer_1_sensor.attributes["filament_motion_sensor btt_smart_filament_sensor"]["filament_detected"] }}'. (See /config/packages/moonraker1.yaml, line 101).
Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer_1_server') for dictionary value @ data['sensor'][0]['state']. Got '{{ states.sensor.3d_printer_1_server.attributes["printername"] }}'. (See /config/packages/moonraker1.yaml, line 113).
Can you not use a number at the start of your name seems to lop it off says d instead of 3d ?
you cannot use a number with the . notation.
you have to use the state_attr function for that.
only at the start? as that used to work when it was printer_3d_etc
at all times
if you mean "at the start" of your object_id, then yes
if you mean "at the start of HA", then no
I meant at the start of the object_id yes.
What does it confuse by using a number?
then no, it will never work
it's a rule in all coding languages
as .3 for example is a number.
so the parser doesn't know if you're trying to access a method or if you have invalid syntax and trying to use a number
no languages allow numbers at the start of any method/definition/property/attribute
did you change the state template already? the attribute will never exist if the state template can never be rendered without errors
you mean the template works in devtools, but not in the message?
in dev tools template showing unknown, but in dev tools states I can see the timestamp
what's the result of this {{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') }}
I changed this then tried {{ states.sensor.printer_3d_server.attributes["printername"] }} => UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'printername'
Result type: dict
{
"timestamp": 1676027698,
"value": [
{
"piid": 16,
"value": "2023,2,10,13,14,0,0"
}
]
}
This template listens for the following state changed events:
Entity: switch.hfjh_v2_eadb_fish_tank_2
- Why don't you just use
state_attr()instead ofstates.domain.object_id.attributes['some_attribute'] - what does that sensor show in devtools > states
okay. now {{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1').timestamp }}
by the way, you see the last two digits on the value line?
6th position corresponds to status (0 = OK; >0 = NOK);
7th position corresponds to number of portions feeded.
Is there a way to monitor only them to let me know if the fed was successful and how many portions did it fed them?
I'm trying hold on
UndefinedError: 'str object' has no attribute 'timestamp'
okay, so it's not a dict, it's a string. The template editor is lying here ๐
Should I technically use state_attr() for everything? This was someones older code.
dude, why didn't you just use state_attr?
yes
that's what I said ๐
I told him to use state_attr a half hour ago
next:
{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).timestamp }}
๐ so if it's a string what should I change to make it work?
that
Result type: number
1676027698
This template listens for the following state changed events:
Entity: switch.hfjh_v2_eadb_fish_tank_2
so, that works
i tried getting tbuiten to default to 10 but doesnt work:
tbuiten: "{{ states('sensor.buienradar_temperature') | float(default=10) | round(2) }}"```
Can anyone give me a pointer as to whether I can do this? json_attributes_path: "$.photos.photo[{{ range(1, 500) | random }}]"
yeah, so In the first template you've sent me
service: notify.mobile_app_your_phone
data:
message: >
{% set feed_time = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1.') | default("{}", true) | from_json).get('timestamp') | timestamp_custom('%H:%M', default='unknown') %}
Fish are fed at {{ feed_time }}
should I change only the first part after the set feed_time?
then (to avoid errors on when the entity is not working)
{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get(timestamp) }}
No, json_attributes_path doesn't accept templates
UndefinedError: 'timestamp' is undefined
hmmm that's scuppered that idea then ๐ฆ
sensor.3d_printer_server_2
printer_3d_server
OK printername: SomeName
friendly_name: printer_3d_server
@plain sedge what are you trying to do? You can put the randomness in the attribute
I guess it got polluted with an extra _2
this.attributes.tbuiten | default(10) this works @marble jackal , But now i dont know if its the default calculation or the real one yet lol
you are not getting my point.
If you use this.attributes.tbuiten in your state template, this will cuase an error when the state template is rendered the first time. The attribute will not exist. This will stop further processing of the template entity, so it will not get to the attribute
ah, you are getting my point
i thought default= will catch any error, but thats not so
no, it will catch an error on the part you apply the filter on, but not errors before that
( a lot of calculations and stuff) | default will still run in error if there is an error in the calculations and stuff
thanks for your time.
this does the same as this.attributes.get('tbuiten', 10)
ah the get(), i was looking into that for syntax :)))
i can finally build out this practice to the full version again ๐
all this because 255+ chars.... :/
and because state is rendered before attributes
the laziest way to deal w/ 255+ characters is to plop the data in an attribute and be done with it
that would be me
if you have multiple levels you can do this.get('attributes', {}).get('something, {}).get('something_else', 99)
sorry, needed quotes around timestamp
{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('timestamp') }}
but I'm overcomplicating it here
so what do you want as the message text
Something like the fishes have been fed 7 times? or do you also want the timestamp somewher
The fishes have been fed 7 times, last time was at 23:23
wait i'm checking
sweet now It shows the number.
I want like every feeding session it doing it will send me a message The fishes have been fed (number of portions) at (timestamp).
If the 6th position number is not equal to 0 which mean the feeding session has failed so it will send a different message to me
service: notify.mobile_app_your_phone
data:
message: >
{% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('timestamp') %}
{% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('value', []) %}
{% set t = timestamp | timestamp_custom('%H:%M', default='unknown') %}
{% set n = value[6] | default('unknown') %}
The fishes have been fed {{ n }} at {{ t }}.
Thank you man, so now whenever the event.4.1 changes it will send me notification based on the numbers within the output right?
@sonic sand I converted your message into a file since it's above 15 lines :+1:
if you remove the dot after event.4.1 it should (I would place quotes around it as well)
and the template should be indented two spaces compared to message
in the attribute line you mean?
alias: Fish Fed Telegram Notification
trigger:
- platform: state
entity_id: switch.hfjh_v2_eadb_fish_tank_2
attribute: "event.4.1"
action:
- service: notify.home_assistant_group
data:
message: >
{% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('timestamp') %}
{% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('value', {}).get('value', '').split(',') %}
{% set t = timestamp | timestamp_custom('%H:%M', default='unknown') %}
{% set n = value[6] | default('unknown') %}
๐ The fishes have been fed {{ n }} at {{ t }}.
mode: single
Thank you man!!
When I paste it to the devtools I get
UndefinedError: 'list object' has no attribute 'split'
trying
I feel like that can be simplified w/ a simple condition
you're probably right
๐ The fishes have been fed unknown at 13:14.
Why is it showing unknown
{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).value[6] }} what does this show in devtools?
alias: Fish Fed Telegram Notification
trigger:
- platform: state
entity_id: switch.hfjh_v2_eadb_fish_tank_2
attribute: "event.4.1"
condition:
condition: template
value_template: "{{ trigger.to_state.attributes['event.4.1'] is defined and trigger.to_state.attributes['event.4.1'] is mapping }}"
action:
...
it's actually not a mapping, it's a string
UndefinedError: list object has no element 6
that doesn't make sense
that's why the from_json is required
why would it be a string?
dunno
How do you remove states from developer tools ( I removed the entities that dealt with them ) is there another place as well?
that means it's invalid json
this is the line from states
event.4.1: {"timestamp":1676027698,"value":[{"piid":16,"value":"2023,2,10,13,14,0,0"}]}
if it doesn't come through as valid json
last two digits are 0,0
which mean feeding was successful but fed them 0 portions (?)
refresh your page if you deleted the entity
{{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is string }}
{{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is mapping }}
{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).value is string }}
can you try that
sorry, adjusted
I don't see how that wouldn't be json... really odd
Result type: string
True
False
False
sensor.3d_printer_server
3d_printer_server
unavailable restored: true
friendly_name: 3d_printer_server
supported_features: 0
sensor.3d_printer_server_2
printer_3d_server
OK printername: VoronV0_001
friendly_name: printer_3d_server
This second one has the right name but the first one doesn't I don't know where it is coming from...
purged all the other values
that was just for confirmation.
{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).value[0] }}
{{ (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).value | count }}
``` what does that give?
if this is a yaml configuration, then it's coming from yaml and it won't be removable until you restart. If it's UI and you're reloading the integration, it should be a similar situation, again, you'll have to restart.
{'piid': 16, 'value': '2023,2,10,13,14,0,0'}
1
wait, I totally missed there is a value in the value
{% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('timestamp') %}
{% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | default("{}", true) | from_json).get('value', {}).get('value', '').split(',') %}
{% set t = timestamp | timestamp_custom('%H:%M', default='unknown') %}
{% set n = value[6] | default('unknown') %}
๐ The fishes have been fed {{ n }} at {{ t }}.
Uh, that value is a time tuple and it's almost identical to 1676027698
@sonic sand is your timezone + 2?
if yes, no reason to dig deep into that object
just use the timestamp and convert it to your local time
| as_datetime | as_local
yeah i'm +2
wait, I think I'm trying to get the wrong value hjere
if you're +2, that timetuple is 58 seconds off from the timetamp
No I have the correct one, I'm just using this information
so then that last value is not milliseconds
apparantly
that's so weird
templates don't handle time tuples
so you have to use the timestamp or manually create the datetime by replacing values in now w/ the time tuple values
I was using that for the number of feed moments, but I agree it does look a lot like a time tuple
this event.4.1 came from this thing basically
https://github.com/al-one/hass-xiaomi-miot/issues/326
It's mentioned here https://github.com/al-one/hass-xiaomi-miot/issues/326#issuecomment-1004044819
so weird
Does the latest template work @sonic sand
trying now
UndefinedError: 'list object' has no attribute 'get'
sorry
should have read that json properly
{% if state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is not none %}
{% set timestamp = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).timestamp %}
{% set value = (state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json).value[0].value.split(',') %}
{% endif %}
{% set t = timestamp | default() | timestamp_custom('%H:%M', default='unknown') %}
{% set n = (value | default())[6] | default('unknown') %}
{% if (value | default())[5] | default() == 0 %}
๐ The fishes have not been fed
{% else %}
๐ The fishes have been fed {{ n }} at {{ t }}.
{% endif %}
Works like a charm, thank you!
is it possible to make a different message to user whenever the fish feeding device has failed == 6th position corresponds is not equal to 0 (feeding has failed)
Hullo. {{ states('zone.home') }} says Result type: number in developer tools. Does that mean the states function automatically casts the string to a number?
The documentation suggests that it should still be a string
States are always strings, but IIRC templates were changed a while ago to output data in the appropriate data type instead of always being a string
Is there some canonical way of initialising a trigged-based template sensor -- it's initial state is unknown and I want it to add to it. Do I just set it to some intial value through the developer tools?
states are always strings, the result of states() will always be a string
however, devtools>templates does conversion to native types (which can be confusing)
You can also take the unknown state into account in your template, eg
this.state | float(0) should do the trick
I've adjusted the template
Just saw it, thanks dude!
Do i need 'this.attributes.get()' inbetween attributes?
like one attribute needs the value of another for its calculation? Or is it only the state
got it
You have to have a failsafe for when the attribute isn't rendered yet
yup especially when dealing with a boiler ๐
been toying with the setpoint of it. works, but now i want it depended on outside temp
I've tried removing all the yaml files and deleting all the entities and restarting yet this
sensor.3d_printer_server_2
printer_3d_server
unavailable restored: true
friendly_name: printer_3d_server
supported_features: 0
still shows up under developer tools -> states
Yes, that's expected. The other one no longer exists, so you can safely change the entity_id of that one
the system naturally increments entity_id's if the entity_id already exists
I can't find that one under entities
if it doesn't , it keeps it un touched
how can you not? You just posted that you see it in dev tools -> states
that's the entity list
click the info icon and change the entity_id
I mean if I go to settings -> devices -> entities it's not there
This entity is no longer being provided by the rest integration. If the entity is no longer in use, delete it in settings.
Oh the settings tab there is a delete
if the entity comes from yaml, it will not show up in any devices
nothing in yaml shows in the integrations area or devices area
the developer tools -> states page shows you everything and you can access everything from that menu
you literally don't need to use any other entity list
That page is all I use
so, just click the info button then delete from there
I wish I knew this before I had so many entities from esphome testing devices under entities that I couldn't remove but they remove fine from the states page!
omg, you've just made my day. I've been deleting from the entities list all this time
I thought that was common knowledge, I guess not
I made a forum post about it, maybe that will reach more people.
Url?
I've asked how to get rid of that stuff multiple times and nobody could answer it just kept telling me to restart was driving me batty.
Now all we need is a checkbox beside them so we can delete hundreds of entries faster ๐
I mean if you know where the info button is, then there's no reason to llok at the post
You need to understand when to delete something and when to disable something
if the entity comes from the UI
you want to disable it
otherwise it will continually come back
if it comes from yaml, you want to remove it from yaml and delete it from dev tools -> states
if you know your entity is no longer getting created from a UI integration, you can safely delete it without it coming back
I was developing a garage device and I added hundreds of analog/digital port devices while I was testing something from esphome yaml I then remove those modules and use that esp32 device for other module tests (I2C devices) every time I removed the modules they would just pend more entities and would never go away after removing them.
right, that's because you kept changing the name of your esphome device
if you kept the name the same, it would just create new entities. Unless you renamed those as well
the name derives the device when coming from esphome
The esphome device never changed it's name just the build up of sensors I was testing with it.
you change the name, you change everything else
so you were adding/removing entities?
then the device shouldn't have changed, just the entities
and in that case, those entities could still be found in the integration -> entities list
because they were in the entity registry
So I was using I2C expanders that had 16+ digital ports on them, I removed them from the esphome yaml then tried another analog 16 pin I2C device on the same esp32, I then removed the i2c analog expander, then tested a PWM module with 16+ ports on it, then tested multple other I2C devices on that esp32. It never removed the entities from HA even though those sensor no longer existed in the ESPHome yaml.
right and it won't because it thinks those are unique and they just haven't been loaded
so you would have just had to delete them, which they would still exist in the entity list
however you most likely would have had to restart for HA to allow you to delete them
Yes that was where I was having the issue as I assumed HA would poll the ESPHome device and say "I don't have these" and HA would purge them automagically. That is where I went wrong so they have been stuck there for a year now. As I didn't know about this state delete. As it would just say I couldn't delete them from the entities page.
If you remove the ESP device from the ESP Integration and add it again (or wait until it's discovered again), the entities will also be cleaned up
HA doesn't know you deleted them if they are push devices
it assumes you they just haven't talked to HA in a while
that's the downside of reloading via the UI
restarting fixes that problem, but people don't like restarting
I'll try that. As with this test ESP32 I just leave it running all the time with it's default settings and attach I2C junk to it to figure out the sensors then add those to other devices afterwards.
sensor.3d_printer_printername
3d_printer_printername
Voron_V0_001 icon: mdi:printer-3d
friendly_name: 3d_printer_printername
Yay it's working now
That was rough. Changed the template code like 50 times until finding out that glitched entry.
if you use a unique_id with your template entity, that won't happen.
just make sure you never change the unique_id after you create it
if you change the unique_id, you'll end up with an _2 entity
- platform: rest
name: printer_3d_updates
unique_id: "IP1cba6677-02bd-4273-9083-b8301bf6844"
scan_interval: 1
resource_template: "http://IP:7125/machine/update/status"
json_attributes_path: "$.result"
json_attributes:
- version_info
value_template: "OK"
{% for i in printer_3d_updates.result.version_info %}
{%- if printer_3d_updates.version_info[i].version is defined %}
{{ i }}
{{ printer_3d_updates.result.version_info[i].version }}
{%- endif %}
{% endfor %}
Tried this in the dev tools template UndefinedError: 'printer_3d_updates' is undefined
what have we told you multiple times to use now?
rhymes with schmate_schmattr
I was just using the code provided...
what code provided?
that code he posted uses value_json
you're trying to get the state's attribute version_info
.
right
so you set your json path to json_attributes_path: "$.result"
then you're extracting - version_info as an attribute
and now you have an entity, sensor.printer_3d_updates with an attribute version_info
value_json no longer exists
what does state_attr mean?
That and much more template magic in the links in the topic
Is this something local to jinja or to ha or other?
it's specific to HA
it's covered in the templating documents
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
it's the extensions link
I really have no idea what to do with these lines...
{% for i in state_attr('sensor.printer_3d_updates','version_info') %}
{%- if state_attr('sensor.printer_3d_updates','version_info[i]).version is defined %}
{{ i }}
{{ state_attr('printer_3d_updates','version_info').version }}
{%- endif %}
{% endfor %}
{% for i in state_attr('sensor.printer_3d_updates','version_info') %}
{%- if i.version is defined %}
{{ i }}
{{ i.version }}
{%- endif %}
{% endfor %}
Result type: string
This template listens for the following state changed events:
Entity: sensor.printer_3d_updates
There's a grey box between the last two lines I assume a list should have been printed there?
yep, but it seems version is not defined
what does
{{ state_attr('sensor.printer_3d_updates','version_info') }}
return?
The full json
going for something like this https://imgur.com/a/W701MRC
Says Result type: dict
starts at
{
"system": {
"package_count": 0,
"package_list": []
},
"moonraker": {
"channel": "dev",
etc...
Dumps the moonraker version
i suggest you look at https://community.home-assistant.io/t/question-about-template-states/214733/2
you basically need to learn how to access your information by knowing what the current object is
that post covers all the object types and how to get info out of them
So why is your for loop not outputting the multiple software names and versions under version_info?
because I was basing it off what you said from what thefes posted
I didn't know what the object shape was, now I do, that loop won't work at all
You just want that information on your dashboard?
yes
if yes, you'll have to use a markdown card. Otherwise you'll have issues trying to make these template sensors if the list is a variable length
Yes that is fine
I have the markdown card there just don't know how to get the data there.
package | version
:-:|:-:
{% for name, value in state_attr('sensor.printer_3d_updates','version_info').items() %}
{% if value.version is defined %}
{{ name }} | {{ value.version }}
{% endif %}
{% endfor %}
if you want it as a table in the markdown card
hello clever ppl, is this doing it right? http://paste.debian.net/hidden/ce06f594/
Do you just paste that into the markdown card?
type: markdown
content: >-
package | version
:-:|:-:
{% for name, value in state_attr('sensor.printer_3d_updates','version_info').items() %}
{% if value.version is defined %}
{{ name }} | {{ value.version }}
{% endif %}
{% endfor %}
title: Update Manager
(worked fine in the template tester)
if you want a table in markdown, use this
<table>
<tr><th>Package</th>th>Version</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_updates','version_info').items() %}
{%- if value.version is defined %}
<tr><td>{{ name }}</td><td>{{ value.version }}</td></tr>
{%- endif %}
{%- endfor %}
</table>
type: markdown
content: >-
<table>
<tr><th>Package</th><th>Version</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_updates','version_info').items() %}
{%- if value.version is defined %}
<tr><td>{{ name }}</td><td>{{ value.version }}</td></tr>
{%- endif %}
{%- endfor %}
</table>
no, your spacing is wrong. Also that's an integration question. This channel is for jinja templates.
it passed a yaml linter, ill figure it out
your spacing is correct for turn_off, but not for turn_on
thanks!
you're also missing spaces for siren
well, everything under siren
I recommend comparing your yaml to yaml in the documentation. Ensure the spacing matches
Just fixed the < on the th> and it's working great thank you
goal is to turn the siren on an off with a toogle in the ui
i need to involve a boolean?
yes
why do you want a toggle if the the services are the same?
just make it a button
how would you do it?
I'd make 2 buttons, one to turn it on, one to turn it off
i have 4 of these zwave smoke alarms, 3 of then have a binary switch exposed but after a FW update which the last one shipped with, it's now in the command class
if there's nothing to grab the state from, then i'd just deal with it as 2 separate services
you can grab the state by checking the value
command class 32 is a switch
are you sure you don't already have the switch somewhere?
yes
are you sure it's not disabled?
zwave devs had to patch the device config file just to be able to see the command class
before that i couldnt even see command class 32
brilliant aye
ah 37 is aswitch, my memory is off
the best you can do is poll the state of the siren
ok, so why don't you update the old one?
if anything id want to downgrade the new one
the old firmware has a binary switch
the new one changed to basic cc
and the new one is using 32?
there isn't an option to change the reporting type?
that's above my paygrade
check the configuration of it
usually devices have the ability to switch how they report
do you use zwave js ui?
yes
ok, take a screenshot of the expanded configuration
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
of zwavejsui?
of that firmware
SDK: v6.81.6```
FW 4.1 - https://quad.pe/e/znNn69nlCy.png
those are shit docs
any idea why they would do such a thing?'
too bad, the switch was very easy to work with
notifications are too
i cant even manage to get an on/off toggle in the HA ui for it
ill be the first to admit my knowledge is poor
well you shouldn't be turning on/off the alarm
i use the sirens for the alarm system
ok, then just make it a switch like you have
you don't need the state being on/off
if you're calling a switch.turn_on service, you don't need to know the state
of the siren
ok cool, thank you very much for helping out!
Hi,
I'm trying to substract timestamps to get remaining time of a washing machine.
However because I suspected DST, the calculation is 1h off...
Any idea what would be a correct template?
{% set remaining = states('sensor.washing_machine_washer_completion_time') | as_timestamp(default) - now() | as_timestamp(default) %}
{% set remaining = (states('sensor.washing_machine_washer_completion_time') | as_datetime - now()).total_seconds() %}
Thanks, however the calculation still has 1 hour offset...
Washing machine will end in {% if (remaining | timestamp_custom("%H") | int) > 0 -%}{{ remaining | timestamp_custom("%-H") }} hours,{{ " " }}{% endif -%}{{ remaining | timestamp_custom("%-M") }} minutes
what's the state of states('sensor.washing_machine_washer_completion_time')?
@lean yacht ^
Do I have to rename every entity in an entities list or is there a there a way for a long list like so http://pastie.org/p/0DnxtnEMpGZ8hoOpUOf7WW, to automatically remove a string and uppercase all the names?
I dont want applehealth listed in each one
though i guess all the default icons suck too. maybe i do need to micro manage them. =/
Is there a way to take an existing time entity and subtract a period of time? i.e. I have a helper "input_datetime.alarm" and if its set for 5:30am i want to start a task at 4:30am without having two separate helpers to manage. I have tried a few things to try and "math that time" but nothing I am doing is working
thanks, time to do some more reading and futzing around ๐ - EDIT: got it. thanks man!
@woeful socket I converted your message into a file since it's above 15 lines :+1:
Hi guys, is it possible to do a simple math of 2 values inside a message without setting up a variable first? I have 2 strings with the year inside of it that have to be converted to an integer and then substracted from each other to get an age of person on its birthday.
The substraction isn't working because they are not integers right now
service: notify.mobile_app_phone
data:
message: >-
Birthday: {{state_attr('sensor.geburtstage', 'data')[0].summary}} Age:
{{now().strftime('%Y')-state_attr('sensor.geburtstage',
'data')[0].originalStartDate[:4]}}
title: Test
{{ "1983"|int - 10 }}
This works for me, it outputs 1973, so you'd have to get your sensor.geburtstage and add a |int after to convert it to a number
I guess I'm doing something wrong with the syntax (my usual problem)
perfect!
Birthday: {{state_attr('sensor.geburtstage', 'data')[0].summary}} Age:
{{now().strftime('%Y') | int - state_attr('sensor.geburtstage',
'data')[0].originalStartDate[:4] | int}}
that is working now!
I'm still stuck on this:
- condition: template
value_template: >
{{ (states(lux_sensor)|int) > (states(light_threshold)|int) }}
Gives error: "error": "In 'template' condition: AttributeError: 'dict' object has no attribute 'lower'"
lux_sensor is an entity with domain.binary_sensor and _device_class.illuminance. The light_threshold is an input_number
In my template editor, I tried this: it's {{ ("ON" if ((states('sensor.hue_motion_sensor_2_illuminance')|int) > (states('input_number.terskel_lys_kjokken_vest')|int)) else "OFF")|lower }} and it worked as expected
Guessing here but do you need to not reference the illuminance sensor?
- condition: template
value_template: >
{{ (states(sensor.hue_motion_sensor_2_illuminance)|int) > (states(light_threshold)|int) }}
@woeful socket you're omitting a ton of information. It appears as if you're doing a blueprint? It also appears as if you're using a selector for said blueprint? And you're assigning those to variables? If yes, then you need to show what selectors you're using, what variables you assigned them to.
based on what I can see in all your templates, most of them are not correct. But that's making the assumption that the 2 bottom ones are correct. Your template condition is also using the translated state when it should be using the under the hood state.
How does a under the hood state look?
The error was found. I was referencing the light directly and not via its entityId
I am shopping now but will share the entire thing when I get home
all entities have untranslated states. What you see in the frontend on a dashboard is the translated state. Developer tools -> states page will show you untranslated states that you use in templates.
Open your Home Assistant instance and show your state developer tools
Is there an easy way to compare 2 dates with each other if one of them looks like
"11.2.2023" and the other one like "11.02.2023"?
the leading 0 for the month on the timestampe of "now()" drives me crazy
You can create a custom date: https://www.home-assistant.io/docs/configuration/templating/#time
Use strptime on both of them to convert them into datetimes
I was able to get rid of the leading 0 by using %-m instead of %m but now I have 2 exactly same strings, but my condition is still "false" ๐ฆ
is the syntax wrong for the comparison?
condition: template value_template: >- {% set heute = now().strftime('%-d.%-m.') ~ 1985 %} {% set kalender = (state_attr('sensor.geburtstage','data')[0].startDate) %} {{ ('heute') == ('kalender') }}
ok fixed it.... just writing the variables straight without quotes etc. fixed it => {{ heute == kalender }}
@mighty ledge and @glacial swan , I'm back from shopping and as promised, here is my now working Blueprint template. Would love comments and areas of improvement. I'm new to this HA templating language
https://gist.github.com/digitaldias/9cb752c2fbd344515a2cdb362739eb87
Making the code cleaner is also something I'd love input on, i.e. if I can write
{{ target_light.entity_id }} instead of ``{{ target_light['entity_id'] }} then that is a win for me, unless it has an expense that I don't need ๐
no way that's working 100%
you're still using the incorrect state on your template condition when checking the target light
It is working 100%, I tested all conditions
and yes, you can change to target_light.entity_id
I'm sorry, it's not
it's literally impossible for the state to be 'On' for a light.
no it's not, you can check if it is on or off
my man, I've been doing this for 7 years
your light will have a state of 'on' or 'off'
not 'On'
{{ is_state('light.hue_ambiance_spot_1', 'On' ) }} works perfectly here
I'm looking at it working ๐
light domains only have 4 possible states
on, off, unavailable, unknown
notice the lack of capital letters
Oo, casing!?
go to developer tools -> states and you'll see the state of your light is 'on'
yupyup, already fixing ๐
so that condition is not working.
Fixed!
Gist updated too
can I always replace object['attribute'] with object.attribute or do some triggers/conditions/actions require one style over the other?
you can always access key's in dictionaries with dict['key'] or dict.key unless the key starts with a number. In that case, it needs to be dict['key']
ok, so updated (revision 3), anything else that I could/should improve in your view?
Can I remove empty statements, i.e. empty data and empty conditions that define empty arrays, or do they need to be there?
after 24 hours with this template there is one problem that constantly happens - I keep getting spammed by unknown notification like this
๐ The fishes have been fed unknown portions at unknown.
It mostly happens when my aquarium losing connection to the internet, but is there a way to ignore those notification somehow or prevent unknown unknown atleast?
It'd help if you shared your automation, but you'll likely either need to add not_from and not_to trigger conditions for unavailable/unknown or put those in the condition to prevent it from firing in those instances
http://pastie.org/p/4V7jMxcapzP1YWDhKNTO5z
Forgot to add it, sorry!
Making sure a template sensor is the way to go here and I can't do this with a helper - I want to create a battery sensor that is based off the value or two attributes of another sensor -- template is the way to go, right?
I need to set some last-minute variables on a trigger temperature change.
Is it allowed to use templates under action: ?
i have multiple sensors like 'sensor.tag_0', 'sensor.tag_1' and so on. the amount is dynamic. every entity has an attribute 'Date'. I want to check in a template if one entity has today as a 'Date' in his attribute. How can I do that?
in pseudo code i am looking for sth like: {{ '11.02.2023' in (give_me_all_entities_which_startswith('sensor.tag_') | give_me_the_attributes_of_all_entities('Date')) }}
@woeful socket I converted your message into a file since it's above 15 lines :+1:
(I fixed the targetTemp quotation mark) - still wrong, it complains about
template value should be a string for dictionary value @ data['action'][0]['data']
2023-02-10T20:57:06+00:00
Hello, Looking to take my thermostat valvues and put the attribute into an entity to then use the history stats sensor to show how long each thermostat has been in heating mode, trying to do the first bit to take the attribute of the sensors, but nothing is showing up, putting the below into my sensors.yaml sensors: hvac_action_sensor: friendly_name: "test Heat" value_template: "{{ state_attr('climate.wiser_test', 'hvac_action') }}"
What does 'nothing is showing up' mean? The sensor doesn't exist? It is undefined? Blank?
yeah can't find anything in HA search with that nam
What key is that under in your configuration? Is sensors: at the top level?
yes
You're missing platform: template, but if you're creating new sensors, you really should look at using the new method under template:, like https://www.home-assistant.io/integrations/template/#state-based-sensor-exposing-sun-angle
Actually for the old style what you have needs to be in
sensor:
- platform: template
Also confirm if you have the correct include statement in configuration.yaml.
Your nested if has a missing bracket.
Here is the latest non-functional blueprint:
http://pastie.org/p/4igkNqLjwQzuZY3emqPew7
The offending bits are at teh bottom
Anyway, you don't need the brackets in the if statements.
Line 78 typo false. And it's elif not elseif.
ooh!
That solved the string error, @rose scroll , it only complains about a bad entity_id now
Pretty sure your entity_id is climate.xxx. Check your entities list.
Oh wait...panel_oven is a variable name not a domain. Hmm...
yeah, it's defined as an input up top as an entity.domain.climate
What exactly is the error?
If thatโs the case, then your timezone is set incorrectly in your system
Message malformed: Entity entity_id is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
Should just be able to use target: !input panel_oven
Trying that
well, it updated the error message:
Message malformed: not a valid value for dictionary value @ data['action'][0]['target']['entity_id']
when I changed to target: !input panel_oven
I couldn't see any device classes on the developer page
Should I define the input as a device instead?
Still confused what to change, I have set in configuration to use sensors.yaml so not sure if there is something I need to remove ```# test
- platform: template
sensors:
climate_wiser_test_hvac_action:
friendly_name: "Wiser test HVAC Action"
value_template: "{{ state_attr('climate.wiser_test', 'hvac_action') }}"
entity_id: climate.wiser_test
climate_wiser_test_hvac_action needs to be indented
Check your home-assistant.log
It'll say what it's failing to parse
selector:
target:
entity:
domain: climate
This DOES report with an entity_id right?
so NSX what condition should I add to prevent those messages from appearing? I can't figure it out
yes, if multiple is on, it will be a list of entity_ids, otherwise it's an entity_id
If thatโs the case, then your timezone is set incorrectly in your system
ah, that could be it, so I just take the first element.
are you searching for it in developer tools -> states page?
Also, do you have multiple template sensors? If yes, do you only have a SINGLE sensor: section?
I suspect that by NOT having set multiple: false that I am being tricked in my selectors? If I add it at the same inset as the domain: climate , the template does not even load. Also, the other two inputs I have do not have multiple: false set, and yet I can pick as many as I want from them?
I am on Home Assistant 2023.1.6 btw, if anything related to this has been fixed lately?
You can probably add this to your trigger
not_from: none
not_to: none
Otherwise this condition
- condition: template
value_template: "{{ not 'unavailable' in [trigger.from_state.state, trigger.to_state.state] }}"
Still no joy, I get the same error over and over. I'm stumped!
http://pastie.org/p/1IngUVr0gogW0OqbNtu13r
Message malformed: Entity entity_id is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
@swift agate I converted your message into a file since it's above 15 lines :+1:
If you donโt specify multiple it will just be the entity_if
Thatโs not an entity selector, thatโs a target selector
That means you have to use xxx.entity_id
If you chose a single entity
ok, in both triggers and actions?
Is it possible to use a template to output a list of dictionaries in such a way that it can be used in a Repeat for each action? No matter what I try, I get "Error: Repeat 'for_each' must be a list of items". The following is an example of one attempt.
sequence:
- repeat:
for_each: >
{{ states.sensor | selectattr('attributes.trash_holiday', 'defined')
| selectattr('attributes.trash_holiday', 'eq', 'on') | list }}
sequence:
- service: persistent_notification.create
data:
message: "{{repeat.item}}"
So itโs possible, but youโre actually making a list of state objects.
And you can only pass โsimpleโ objects. List, dict, int, float, str, bool.
When Iโm home later I can help you make that work
The actual idea is to populate a calendar: https://gist.github.com/Didgeridrew/491fa955ef2fe7c4f16bc503ac121db8
Ok, yeah I can help out. Wonโt be home til 6 or 7 est
But what you can do is use namespace to make a list of dicts using the info from the state objects
If you wanna try without my help
everywhere you want to use the data from the selector. Keep in mind that if you choose area or devices for the target selector, the code changes to get to your entity. And itโs not simple code.
Thanks, that's the piece I was missing... I needed to convert the datetime objects to strings.
Yep, that too
Is there a way to debug this so that I can see where the values are wrong? I replaced the inputs with straight entity names and it worked at once, but that error message tells me too little
I commented out the actions, so the trace is empty
Probably a simple question, but I can't seem to find it in the docs... How do I test for multiple conditions in an if statement? All I could find was a nested if and that seems messy
In templates you simply use and or or with ()
the best I get now is
Message malformed: Entity {'entity_id': 'sensor.soverom_elinor_temperature'} is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
when I use
trigger:
- platform: state
entity_id:
- !input temp_sensor
for:
minutes: 1
I've isolated the problem to triggers I think
You can only use inputs with specific triggers
It has to return an wntity_id for it to work. I..e. You canโt use a target selector for triggers
Howcome this one works then?
trigger:
- platform: state
id: motion_triggered
alias: 'Motion is detected'
entity_id: !input motion_sensor
from a different blueprint I made
They both are, or am I not understanding this correctly?
and( both conditions) or condition and() condition?
I donno because you didnโt post the selector youโre using for motion_sensor. Itโs not in your paste above
The difference is that one is a binary sensor (the motion sensor) and the temperature sensor is a sensor with device class temperature
It follows normal parenthesis order of operation
Post them both please
@woeful socket I converted your message into a file since it's above 15 lines :+1:
ooh, I see one has a target, the other doesen't!
Ok, one is a target selector the other is entity
So you have to use an entity selector, not target
did not saw your tag,
so like that?
http://pastie.org/p/3ala8ZH76OY3IPPFxTRR8S
will it work fine?
Sorry it's not computing in my head (or the editor)... I'm ok if you can point me to the docs page where I can look it up myself too, just haven't been able to find it
{% if states('schedule.home') == 'off' and states('device_tracker.reinhardt_mobile' == 'not_home') %}
You put the test in the function call?
It's a service call action in an automation. Here's the full one:
service: climate.set_temperature
data:
temperature: >
{% if states('schedule.home') == 'off' %} {{
states('input_number.living_room_low_temperature') | float }} {% else %} {{
states('input_number.living_room_home_temperature') | float }} {% endif %}
target:
entity_id: climate.livingroom_thermostat
I'm talking about this:
states('device_tracker.reinhardt_mobile' == 'not_home')
Yeah I'm trying to add that test into the if statement. THe code I shared was by accident the one with only one test
That will not work. Move the parenthesis
You're putting the test in the function call
is states() the function call? Guess I'm missing some terminology here
Yes
Look at what you did here: #templates-archived message
The first is correct, the second is wrong
What would be the best approach to see how long would a phone/tablet take to charge(100%), in %h:%m? I noticed that the data from the companion app updates in a somewhat erratic way: from 50%-52%-55%
You can change the update interval in the app settings
Oh, true. Will have to check it.
Right now I'm having a timer start when the state of battery_state changes to charging; and stop when the battery_level goes beyond 99.
Will have to work from there.
Hi all, i am pulling my hair out now. I really need help with this templating.
I tried to use an event trigger of the overwolf_game_event (need to fetch data for counter strike stats)
when doing so i get this data:
INFO: {"game_info":{"scoreboard_0":{"nickname":"TRoager","steamid":76561198085455790,"team":"T","money":1000,"kills":0,"assists":0,"deaths":0,"mvps":0,"score":0,"adr":0,"ud":0,"ef":0,"ping":4,"local_player":1}}}
now how do i extract, "kills" and "mvps" into an automation ?
my problem is that "scoreboard_0" key is not always 0 it can also be 3, 4, 5 etc so i need to get around that this variable is unknown.
Anyone have a clue ?
i did try this and this works but then i need to know the scoreboard_0
json_data.game_info.scoreboard_0.mvps
just do {{ (json_data.game_info|first).mvps }}
Hmm strange, this seems to give this issue:
UndefinedError: 'str object' has no attribute 'mvps'
`{% set json_data = {"game_info":{"scoreboard_0":{"nickname":"TRoager","steamid":76561198085455790,"team":"T","money":1000,"kills":10,"assists":0,"deaths":0,"mvps":15,"score":0,"adr":0,"ud":0,"ef":0,"ping":4,"local_player":1}}} %}
{{ (json_data.game_info|first).mvps }}`
yeah
{% set json_data = {"game_info":{"scoreboard_0":{"nickname":"TRoager","steamid":76561198085455790,"team":"T","money":1000,"kills":0,"assists":0,"deaths":0,"mvps":0,"score":0,"adr":0,"ud":0,"ef":0,"ping":4,"local_player":1}}} %}
{{ (json_data['game_info'].values()|first)['mvps'] }}
-> 0
You are amazin !! โค๏ธ
@plush pewter I converted your message into a file since it's above 15 lines :+1:
@sonic sand I converted your message into a file since it's above 15 lines :+1:
There you are! ๐คฉ
You can just change the timestamp_custom filter to include the date as well
is it on the third line?
@plush pewter value: "{{ trigger.event.data.data.['game_info'].values()|first)['mvps'] }}"
I don't know what all the "> " are about, but you need to quote your template
{% set t = timestamp | default() | timestamp_custom('%H:%M', default='unknown') %}
There
tried to do it myself but I failed.
also wanted to ask you, sometimes after my internet drops I get the same notification over over (about it fed them) most likely because it changed from unkonwn to the last fed time
https://strftime.org for all options
is there a way to workaround it so it won't spam me?
You are not referring to adding the date anymore now are you?
I already gave two possible solutions for that
Yeah, you helped me with the unknown options but what about it spamming the fed time after the internet restores
Hold on I will send you screenshot
Oh yes, like this
If that doesn't work, try the condition
Still same issue :/
Message malformed: invalid template (TemplateSyntaxError: expected name or number) for dictionary value @ data['action'][5]['if'][0]['value_template']
{% endif %} {% set t = timestamp | default() | timestamp_custom('%H:%M' '%d/%m',
default='unknown') %}
is that ok?
just need the day and month
https://imgur.com/YESqam9
That is the screenshot, you see at 8:00PM it did fed them so it did as supposed to.
but at 9:07 internet restored and sent the same notification again (probably the state changed from unknown to the actual feeding time)
Okay the new timestamp is working fine, just adjusted it
{% endif %} {% set t = timestamp | default() | timestamp_custom('%H:%M %A',
default='unknown') %}
Thanks man
Might be my template for "testing"
{{ (trigger.event.data.data.['game_info'].values()|first)['nickname'] == 'TRoager' }}
this seems to be invalid since its a string and not a number
If that is the case, and the not_to/not_from didn't help, then try the condition
I will test it out for 24H because I added the not_to/not_from after it happened.
but will it prevent from the same notification to show twice?
No, it will prevent that the message will be sent if the attribute changes to or from none. And it will be none if your switch is not available
The condition will basically do the same, but will check on the state of the switch itself
Okay, thanks.
so generally there is no way to prevent the issue that I showed up in my screenshot?
Because this condition is preventing the unknown issue, right?
Well, in practice it will prevent that
is it possible to get the current color of my lights? am i close?
{{ state_attr('light.aaron_s_room_light_3', 'color') }}
The message is sent because the attribute changed
If you are looking for the color name, you can't
about what color value?
Question is there a way to check the last attribute that was sent to prevent it to send it again
And I'm trying to tell you that either the condition, or the extra values on the trigger will already prevent that
Okay, I thought it will only prevent the unknown
Check devtools > states for all available attributes
gotcha thanks. i forgot about that
I will check it for a day see if it will stop to send it more than once.
Thanks for your explanation and help!
If you really want to prevent the same message to be sent again, you can write the last message to an input text, and compare that to the new message.
But I don't think that's needed here
this is what i do for some things
how do i make it look for a str object instead ?
mmmm sounds right, and if it's equal don't send the action
i have an automation broadcast emails from work and i have an input text to compare the old message to the new message.
and where does it holds the text? in a helper?
yeah basically
i store the subject of an email and compare it to the new email, if its different, it will continue
cool, I will check it the condition won't prevent it I might create a helper to do so
you can also look at doing things like checking the TIME a value changed, and if it did / didnt change in the last X minutes or hours or whatever, then also do X and Y
ok Internet just restarted and I got the notification again, I will try now the condition to see if it prevents it.
How do i make a template condition to see that the state has been 'on' less then xx seconds?
You could have 2 conditions, one state condition to check that it's 'on' and a not condition for the xx duration of the state, unless there's a reason you didn't mention where you need a template.
I just created an automation to turn in the hallway light when entering the house. The trigger is when door has been opened condition now is a template: states.motionsensor.last_changed < 30
But i think thats actually 1 minute because it changes from detected to not detected in 30 secs
you can have multiple conditions
Yeah i know, my brains wont work today ๐
I'm setting up an energy template sensor to calculate my current energy bill cost. My bill cycle runs from the 17th of the month-17th of the next month. There is a daily charge for electric service of $0.71/Day. How can I calculate how many days its been since the 17th of the previous month so I can add this in to my template sensors math to figure out the total cost?
Good Morning guys, is it possible to replace my string "John Doe (1999)" with "John Doe" inside a template? The passed in Variable can have the year in brackets at the end but that isn't always the case.
Can I specify some duration in a code section of a template?
- condition: template
alias: "Check if the light is above threshold"
value_template: >
{{ states(lux_sensor)|int >= states(light_threshold)|int }}
I would like to add to this that it needs to be true for 30 seconds
{% if now().month == 1 %}
{% set cycle_start = now().replace(year = now().year - 1, month = 12, day = 17) %}
{% else %}
{% set cycle_start = now().replace(month = now().month - 1, day = 17) %}
{% endif %}
{{ (now() - cycle_start).days }}
I came up with this:
value_template: >
{% set lux_state = states(lux_sensor)|int %} {% set threshold =
states(light_threshold)|int %} {% if lux_state >= threshold %}
{% set trigger_time = trigger.last_triggered %}
{{ (as_timestamp(now(), default=0) - as_timestamp(trigger_time, default=0)) >= 30 }}
{% else %}
false
{% endif %}
Testing now, but still seems like it runs "immediately"
Create a binary sensor comparing the lux value with the threshold, and use that in a state trigger with for: "00:00:30"
Is that the usual approach, or do people mostly just check the lux value before turning off the lights once a threshold has been found? I see my hue illuminance sensors tend to jump a little around
(What would the sensible thing to do be)
Huw illuminance only changed upon motion, it doesn't change with just lux changed I believe so it's useless to any automations based on it, would need a separate luminance sensor that will change when luminance changes
It be to preserve battery also in the default hue app there isn't much automation to do with luniminance so no suprise it's not in firmware to report when changes
I would get a separate sensor and have that as a condition to triggering motion
Aah, so if I have detected motion at low light during sun-up, then the added changes in light level won't trigger my "shut down lights when the light level is above my threshold" ?
Man, I bought 5 hue sensors just because of that illuminance lol, now they're sorta not fully useful to me :/
Illuminance is a part of the motion sensor I believe so it's not specially a real illumiance sensor put in there for this sort of thing
There is some motion sensors with built in separate illumiance like aotec 5 in one
How would you get a generic value without specify its name? (Like if the name changes and you just want to dump all the values from the list of content in the markdown) https://paste.debian.net/1270469/
Something like this: https://imgur.com/a/rUjyF8g
Does anyone know of any repos of template examples? The docs dont show full examples.
Ignore this - found a decent youtube tut.
can you explain how this works? im a bit confused reading it
In pseudo code:
If the month now is Jan,
Set cycle_start to today's date but minus one to the year, set the month to Dec and set the day to 17.
Else,
Set cycle_start to today's date, except minus one to the month and set the day to 17.
Return the number of days between now and cycle_start
Is its possible to take a delta reading using history_stats? I want to get the KWh from a sensor for the current week. Or should I use something else?
Maybe check https://www.home-assistant.io/integrations/utility_meter for that. You can set the cycle time there where it'll reset weekly
Looks like it only uses new data. I suppose that's ok - I'll have to be patient ๐ฆ
Can someone please help me with this ESPHome template switch?
` - platform: template
name: "Display Page Switch"
lambda: |-
return display.is_displaying_page("page1")
return display'is_displaying_page';
turn_on_action:
- display.page.show: page1
turn_off_action:
- display.page.show: page2`
It says: /config/lora32-v2-oled.yaml:66:21: error: expected primary-expression before '.' token (that's the return line)
ESPHome is a system to control your ESP8266/ESP32, with a native integration for Home Assistant.
You can find their documentation here, and get help with ESPHome itself here in the #diy-archived channel (#integrations-archived for the Home Assistant side integration with it). They also have their own Discord server too.
You'll want to check w/ their Discord
Short logic question...
{% set thermlr = 'climate.livingroom_thermostat' %}
{% if states('schedule.home') == 'off' or states('schedule.away_no_heating') == 'on' %}
{{ state_attr(thermlr, 'current_temperature')|float(0) > states('input_number.living_room_low_temperature')|float(0) }}
{% else %}
{{ state_attr(thermlr, 'current_temperature')|float(0) > states('input_number.living_room_home_temperature')|float(0) }}
{% endif %}
Would "else" trigger only if neither of the conditions in the if is true?
yes
Ok cool, then it should work. Somehow my brain was telling me that it would also trigger if only one of them is true ๐
the "or" explains it
or if both were true, which would also suck
what you described is "and"
Haha yeah, so it sounds logical, but somehow wasn't sure
I'm trying to utilize an addon (Sankey) to map my power usage in my home, but I've run into a potential problem that due to how my solar PV system presents if it is drawing to/from the grid/battery, rather than give two seperate entitys it only has one that goes positive/negative depending if its charging/discharging. So my thinking is a 'simple' solution is to create two new entities based on a template from the source. setting them to what they need to be depending if the source is a positive or negative number. Does that make sense and is possible?
I've written some.. basic templating? which I think will do the correct logic but unsure how to turn that into entities ```{% set grid_power = states('sensor.growatt_grid_power') %}
{% if is_number(grid_power) and grid_power | int <= 0 %}
Sending {{ grid_power }}w to Grid!
{%else%}
Drawing {{grid_power}}w from Grid!
{% endif %}
{% set battery_charge = states('sensor.growatt_battery_power') %}
{% if is_number(battery_charge) and battery_charge | int <= 0 %}
Sending {{ battery_charge }}w to Battery!
{%else%}
Drawing {{battery_charge }}w from Battery!
{% endif %}```
... Sorta, Still very much getting my head around the basics of this stuff ๐
@leaden harness I converted your message into a file since it's above 15 lines :+1:
Executed: February 12, 2023 at 6:03:00โฏAM
Result:
result: false
conditions/0
Executed: February 12, 2023 at 6:03:00โฏAM
Result:
result: false
conditions/0/conditions/0
Executed: February 12, 2023 at 6:03:00โฏAM
Result:
result: true
conditions/0/conditions/1
Executed: February 12, 2023 at 6:03:00โฏAM
Result:
result: false
entities: []
Is there a way to basically do a string variable? I want to be able to set the values of a string global to Home Assistant that Node-Red and/or ESP Home can reference. Seems like this is solved already and I'm just lost on what to search for.
Welp, closer
I've got an input_text sensor called 'alarm_url' setup and it is updating in HA through Node-Red. Here's my ESPHome config for it; but it's never updating. on_value is never triggering even when I force a change to the input text entity:
text_sensor:
- platform: homeassistant
name: "Alarm Url"
entity_id: input_text.alarm_url
id: alarm_url
internal: true
on_value:
lambda: |-
ESP_LOGD("main", "Alarm URL: %s", x.c_str());
Is there a way to poll for a sensor value rather than using esphome's update function or am I doing something wrong here?
You'll get more help on their discord server
ESPHome is a system to control your ESP8266/ESP32, with a native integration for Home Assistant.
You can find their documentation here, and get help with ESPHome itself here in the #diy-archived channel (#integrations-archived for the Home Assistant side integration with it). They also have their own Discord server too.
Thanks!
Hi all, I have a sensor that keeps showing up as 'unavailable' even though my code should not allow it:
https://hastebin.com/share/urenusetih.csharp
can anyone see what I am doing wrong?
I don't see how you're preventing it
The state trigger will cause errors because it doesn't have event data
If you have an availability key, it can be unavailable
Looks like you added the state trigger as a kind of condition, but that's not how it works
Do it the other way around, check on the unwanted states and combine that with the check on the device tracker. Do that check first in your if statement
- trigger:
- platform: event
event_type: delonghi_primadonna_event
- platform: state
entity_id: device_tracker.delonghi_primadonna
to:
- unavailable
- unknown
sensor:
- name: DeLonghi Dinamica Plus
icon: mdi:coffee-maker-outline
state: >
{% if trigger.platform == 'state' or states('device_tracker.delonghi_primadonna') == 'not_home' %}
Disconnected
{% elif %}
Your other stuff
{% endif %}
Oh, and indeed remove the availability
now here's a challenge ๐ having a rest sensor to dutch KNMI results in a Waarschuwing attribute that does not always contain the same string. When all is good (green) a simple text string is returned so I can use {{state_attr('sensor.knmi_waarschuwingen_nb','description')}} and have it say 'Code Groen, geen waarschuwingen'. I use that in a markdown. However, when an actual alert is on, the same template returns: Code Geel.<br>Plaatselijk dichte mist.<p><a href="/kennis-en-datacentrum/waarschuwingen/zicht">Wat kan ik verwachten en wat kan ik doen bij slecht zicht door mist?</a> (van 13/02/2023 09:00 tot 13/02/2023 11:00 uur)<br><br> which has an incomplete link in the href... so using that in the frontend does show correctly like in the screenshot, but clicking it leads to nowhere. It should add the prefix to this full address https://www.knmi.nl/kennis-en-datacentrum/waarschuwingen/zicht, so insert https://www.knmi.nl . Any thought on how I should approach that template...?
thanks ! I did consider that, but am not sure if that also works when there is nothing to replace? in the case of no link when Green
if there is nothing to replace, it will do nothing
well, the filter will do nothing
great, Ill add it and thank you very much!
Added an extra replace for the double <br><br> which messed up the layout, using ``` content: >
Actueel:
{{state_attr('sensor.knmi_waarschuwingen_nb','description')
|replace('href="','href="https://www.knmi.nl')|replace('<br><br>','')}}
KNMI waarschuwingen Noord-Brabant
you can remove the elif in lines 29/30. You already covered that option in the first if
Morning,
as I'm trying to get rid of all logs issues I got this error
http://pastie.org/p/5GR23gq4zl61B4QrG2bA0x
this is the sensor:
http://pastie.org/p/7MQKIUSHw3aYYs1hIQ8T8u
and this is the template of the part of the automation that TheFes helped me with -
http://pastie.org/p/0CQI6JIk1QYqdTKhkx56U3
Thanks!
also got this warning before the error above^
Logger: homeassistant.components.sensor.helpers
Source: components/sensor/helpers.py:22
Integration: Sensor (documentation, issues)
First occurred: 10:00:13 AM (2 occurrences)
Last logged: 10:02:04 AM
sensor.feed_record_timestamp rendered invalid timestamp:
add an availability_template which checks if the switch (or attribute) is available
well through the devtools I get that:
ValueError: Template error: timestamp_local got invalid input '2023-02-11 18:00:17+00:00' when rendering template '- platform: template
sensors:
feed_record_timestamp:
value_template: >-
{%- if state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1') -%}
{% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %}
{{ as_datetime(feed_record.timestamp)|timestamp_local }}
{%- endif -%}
friendly_name: "Last Fish Feed"
icon_template: "{{ 'mdi:fish' }}"
device_class: timestamp' but no default was specified
by the way, the condition on the fish tank automation did prevented the duplicate messages so far
- platform: template
sensors:
feed_record_timestamp:
value_template: >-
{% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') | from_json %}
{{ as_local(as_datetime(feed_record.timestamp)) }}
friendly_name: "Last Fish Feed"
icon_template: "{{ 'mdi:fish' }}"
device_class: timestamp
availabitliy_template: "{{ state_attr('switch.hfjh_v2_eadb_fish_tank_2', 'event.4.1') is not none }}"
Does this work?
the sensor expects a datetime object or a isoformat datetime string
Edit:
Works perfectly!
@sonic sand I converted your message into a file since it's above 15 lines :+1:
Most likely a dumb-ass question , but where can I find what the difference (and how to use) between '{%' and '{%-' ?
Thanks
The difference between {% and {%- is that {% is used to start a statement, whereas {%- is used to start a statement that will not add an extra whitespace character after it.
Should I have found this in the manual ? (Where I hope are some explanatory examples)
Not that I am familiar with
This is all jinja syntax. Look up a basic jinja tutorial on google.
I can't find a tutorial that actually covers the delimiters
Jinja uses various delimiters in the template strings.
{% %} - statements
{{ }} - expressions to print to the template output
{# #} - comments which are not included in the template output
Adding a - after a starting delimiter will remove previous whitespace. Adding a - before an ending delimiter will remove trailing whitespace.
e.g.
{%- removes leading whitespace before a statement
-}} removes trailing whitespace after an expression that prints to the template output
click the link to Jinja in /developer-tools/template, and go to https://jinja.palletsprojects.com/en/latest/templates/#whitespace-control for this specific aspect. run the full rext a couple of times, to get the idea of its content, so you'll ring a bell next time ๐
@heady trellis check the most recent ๐ for explanation on the bracket meanings
Hi All, I have a pool pump that I was able to integrate into HA using a HASS plugin. One challenge with using it to manage pump speed is that the pump is turned on an off with a switch entity, but the speed is adjusted with a custom service. I realized I could simplify things with a fan template, and I got it working, but with a challenge in that when it's exposed to HomeKit it shows up in HomeKit as a group of five switches, three of which seem to be turning on and off the presets. I'm not sure what is happening and I'm hoping someone has encountered this before. Template code in a threaded reply.
fans in homekit just show up as a fan
if it's not showing up as a fan, you aren't exposing it as a fan