#templates-archived
1 messages · Page 132 of 1
Are you going to share the value?
Question: Will Zyankali provide the mystery value?
Answer: No
Well, that's pretty definitive.
Lol
Been working a loop using a chunk of code provided by Mono. However, I can't figure out how to deal with a default condition:
{% if trigger.event.context.user_id == '0c3242344a8ef4c5eb0668feaeecf2332' %}Locked by Google
{% else -%}
{% for person in states.person -%}
{% if trigger.event.context.user_id == person.attributes.user_id %} App Lock - {{ person.name }}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
If the user_id isn't the first option, and it isn't in the person.attributes.user_id, I'd like to it be "unknown". But I feel like I've painted myself into a corner here...
Sorry...wrong attribution, Tinkerer provided the loop.
Seems like that could be done by a set of filters and assigned to a variable. Then you can make a decision on whether it found something
But I’d have to play with it and I need to eat. I’ll come back if someone hasn’t figured it out
(states.person|selectattr('attributes.user_id', 'eq', trigger.event.context.user_id)|first).name
Yeah. That's the one that mono gave me last night, but if the user_id doesn't exist in the person list, it blows up because you get an empty result.
Trying to get it to check the person list, if it exist in there output the name. If not, check my hardcoded options. Finally if nothing can be found output "unknown"
So grab the result right after the selectattr, check it, then decide whether to move forward
{% set person = states.person|selectattr('attributes.user_id', 'eq', trigger.event.context.user_id)|list %}
{{ (person|first).name if person|length > 0 else "unknown" }}
oh. piping to length will catch "empty" responses?
sorta - that's how to determine if the search found something
I don't think this is a great way to handle it, though. Why would you get an event with a user_id that doesn't correlate to a person?
there's a user called "cloud_user" which isn't in the user table
If it's just null or 0 or user_id doesn't exist at all, then that's easier to check for explicitly
then you can just check for that
not sure if there are others
anyway, I think what I have up there should help
Thank you
`## Some one home
- platform: template
sensors:
someone_home:
friendly_name: Someone Home
device_class: presence
value_template: >-
{{ is_state('person.xxx', 'home')
or is_state('person.gggg', 'home') }}`
Is it possible to have this sensor act by the domain person and not individuals?
Hi everyone, why is my template energy sensor sometimes dropping to 0 when it is just a sum of three other sensors?
'home')|list|length > 0 }}```
thanks
.share your template
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
- sensor:
- name: "Total Energy"
state: >
{% set phase1 = states('sensor.energy_phase_1') | float / 1000.0 %}
{% set phase2 = states('sensor.energy_phase_2') | float / 1000.0 %}
{% set phase3 = states('sensor.energy_phase_3') | float / 1000.0 %}
{{ (float(phase1) + float(phase2) + float(phase3)) | round(3) }}
device_class: energy
unit_of_measurement: "kWh"
state_class: measurement
attributes:
last_reset: '1970-01-01T00:00:00+00:00'
if any of those are ever unavailable they'll eval to 0.0
could just add an availability template to it
ok, so I can leave state like it is and add availability_template to set it to unavailable when one of the phases is unavailable?
thank you very much guys!
@dreamy sinew @ivory delta Yesterday i tried and then went to sleep . Where can i find the value , iam a bit lost what i need to share is it this? supported_color_modes: hs color_mode: hs brightness: 255 hs_color: 0, 100 rgb_color: 255, 0, 0 xy_color: 0.701, 0.299 friendly_name: Canvas FA77 supported_features: 17
Use the template I asked you to use.
which template you mean?
other question, i got this work now how i want ```template:
-
sensor:
-
name: "canv"
state: >
"{% if state_attr('light.canvas_fa77', 'brightness') | int >= 220 %} bright
{% elif state_attr('light.canvas_fa77', 'brightness') | int >= 200 %} bright2
{% elif is_state('light.canvas_fa77', 'on') %} on
{% else %} off
{% endif %}"``` how can i use this entity in Picture Elements Card ? When i use the Sensor.canv it dont Work anymore with changing Pictures
-
You should ask in #frontend-archived
https://pastebin.com/qcATGiVc
https://pastebin.com/VvVG18xP
This data_template: code works correctly but when I save the Automation and refresh the page, the linebreaks are reformatted/screwed up, changed from the first link to the second link (lines 6,7,8), what am I doing wrong?
First, data_template: was deprecated over a year ago - use data:
Second, if you let the UI interfere, you can expect to see it formatting your code in odd ways
They appear functionally equivalent to me, so what's the problem?
I don’t think the spacing is particularly important there
Second one is 'better', just because the opening tags are all on their own line. The UI knows better in this case.
You shouldn't have to read halfway along a line to see where something new starts.
i think you've got them switched?
Aha, I clicked the links in the wrong order 😂
But yeah... #templates-archived message
If you're doing something advanced enough to need multiline templates, you're probably better off using a real editor.
is there a way i can not have the UI "interfere" ? other than move the whole automation into raw yaml ?
Nope. You use the UI or don't. It's not customisable.
ahhh okay
If you're comfortable with YAML and Jinja, I'd recommend switching to YAML mode and just SSHing in with something like VS Code.
You get a lot more control over how your config is organised too if you start splitting the files out.
A good example from one of the users here: https://github.com/DubhAd/Home-AssistantConfig/tree/live/automation
But for more on splitting your config, head over to #integrations-archived
I want to change the color if both speakers are playing, works fine for one speaker but the template below seems not working Anyone know whats wrong on this? Thx
ha-card {
--primary-text-color:
{% if is_state('media_player.sonos_keuken', 'playing') and (states('media_player.badkamer', 'playing') %}
#EBEBEB
{% endif %} ;```
states('media_player.badkamer', 'playing') isn't valid, and you have too many opening parentheses in your template.
Got it fixed in the meanwhile, thanks anyway for the help mono. 😉
This is the working version.
ha-card {
--primary-text-color:
{% if is_state('media_player.sonos_keuken', 'playing') and is_state('media_player.badkamer', 'playing') %}
#FFA229
{% endif %}
;```
Coming over from automations. I need a template sensor that turns "on" when message attribute of calendar.district_calendar CONTAINS "No School" they put all sorts of other information like "No School - Teacher Workday" or No School - Teacher Training", but they all contain "No School" as a string. Help!
{{ "No School" in "No School for frogs" }}
or for your actual use case: {{ 'No School' in state_attr('calendar.district_calendar', 'message') }}
@proper holly
Wow, so easy. Will put into testing! Thanks!
you can test in
-> Templates and change the attribute to whatever you want in
-> States
Worked perfectly. Thanks for the help!
Thanks @inner mesa
One more question, they have a few that are "NO School" with a capital "O" in "NO". Can I make it non-case sensitive?
@inner mesa
you can use filters to force a case on both sides
something like {{ "No School"|lower in "No School for frogs"|lower }}
Ah fantastic. Whole new world!
Hello there template masters.
I"m trying to figure out why this is throwing an error
sensors:
living_room_window_sensor:
value_template: {% if 'states.binary_sensor.living_room_window' %}
{% if states.binary_sensor.living_room_window.state == "off" %}
open
{% else %}
closed
{% endif %}
{% else %}
n/a
{% endif %}
friendly_name: 'Living Room Window Sensor'```
I get the following error message when I lint it ```(<unknown>): found character that cannot start any token while scanning for the next token at line 4 column 24
I don't understand what the issue is. I've tried with quotes without
this was working
either put it in a single line under quotes or open a multiline with >
I don't fully understand. Sorry my yaml skills are lacking but they're getting better
If you want to put a template on multiple lines, you must write value_template:> and not wrap your template in quotes.
is there anything like relative_time to count "age" of kids? I'd like to create 2 sensors for kids - older one getting value "x years, y months" and younger: "xx weeks"
or even "x weeks, y days"
Your syntax is also wrong. You have if - else -endif -else -endif. You cannot have an else without a starting if. Your second else onward is wrong and should be removed. EDIT: Nevermind, you just formatted that in an odd manner. Disregard.
You have to calculate it yourself if you want years and months
and once you get to months, it becomes ballpark numbers.
years and weeks are easy to calculate. Months are not because calculations require a static number of days and as you know months alternate between 28, 30 and 31 days
I reformatted it a bit, your first if statement doesn't seem to be an if statement..
value_template: >
{% if 'states.binary_sensor.living_room_window' %} {# if what?! #}
{% if states.binary_sensor.living_room_window.state == "off" %} {# better use if is_state('binary_sensor.living_room_window', 'off') #}
open
{% else %}
closed
{% endif %}
{% else %}
n/a
{% endif %}
friendly_name: 'Living Room Window Sensor'
should use is_state which would handle that entity existing properly
{{ map.get(states('binary_sensor.living_room_window'), 'n/a') }}```
@pliant dagger ^ simplified lookup
shouldn't we just do the proper setup for that device? I just noticed it's a binary sensor:
template:
- binary_sensor:
- name: inverted living room window
state: "{{ is_state('binary_sensor.living_room_window', 'off') }}"
device_class: window
probably
I wish we could expunge these old templates when device_classes and translations didn't exist
lol
even from my head 🤣
hi everyone, Im trying to use the value of a script field on wait_for_trigger template and it errors saying that the variable is undefined, is that expected? this is the block (time_away is the field that I defined on the script :
- wait_for_trigger:
- platform: template
value_template: '{{is_state(motion_sensor_entity_id, ''off'')}}'
for:
minutes: '{{ time_away|int }}'
need to share the full thing
@dreamy sinew this is it https://paste.ubuntu.com/p/dbKhXxkFdn/
seems fine. have you tried tracing the run with the new debugging tools?
yeah, execution wise looks fine, but the logs say Error rendering 'My Script' for template: UndefinedError: 'time_away' is undefined is like the fields defined on the script are not passed downstream, like they're not available on the for: section
btw, I tried creating a variable as well, and it's the same...
by new debugging tools you mean the diagram of the execution, right?
are you just running the script? If yes, then you aren't providing the script with defaults for it to run without error
i.e. clicking 'run'
the examples do not auto populate the data, so you have to provide it yourself or give defaults to the variables
thank you @mighty ledge so are you guys saying that we don't really need the value templates to convert on/off to open/closed anymore? Except in the case of my living room window where its backwards, which is the result of using an external sensor. Took me some time to figure out how to monitor a dual slide window but that did the trick
binary sensors 'under the hood' are treated as on/off. But in the UI they are translated based on whatever device class you use. If you use a 'window' device class, it will appear in the ui as "Open/Close"
ah gotcha, thank you for educating me. A lot of this stuff was stuff I setup years ago
but I'll gladly go through and clean it up. Will require changes to my automations to monitor a different device and the state of said device from being open/closed to on/off
yah they are like 3 years old now tho
mainly my alarm code in appdaemon I'll just have to add an 'or' statement in there
I made that change at some point, so it was only a matter of time
ya
I ditched appdeamon too
kicked that pile o mess to the door. You can do most things in native automations now
Yeah me and yaml aren't the best of friends lol
pyscript then
probably
appdaemon is so bloated now
I'll have to look into that
I like the ability to reuse one script multiple times
which I'm sure there is a way to do that natively as well
Most of my appdaemon apps were 100s of lines, on conversion most of them are shorter with yaml.
thats always a bonus
I'll have to research that and see where I can convert things
There were 2 that I didn't want to convert and I just made custom integrations
which were shorter than the appdeamon apps
and easier to understand
I also use NodeRed for things but I keep that to a minimum
flows get so big and messy
I never bothered with NR, I don't think like that
I thought it would be something neat initially
and it was
but the flows can get complicated and it was easier just to write a few lines of python to do the same thing
ya
the api for integrations now is super duper simple
and you can fake out configurations by passing a True back from the config validator if you want to bypass all the voluptous
oh dang
ok so how does one set the device class?
aww can't paste pics in here
but I'm looking at a binary sensor for a door
customization
Thanks @mighty ledge
template:
- sensor:
- name: "energy_current_hour_watts"
unit_of_measurement: "W"
state: "{{ (states('sensor.energy_current_hour') * 1000) | float }}"
What did i do wrong?
You didn’t add |float
States are strings
Just move the one you have to after states()
thanks that removed the errors although the sensor still doesn't show up in the dev tools
did you reload template entities or restart HA?
both actually
Package templates setup failed. Component template cannot be merged. Expected a dict.
is there a way around that?
put it in configuration.yaml
thanks alot 👍 i don't really understand though how that made a difference 🤔 i mean if i do: template: !include template.yaml it works aswell
nope, well, yes, but I'm providing the data, btw thanks for answering
if you put that in configuration.yaml, that's why
I also think that Paulus did something that may help. https://github.com/home-assistant/core/pull/54085
just starting out and I'm looking for advice on setting color_temp via left-right button on tradfri. I'd like to adjust the color_temp up or down similar to the automation brightness step. Wondering if I need to do this in a script, or a template in the automation?
Hi Guys,
I would like to turn on a switch when my last active sensor changes state.
The sensor is changing every time it detects mouse movement on my computer.
I don't want the trigger to fire all the time when I use the mouse.
I tried to do a template trigger but it can't get it working.
Something in this direction:
{{ now() - states.sensor.last_active_sensor.last_updated > "5 minutes" }}
Is this even possible?
Is this for an automation?
If so, just set the run mode to single and put a 5 minute delay as the last action.
{{ now() > states.sensor.last_active_sensor.last_updated + timedelta(minutes=5) }} 🤷
So can Jinja just support full python expressions? Or are these custom filters and tags specifically for HA
HA Templates support Jinja + some extensions as described in https://www.home-assistant.io/docs/configuration/templating/, but the objects themselves support methods from Python
{{ "foo:bar:blah".split(':') }}, for instance
and Python data structures, like dicts, lists, datetime, etc.
thx
{{ (states('sensor.office_desk_peripherals_power')|float > 30.0) and ((as_timestamp(now()) - as_timestamp( states.sensor.last_active_sensor.last_changed))|float < 10) }}
`
Entering the above code into the developer template tools:
This template updates at the start of each minute. <<<<---- How would i reduce this interval?
Can somebody help me. I have some states for each user where it records the time and date of when the user unlocks the door. Everything behind this works. Including the states which change there time and dates when that user unlocks the door. I have this sensor (unlocked_by) which is what the conditional Lovelace cards use to determine who was the last to unlock the door. However, both David and Vicky work but if I add anymore such as spare card or another user it doesn’t work. Could somebody help me? I’m completely stuck
https://paste.ubuntu.com/p/r9Crz3mr35/
Sorry if I’ve posted this wrong. I’m a little new. Any help is appreciated.
I basically need the sensor to determine which state is the latest time and date and then update with the corresponding users name
🤦♂️
I did just say to use a code sharing tool, right?
Delete your post, do it properly.
And delete the post back in #automations-archived too while you're at it.
Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs
Done, apologies.
@warm ibex See if this works. If it does you can add as may cards to the list and elif statements as you want https://paste.ubuntu.com/p/DHwN7shPBq/ if it does not work the input datetimes need to be converted to timestamps first. EDIT: I just tested it. It works.
Hi Tom, I’m very grateful for your input on this. When I add this it says the entity is not available. Any ideas? I get an invalid template error expected token 'end of statement block', got '=')
The if statements should use the comparison operator == not =. Sorry.
Only the set statement should use =.
Like this: https://paste.ubuntu.com/p/YYx7ctxS4C/
Hi Tom, omg 😱 you are amazing! You’ve fixed all my issues. I was near to breaking point.. thank you so so much!
Hey guys, I'm trying to add two additianal sensor for smarter status reporting of a poolcover. Can I simply just add the bottom two sensors to the template sensor here? There are comments in the paste that should explain what I'm trying to do/understand
It depends on where you’re using it. If you’re creating a template sensor, you can add a time_pattern or other type of trigger to indicate when and how often it should be reevaluated
i'm using it with a template sensor
Great, then follow the docs to add a trigger
Can a template reference itself or does that result in a loop as the templates own value would change? For instance.. - sensor:
- name: "DTE Daily Energy"
state: >
{% set minuteKwhUse = states('sensor.dte_summation_minute') | float / 1000 / 60 %}
{{ (float(minuteKwhUse) + states('sensor.dte_daily_energy') | float) | round(3) }}
unit_of_measurement: kWh
device_class: energy
state_class: measurement
In that case, wouldn't you need two sensors and an automation?
No...? Make a template sensor that exposes the value you want for minuteKwhUse, then create another template sensor that uses the result and performs the next step.
No circular references 🎉
Does anyone know of a way to force decimal places?
When using round(2) – if I have a float with a value of 13.4004, it'll round to 13.4 instead of 13.40
but if the value is 13.405 it would round to 13.41
'{0:.2f}'.format(your_number_here)
You'll still want to round first so you're not just truncating the extra digits.
though the template tester will still chop it for reasons
It doesn't here...
Ah, my example with pi isn't useful 😄
Will it return correctly in a template sensor?
but $%0.2f works
This is returning 1.20 for me:
{{ '{0:.2f}'.format(1.20000) }}
force it into a string
Is it that thing where the Dev Tools works differently if you only have a single template in there?
probably
Yup
its getting natively converted to a number
Just got rid of the rest, can confirm.
gotcha. It's NBD.
templates
cold starting a thread is a good way to be ignored
ahh. ok. nevermind that then
Please stop tagging me.
When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
For my template, I am still getting a circular reference when split. it looks like it still complains of circular references
- name: "DTE Daily Energy"
state: >
{{ ( states('sensor.dte_minute_energy') | float + states('sensor.dte_daily_energy') | float ) | round(3) }}
unit_of_measurement: kWh
device_class: energy
state_class: measurement
you are still referencing the sensor within itself
Are you just trying to keep a running total?
agreed, doesn't seem like templates can update themselves. I am trying to run a total in a template
And if this is for use with the new energy dashboard, #energy-archived can help more.
ok. I will try there. I need to convert from minute based kwh usage to hourly in order to use utility_meter
for totals in general, it doesn't appear that templates are appropriate
Templates are a calculation of known values, not a tracker of any form of history.
And I think you misunderstand power/energy. If you have something that can report power, the rest is easy... but still #energy-archived
@grave cargo posted a code wall, it is moved here --> https://paste.ubuntu.com/p/mKgcFkQ45Z/
@grave cargo posted a code wall, it is moved here --> https://paste.ubuntu.com/p/rc8WwTZ8GY/
🤦♂️
@grave cargo Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
For sharing code or logs use https://paste.ubuntu.com/.
44 lines of text across two posts. Nice.
Energy questions go in #energy-archived. Share a short description of your issue there and include the rest in a paste from a tool like the one in the bot message.
Thanks and sorry for trying to explain my issue with to much text 🤣
Is it possible to use customize_glob to add a friendly name that truncates the suffix? All of my energy sensors end in "_energy" and I would like to strip energy off and make the friendly name the rest of the entity id
You're describing a RegEx replacement.
Not quite the same as a glob but similar idea.
Can that be done through customize_glob so I can bulk hit all of my entities?
Nope.
Could the template update the friendly name?
Nope.
Templates just are. They're calculators. They don't impact other things.
Hello, is it possible to somehow get the last_changed or last_updated attribute on a template sensor? I have a template sensor that just tracks the position of a cover. I would like to make a sensor to track if it's moving or not, and i thought sensors had last_changed attribute?
Okay, it's just under developer tools and attributes there is not anything like that. Is it because it's a hidden attribute and can just be used in automations?
In templates, but yes.
It's not an attribute in the sense of entities having attributes. It's just a property of that state object.
Yeah in templates. Okay I will try playing around some more with it.
I just don't really get any results when I try it out in template. This is the templates. And the output is blank for the first two, and None for the last.
{{ states["sensor.cover_position_livingroom_1"].attributes.last_updated }}
{{ states["sensor.cover_position_livingroom_1"].attributes.last_changed }}
{{ state_attr('sensor.cover_position_livingroom_1', 'last_updated') }}
{{ state_attr('sensor.cover_position_livingroom_1', 'last_changed') }}
@hot swift I checked a couple of mine. They seem to behave a bit differently.
Normal sensor:
{{ state_attr('sensor.tellstick_id_22_temperature', 'lastUpdated') | timestamp_local }} = 2021-08-13 23:49:50
{{ states.sensor.tellstick_id_22_temperature.last_updated | timestamp_local }}= 2021-08-13 21:50:38.842806+00:00
Template sensor:
{{ state_attr('binary_sensor.balkongdorr_sovrum_tmpl', 'lastUpdated') | timestamp_local }} = None
{{ states.binary_sensor.balkongdorr_sovrum_tmpl.last_updated | timestamp_local }}= 2021-08-11 09:36:08.678170+00:00
Also note "lastUpdated" vs ".last_updated".
Based on this, does {{ states.sensor.cover_position_livingroom_1.last_updated | timestamp_local }} give you anything useful?
Based on this, does {{ states.sensor.cover_position_livingroom_1.last_updated | timestamp_local }} give you anything useful?
Which is... what phnx said 🤯
Yes. But for some, me included, it is easier to see an actual example. Anyway, i hope AnthonMS got what they needed.
I'm having conceptual difficulties. I am looking at KASA HS110 power adapters, and I'm trying to figure out where in the HA UI I can see the attributes of the device (so I can create templates etc.) I have seen example templates with entries such as: washing_machine_pump_volts: friendly_name_template: "{{ state_attr('switch.washing_machine_pump','friendly_name') }} Voltage" value_template: "{{ state_attr('switch.washing_machine_pump','voltage') | float }}" unit_of_measurement: "V"
But I don't see where I can find the relevant information ie: voltage? How do I 'list' the attributes of a device, so I can create the relevant sensors for my setup?
Developer Tools
/ States
Hmm, in my case, that doesn't give me any more information. If I look at the switch.washing_machine_pump entity. I don't see any attributes other than friendly_name.
The attributes available depend on the integration you use.
The tplink integration creates 5 entities per port/switch. One switch.washing.. and 4 sensors. These sensors entities would be named sensor. Washing_machine_pump_voltage , current, total consumption & today's consumption.
The switch entity wounld only have the state: on/off attribute.
@wet vault 👍 thank you
i have a command_line sensor that outputs a huge float in celsius. using the example template from the docs seems to throw off the conversion to fahrenheit. without the template the conversion is correct. is there something else i need to do to trim the sensor output? e.g from 119.72000133989536 °F to 119.7 °F
- platform: command_line
name: Core Switch Temperature
command: "ssh -o StrictHostKeyChecking=no -o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null homeassistant@10.0.2.2 -i /ssh/id_ed25519 \"show system environment temperature | json\" | jq '.tempSensors[] | select(.name==\"TempSensor1\").currentTemperature'"
unit_of_measurement: "°C"
# value_template: "{{ value | multiply(0.001) | round(1) }}"
I'm not following. You have value_template there that should effect the rounding, but you've commented it out. What exactly is the problem?
yes, when it's uncommented it rounds but the conversion to fahrenheit is incorrect, 32.0 °F
Thank you for this reply, it helped a lot! I have briefly tested it out with these two templates:
{{ state_attr('sensor.cover_position_livingroom_1', 'lastUpdated') | timestamp_local }}
{{ states.sensor.cover_position_livingroom_1.last_updated | timestamp_local }}
The first returns None, but the second returns "2021-08-14 18:07:54.015289+00:00", so now I think I can make my binary_sensor that checks if it's currently changing/moving.
Thanks again
nevermind, just needed to remove the multiply
The timestamp local on that isn’t doing anything FYI.
So you can just remove the | timestamp_local
I've been working on this for weeks and feel so close, yet so far away... Hoping someone here can help me. All I want to do is take my automation that I'll post, but make it trigger off of ANY moisture sensor in my HA setup without having to list each one out. I THINK I need to do this with a template, but I can't figure out how to format it. Am I on the right track?
You could certainly do it with a template, but that might work
Did the UI build that?
I suspect that platform: device is wrong
You want entities with device_type: moisture
Rob, you gave me a sample code a few weeks back, but when I use it, it take like a minute before it actually triggers.
{{ states|selectattr("attributes.device_class", "==", "moisture")|selectattr("state", "==", "on")|list|length > 0}}
Do you see any reason why it would take so long to trigger when using this vs. watching the state change on a single sensor?
No
Hmm. I've rebooted my RaspPi since trying that last. Let me put that template as the trigger again and try now.
Test it in dev tools
I did, and it still took a long time to change to true.
Try states.binary_sensor instead of states
Just that by itself of inserted into that original template somewhere?
{{ states.binary_sensor|selectattr("attributes.device_class", "==", "moisture")|selectattr("state", "==", "on")|list|length > 0}}
Like that?
Sorry for my ignorance...
Yes
Oh, wow. That triggers in like 2 seconds now instead of 30+
Are you on a pizero?
Weird
When using the first template, it was also listing a motion sensor in my alerts in the actions section. When I just changed it to this new one, it accurately uses the name of the triggering water sensor!
Is there some way I can buy you a beer?
No, just happy it’s working
Well thanks sir. Now I can move on to the next thing. That was the biggest thing bugging me that I couldn't recreate since moving away from SmartThings.
All I did was further restrict the entities under consideration to binary_sensor
So made it only look at binary sensors vs every sensor out there?
Vs every entity
Np
I’m trying to write a template that has 2 If statements and an else but I’m not getting it correct
If a, then x ; if not a, but b, then y, Else z
I keep getting a return of z on the second and third evaluation
So I can get x, but never y when I should
I did it this way ; if a then x else if b then y else z
And then endif twice. I’m thinking my issue is placement of the endif and else
Yea gimme a sec will retype, it’s just going into iOS as a watch complication
(So I didn’t save a draft)
Else if or us elif something else?
‘’’{% if states("sensor.held_lvpd") == "True" %}
VPD
{%else%}
{% if states("sensor.herbybig4_true") == "True" %}
HLD
{%else%}
!!!
{%endif%}
{%endif%}’’’
Sorry on iOS. Not sure if there is a back tick
there is
‘ is apostrophe I assume.
so like I said, elif
{% if states("sensor.held_lvpd") == "True" %}
VPD
{% elif states("sensor.herbybig4_true") == "True" %}
HLD
{%else%}
!!!
{%endif%}
Just looked up elif makes sense never seen that syntax thanks
Thank you kindly Rob
Hmm doesn’t seem to work
Maybe I have a typo somewhere let me double check
it's better written like this, assuming that the sensors and values are correct:
{% if is_state("sensor.held_lvpd", "True") %}
VPD
{% elif is_state("sensor.herbybig4_true", "True") %}
HLD
{% else %}
!!!
{% endif %}
can we template the used unique_id's of our entities somehow? Ive just found an identical unique_id used in my template: sensor and binary_sensor doesn't hurt, but Id like to prevent that nonetheless. Having an easy check for unique_id's would be nice for that
No, unique ids are static, if you let it create the unique_id it will handle that for you.
I meant to have them listed, so we can see which unique_id's have been used already. I don't want to 'template' a unique_id'.... Sometimes we have to manually add a unique_id, (tbh, I manually added them all in migrating the template sensors to the new platform, to be sure they were identical to the object_id's)
Generate a UUID, use that. The chances of generating the same UUID twice are... beyond astronomical.
You'll start seeing collisions in about 2^50 ie. about 10^15 keys. Your chances of seeing a collision if you've populated your database with just 1000 billion keys are still negligible.
you mean with a tool like this: https://www.uuidgenerator.net ?
Or if you have a Linux machine, literally type uuidgen on the command line.
ok, will do that next time I need a manual uuid... (although I like the UID to be related to the entity...) still, Id like to know if/how one can list all used unique_id's. We should be able to do so, as they are attributes of the entities?
They're not attributes, they're just ID's in the registries. You know where to raise feature requests if you want them surfaced.
hello everyone. I am trying to get my HA to read XML data from my pool manager.
I have the following in my configuration.yaml:
https://pastebin.ubuntu.com/p/2WTC4TkdtD/
if I put the address in my browser I get:
<pm5>
<item type="34" id="4033" label="T1" unit="°C" value="27.5"/>
</pm5>
My goal is to "extract". the value (27.5) so that HA can interact with it... but I am struggling with how to get HA to read just the " value" component.
I saw someone on the forms use grep after the address (https://community.home-assistant.io/t/use-xml-result-from-rest-api/6195/9?u=aziwa), but im not sure if thats the right path, if it is i would need help to right the grep.
any help really appreciated 🙂
I'm hopeless with regular expressions but try this: value_template: "{{ value|regex_findall_index('value=\"(\d*\.?\d*)') }}"
thanks @fossil venture , i get the following error with that:
unknown escape sequence at line 39, column 62:
... |regex_findall_index('value="(\d*.?\d*)') }}""
^
Try it like this ```
value_template: >
{{ value|regex_findall_index("value="(\d+.?\d*)") }}
saves ok, and I am able to reproduce what you did in the template developer tools, this is the logs:
line 39 is the value_template
You have not copied what I wrote correctly. See how my template is on two lines? https://paste.ubuntu.com/p/8cBJ7McJG5/
you good sir @fossil venture are a genious!! its working perfectly!!!
2 days iv been trying, thanks so much for your help!!!
hi again @fossil venture , I saw your post on the forum, looks great,
im getting "unknown" however with that code you posted. any ideas? (i assume the ' after value should have been " ?)
ue_template: '{{ value["pm5"]["item"]["value**"**] }}'
Try it without the pm5 value_template: '{{ value["item"]["value"] }}'
And yes that single quote should have been a double.
nope, still unknown
nothing in the logs
dunno if this helps?
or if i did it correctly
but it says " UndefinedError: 'value' is undefined
ok?
do you mean I cannot just add it in the "templates" in dev tools? or the parsing? sorry im easily confused 🙂
I mean pasting that in
-> Templates isn't useful because it's not actually going to make that REST request
the template must be evaluated in the context of that REST sensor
ok
Yeah you actually have to create the sensor and restart.
you could use curl or similar from the command line, capture the output, and seed a variable with that to test the template, if you want
thats where we started. Restful avoids nasty xml searches with regex as it converts xml to json.
Oh sorry, you mean to test. Yeah it works.
dunno if this is any help but i tried this:
Nope. The template editor is not going to do xml -> json. Only the rest sensor will do that. You have to actually create the sensor.
ok let me try
so basically I would create it with this?
- resource: http://10.1.1.42/cgi-bin/webgui.fcgi?xmlitem=34.4033
scan_interval: 60
sensor:
- name: "PoolTempRest"```
Not quite. you are missing the value_template. see my example here: https://community.home-assistant.io/t/bayrol-pool-manager/256262/9?u=tom_l
oh sorry, i thought i was just creating the rest sensor in order to test the value_template line
when i add the value_template: '{{ value["pm5"]["item"]["value"] }}' with or without the ["pm5"] it doenst work
i get "unknown" in the state of the sensor after a reboot
I'm in need of some guidance... I am trying to create a binary sensor for my OpenSprinkler set up that will tell HA if any of the zones are running. I have 6 entities that i have to account for and the docs just look confusing to me. any help would be appreciated...
Stick with your command line sensor then.
will do. thanks for the help today!
Oh crap. I see why, we should be using value_template: '{{ value_json["pm5"]["item"]["value"] }}' try it if you can be bothered.
trying 🙂
nope, still unknown with:
rest:
- resource: http://10.1.1.42/cgi-bin/webgui.fcgi?xmlitem=34.4033
scan_interval: 60
sensor:
- name: "PoolTemprest"
value_template: '{{ value_json["pm5"]["item"]["value"] }}'
What do you get if you just use: value_template: '{{ value_json }}'?
You might have to look in developer tools / states to see the whole value.
trying that now.
in the meantime, if it helps, i used a xml -> json converter online for the xml that the poolmanager outputs and get this:
{
"item": {
"@type": "34",
"@id": "4033",
"@label": "T1",
"@unit": "°C",
"@value": "28.0"
}
}
Yeah I did a few too. I remember that silly one that prefixes attributes with @
arg now having other issues, cant find the sensor. got to go anyway but will try and pick this up later, thanks again for your help!!
@hard pond posted a code wall, it is moved here --> https://paste.ubuntu.com/p/JyNc38Fvwq/
Nevermind, I just ended up adding 6 triggers to the automation...
Looking for a little help with a template here
I use an integration (twente mileu) which retruns 3 seperate sensors, all three sensors return a date (next garbage pickup date for that specific garbage type)
For a dashboard I would need a template / sensor which returns only the first upcoming date and garbage type of the three sensors
I was thinking a value template to check which date comes first and use the value of this sensor as the value for the template output, and a friendly_name_template which takes the name of the date that comes first, but to be honest I hardly know where to start
Anyone with a similar example or something to move forward?
Share an example of the state of one of the sensors
2021-08-20
{{ [states('sensor.sensor1'), states('sensor.sensor2')]|min }}
Ahhh
Oh that would just get the date
I would create a dict of the state and name
Then do that for the dict and index for the name
I have no idea how the dictionairy and index work :P
But, the idea from phnx works great, and I suspect I can figure the rest out from there =D
for fun:
{% set date1=states.input_text.test %}
{% set date2=states.input_text.test2 %}
{% set mapping={date1.state:date1.name, date2.state:date2.name} %}
{{ mapping[[date1.state, date2.state]|min] }}
Interesting, thanks, I'll try that!
afval_next_up:
value_template: >
{{ [states('sensor.non_recyclable_waste_pickup'), states('sensor.organic_waste_pickup'),states('sensor.plastic_waste_pickup')]|min }}
friendly_name_template: >
{% set pickup = states('sensor.afval_next_up') %}
{% if pickup == states('sensor.non_recyclable_waste_pickup') %}
Rest
{% elif pickup == states('sensor.organic_waste_pickup') %}
GFT
{% elif pickup == states('sensor.plastic_waste_pickup') %}
Verpakkingen
{% endif %}
It's not elegant, but it works :P
I don't recommend a self-referential template
but that's essentially what I had in my example, but with a bunch of if/elif instead of a dict
it's a shame that template sensors don't have a common variables section
Would help a bunch
Thanks for your help! I'm happy with my sensor! now to make a nice button card for it :)
Oh, min() accepts an attribute parameter
{{ '{}: {}'.format(sensor.name, sensor.state) }}```
"Template Designer Documentation — Jinja Documentation (3.0.x)" https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.min
@slim cliff
And @inner mesa too I guess
My entity state stays in 'unavailable' anyone can point me to what i am doing wrong ? ```template:
- binary_sensor:
- name: "shellymotion01 Brightness"
unique_id: shellymotion01_brightness
state: >
{% if is_state('sensor.shellymotion01_luminosity')|int > 1700 %}
bright
{% else %}
dark
{% endif %}
icon: >
{% if is_state('sensor.shellymotion01_luminosity')|int > 1700 %}
mdi:brightness-5
{% else %}
mdi:brightness-4
{% endif %}```
- name: "shellymotion01 Brightness"
sensor.shellymotion01_luminosity has a value of 1989 according to developer tools
Your templates are invalid. Try them in Dev Tools > Templates.
Oh i never noticed that template tab in dev-tools 😱 Thanks ! i thought the syntax was correct as VSC and 'check config' didnt complain
The config check in the UI is very basic and won't know if your templates work. It only looks for YAML syntax.
To check properly:
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
That should actually be a note in the UI itself ...
There's not space to describe everything in the UI... but if you feel it should be changed, you can suggest a feature request.
bright
{% else %}
dark
{% endif %}``` fixed it
I understand but, the green Configuration valid! in the UI sounds quite definite.
hi @fossil venture (and others) - im trying again with the rest function you helped me with yesterday.
with the following code:
rest:
- resource: http://10.1.1.42/cgi-bin/webgui.fcgi?xmlitem=34.4033
scan_interval: 60
sensor:
- name: "PoolTemprest"
value_template: '{{ value_json }}'
I get this from the states in dev tools when i call up the status of PoolTemprest:
{'pm5': {'item': {'@type': '34', '@id': '4033', '@label': 'T1', '@unit': '°C', '@value': '27.3'}}}
just need to filter out all the rest exept 27.3 🙂 any ideas? we are so close!
Huh. Well there you go. It does the silly @ thing too. Try value_template: '{{ value_json.pm5.item["@value"] }}'
it worked! well done!! thanks again! 🥳 🙏
Don't forget to add unit_of_measurement: "°C" to the rest sensor config or you won't be able to graph it correctly.
good catch! will do
is it possible to create a new line in the configuration.yaml file?
i am creating a combined sensor with multiple (6) states combined, making it difficult to eddit and work on:
value_template: '{{ "on" if (is_state("switch.status_light_on_annex", "on") and is_state("switch.status_light_on_covered_terrace", "on") and is_state("switch.status_light_on_covered_terrace", "on")) else "off" }}'
I would like to be able to have a line break between each item to make it easier to work with, is there a way?
@wintry garden posted a code wall, it is moved here --> https://paste.ubuntu.com/p/wnYXCGFXNR/
You could make a script that you call from the frontend which does this.
@open coral: https://yaml-multiline.info/
Hi! I'm having trouble making a simple service call with templates in my lovelace-ui file. Here is a simple representation of my dashboard: https://paste.ubuntu.com/p/fsBqX2HxpH/
Currently making service call in the UI logs "{{ states('input_select.broadlink_remote') }}" as a string instead of the state. I also tried without the outer " " and get the following error:
invalid key: "OrderedDict([("states('input_select.broadlink_remote')", None)])" in "/config/racelandDashboard.yaml", line 29, column 0
I was under the impression that I could use templates in the UI
thanks @charred dagger - helpful
(I already checked if the template is correct using the template tab in dev tools)
You can not.
got it, I'll find a workaround
@tepid apex posted a code wall, it is moved here --> https://paste.ubuntu.com/p/QZNV2Bhygf/
im trying to create a sensor to display the correct year/month/days that a person is old, but cannot get it to work. If this person did not have a birthday this year it will display for example -2
if the person had his birthday, the value is correct
how can i change this in a way to calculate the exact amount of months the person is old for this year?
state_attr("sensor.anniversary_verjaardag_caroline", "date") is for example '1990-09-27', this returns -2 now 🤣
that kind of date handling gets pretty dumb in a hurry. What is the intended purpose of this sensor?
the exact amount of months the person is old for this year
Full months? Partial months? Julian, Gregorian, lunar?
it's a crime that all months aren't exactly the same length
we need a metric calendar and time scale
I was just going to say that 🙂 But it would guarantee that the US wouldn't use it
eh, as long as all the computers use it i won't care
i already use day-month-year and 24h notation so meh
Lunar months are 
This is a little too advanced for me, I can't even found out where to put this :P
Is it a value_template?
i had an example directly below of a full template you could use
typed out on mobile even 😉
Sorry I might have quoted the wrong message than :P
I was actually talking about the code you posted
The {% set sensor .... code, this is a value template?
the whole thing is a template together
you can drop that as is into the
> template page, just swap out for your sensors
Sorry to ask, but,, how would I use it..
Something like the followign?
{% set sensor = [states.sensor.non_recyclable_waste_pickup, states.sensor.organic_waste_pickup, states.sensor.plastic_waste_pickup]|min(attribute='state') %}
{{ '{}: {}'.format(sensor.name, sensor.state) }} ```
Oh wow, That's way cleaner... I had no idea that was an option XD
Let me give this a go
i had a suspicion that it was possible but had to look it up
Getting an error after swapping out for my sensors, TypeError: 'attribute' is an invalid keyword argument for min()
that's odd
checking my sensors, but I think I swapped the correct values..
docs clearly state its possible
https://jinja.palletsprojects.com/en/latest/templates/#jinja-filters.min
but i just tested it and get the same error
Ahh that's reassuring :P
No not at all!
Thank you for helping me, thank you for teaching me things about this genius application!
| sort(attribute='block_total') | first should still work, right?
Update the first line to be this, Giblet:
{% set sensor = [states.sensor.non_recyclable_waste_pickup, states.sensor.organic_waste_pickup, states.sensor.plastic_waste_pickup] | sort(attribute='state') | first %}
That totally works!
Slightly more verbose, does the same thing.
The combined brainpower in here is staggering XD
phnx contributes way more toward that total than I do.
Most of what I know about the 'clever' stuff with templates, I've picked up from phnx and petro.
Still, the combined know-how and willingness to help is what makes this an awesome community
hello, is there a easy way to remove one month to a date? I think there was a recent update to that, but I can't find any reference to that
Rephrase?
a easy way do do now() - 1 month?!
That'd be a timedelta.
Plenty of examples in the chat history if you'd like to search for that term.
thats it... tks
Ah, the universal language of pseudo code 🙂
😆
I'd like to create a sensor that is the absolute value of another sensor. So templates seems to be the way to go about it.
But I can't figure out how to use mathemtical operator with template.
There's abs() mentioned here: https://jinja.palletsprojects.com/en/latest/templates/#jinja-filters.abs but do I have to use jinja-filters.abs(x, /)¶ ?
so something like:
value_template: "{{ state('sensor.iotawatt_input_solar2_wh')|abs }}" ?
Not quite. States are strings, so you need to convert it to a float first
value_template: "{{ state('sensor.iotawatt_input_solar2_wh')|float|abs }}"
ah
I don't even know if that will fix the issue I'm seeing with the energy bit, I get no data showing for my solar. My only guess is that I'm reading an negative value
I think that was an issue, but #energy-archived could say for sure
it's showing as "unavailable" in the developer tools
sensors:
solar1_wh:
friendly_name: "Solar11"
unit_of_measurement: Wh
device_class: energy
value_template: "{{ state('sensor.iotawatt_input_solar1_wh')|float|abs }}"
states
in the developer tools, sensor.iotawatt_input_solar1_wh is :
Not state
Where?
in "Developer Tools"
Yes, but where?
Ok, that’s unrelated to templates
That’s just a table. The data structure is called states
that it's plural is a bit confusing 🙂
I’ve felt that way as well
Consider that it’s a data structure of all states and you’re grabbing one out of it
I posted a link in #energy-archived
hmm, my sensor while showing in the "developer tools" with what I'm hoping is the right unit and type, isn't showing in energy
so the full months that passed since the birth date
That should be pretty easy then. Work out full years first (difference between the two, rounded down, multiplied by 12), then work out the remaining full months (similar logic, no multiplying).
#energy-archived can help
well hello there everyone 😄 i'm trying to setup a template that add's together the 3 current hour estimated solar production to make one value and its throwing a "Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 73, column 13" and a "expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 75, column 34"
here's my code, any help would be greatly appreciated 🙂 thank you!
sensor:
- platform: template
sensors:
estimated_total_hourly_energy:
friendly_name: "total estimated hourly energy" #(line:73)
value_template: "{{ (states('sensor.energy_current_hour')|float + states('sensor.energy_current_hour_2')|float + states('sensor.energy_current_hour_3')|float) }}
unit_of_measurment: "kWh"
could you please format it properly?
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://paste.ubuntu.com/.
offhand, it looks like you're missing a closing "
- platform: template
sensors:
estimated_total_hourly_energy:
friendly_name: "total estimated hourly energy"
value_template: "{{ (states('sensor.energy_current_hour')|float + states('sensor.energy_current_hour_2')|float + states('sensor.energy_current_hour_3')|float) }}"
unit_of_measurement: "kWh"
first, 2 spaces per indentation level
quote added. good catch, changed error to
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 1, column 1
expected <block end>, but found '<block mapping start>'
in "/config/configuration.yaml", line 77, column 2
second, the outer set of parens are unnecessary in the template
the {{'s?
the one around the states? gotcha
I suspect that the problem is indentation
you're just inconsistent across the definition
well. that's how all my other things on config are indented.... why's it only messing up on this one?
infact i went to change the other's to only two spaces and it broke those uhh.. integrations
i am, 3 spaces for each "tab" notepad++ is nice like that
looks like 4 to me
well its 3, one before the - the - and one after the - for example
#icantcount nvm your right
its still consistent across the board
I don't see anything else wrong with it other than the indentation, and indentation is important and meaningful in YAML
i've noticed lol.
not sure what to tell you, then
so when i do binary_sensor: - platform for example should the - line up under the binary_sensor ?
it's a list under binary_sensor:, so...
binary_sensor:
- platform: template
sensors:
foo:
value_template: "{{ xxx }}"
i ask because right now they're all bumped in two spaces. has the - and then another space. as you just exampled to me, so sensors: in that case is also 4 spaced in, correct?
it's all relative to the parts around it
in any case, I just added what you posted above. fixed the spacing, and it checks fine for me
- platform: template
sensors:
estimated_total_hourly_energy:
friendly_name: "total estimated hourly energy"
value_template: "{{ (states('sensor.energy_current_hour')|float + states('sensor.energy_current_hour_2')|float + states('sensor.energy_current_hour_3')|float) }}"
unit_of_measurement: "kWh"
i adjusted to
- platform: template
sensors:
estimated_total_hourly_energy:
friendly_name: "total estimated hourly energy"
value_template: "{{ states('sensor.energy_current_hour')|float + states('sensor.energy_current_hour_2')|float + states('sensor.energy_current_hour_3')|float }}
unit_of_measurment: "kWh"
with no luck, i'll copy your code in and hope it fixes it
oh dang it, i prolly ctrl+z'd too far and didn't check. good eyes
well i copied your code in and it works fine now 😄 thanks for your help and expanding my understanding of this powerful platform! 😄
value_template: "{{ [states('sensor.energy_current_hour'), states('sensor.energy_current_hour_2'), states('sensor.energy_current_hour_3')]|map('float')|sum }}"
Hey!
I am pretty new to templating, but i have manage to do some stuff. Now i am stuck.. I am trying to translate this to swedish, since it shows if my cat is inside/outside, and since when. The code takes status from another sensor, and then translate it's to "Inside sedan 18:02" etc.. "Sedan" means "Since", the thing is i can't manage to make it from "Inside/Outside" to instead show "Hemma" or "Ute" Witch is the translate i wan't. I can't really understand how i knows to translate "where" to inside, since "where" from the sensor is 1 or 0, depending on my cats status. Hope someone can help, thanks!
Something like {{ 'Hemma' if is_state_attr('binary_sensor.pet_doris_2', 'where', 'inside') else 'Ute' }} should do it
cat_tracker:
Wow, that worked like a charm. Hat off to you man, thank's so much!
What is cat_tracker? I use surepetcare integration
Anyone have any suggestions where I should list a webpage that generates template elements? I made a template-generator to track profit and loss on crypto purchases. Just saving myself some coding hassle, but I think it would be useful to others who are speculating in crypto and tracking via HA.
You could share it on the forums, then it's easy to search for.
@keen cloak posted a code wall, it is moved here --> https://paste.ubuntu.com/p/fbHGBK7tsr/
@keen cloak What are you asking?
@wheat cargo posted a code wall, it is moved here --> https://paste.ubuntu.com/p/hj39T55QKT/
You have to add device_class: as a customization
It doesn’t get automatically assigned. Integration just performs a mathematical integration on the data coming from a sensor. It doesn’t assume it’s a power device_class.
That was solved in #energy-archived. integration will set device_class to energy if it's fed a sensor with device_class power. But only after at least two state updates as it turns out. See https://github.com/home-assistant/core/pull/54802
But avoid double posting, @wheat cargo.
sorry, I posted it here and then thought #energy-archived would be a better place
thanks for the commit fixing it
No worries... and I guess you can't delete a message after the bot has had it's way with it...
Ah good to know, must be a newer addition
Definitely
Hey.. again! Well, it seems like it worked but when she left in the morning i realised it only changed the time, and it still said "Ute" and not "Hemma", since "where" isn't "Inside", it's 1 and 2, depending on where she is, i changed that, but it still won't work.. any ideas?
have to share what you chagned
Hey, I have an LED strip controller where 50% brightness is actually 100%, and setting anything higher than 50 overheats/bricks the device. Does anyone know of a way to limit or rescale the dimmer so that 100% on the bar sends 50% to the controller? Most important thing to me is that it should not be able to be set higher than 50
Is thera a device_entities() equivalent for area's? I want to somehow get the entities associated to an area.
See this conversation: #templates-archived message
Thanks.. I've been informed by Frenck in the Dutch HA discord that template support for areas is in the pipeline
@broken urchin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/BzxW4Mt4Qt/
Hey, could anyone with knowledge of „Create sensor with attribute of entity using templates“ look at this? I really dont know what else I could try to get this sensor working…
Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).
Please take the time now to review all of the rules and references in #rules.
(sorry for the codewall ._.)
What is wrong?
I do note this, which can’t have a space in it:
aussentemperatur city:
And there's sensor: three times.
You’ve only said ‘none of them seem to work’
That too
But there are several different formats there, so no sure what’s going on
Good points. I cleaned everything up, used the structure of the official home assistant wiki site.
Still, If I search the entity (newly created sensor) in the developer tools sektion of HA, it wont show up
*section
After restarting HA? All that would go in configuration.yaml, BTW
Not sure if this is the right channel for this. I have a group, group.people, which includes some person entities. I also made a template sensor which counts the number of people at home:
template:
- sensor:
- name: Number of people at home
unique_id: 'number_of_home_people'
state: "{{ states | selectattr('entity_id', 'in',
state_attr('group.people','entity_id')) |
selectattr('state','eq','home') | list | count }}"
There is a delay of about a minute between a person being detected as away, and the sensor updating to reflect this new reality. Why is that? Also, if there is a way to improve this template sensor, would love to hear it. I feel like there should be a way to start at expand('group.people') but I couldn't figure it out.
If HA doesn’t know what entity state changes to track, it updates every minute
You can add a state trigger to your template sensor listing the entities it should monitor
Right—I imagine that would only update when the group overall is home/away
Why don't you just expand the group?
{{ expand('group.people') | selectattr('state','eq','home') | list | count }}
I was thinking that, but I think you can just use the same state template in the trugger
Any time the group changes, the template will be re-evaluated.
Yes. I had a look into the logs:
Logger: homeassistant.config
Source: config.py:437
First occurred: 18:07:12 (1 occurrences)
Last logged: 18:07:12
Invalid config for [template]: required key not provided @ data['trigger']. Got None. (See /config/configuration.yaml, line 30).
I dont understand why I need a trigger, according to this info state-based template sensors are formatted like I did
( https://www.home-assistant.io/integrations/template/#state-based-template-sensors )
Which line is line 30 of your configuration.yaml?
I think mono's solution is correct!
It simplifies the expression, and the template dev tool tells me it will monitor for the group as well as each entity in the group
Thanks, @ivory delta
Your approach would make more sense if you were looking for something dynamically... but then you could still use select or selectattr filters.
Line 30:
template:
- sensor:
- name: „Temperature….
That's 3 lines. Which is line 30?
template:
Great. Now stop pinging me.
When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
Where did you put that?
It sounds like you have something nested where it shouldn't be.
sorry mono
It goes in configuration.yaml, not in sensor.yaml
I already moved the code to the configuration.yaml file
.share the whole file, hide any secrets
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
if I paste exactly your definition into my configuration.yaml, it checks fine
When I „check configuration“ do, everything is fine too. But when rebooting I still get the error :
„Invalid config for [template]: required key not provided @ data['trigger']. Got None. (See /config/configuration.yaml, line 30).“
Here the stuff thats above the code in my configuration.yaml file:
https://paste.ubuntu.com/p/by4Q7S63Bp/
what version of HA are you using?
something from a stone tablet?
please don't say something like 2021.2
Version core-2021.4.6
Installationstyp Home Assistant Container
Entwicklung false
Supervisor false
Docker true
Virtuelle Umgebung false
Python-Version 3.8.7
Betriebssystemfamilie Linux
Betriebssystem-Version 5.10.17-v7+
CPU-Architektur armv7l
keep updating
you're 4 releases behidn
I suspect that's before the new template sensor format was supported
it's August, and that's from April
ok.. will try it. Started backup process..
hey yall, I'm trying to wrap my head around templates and for some reason this feels like PhD level math to me right now....
my goal is to use a sensor on my mailbox to create a virtual switch where the state of the switch corresponds to if we've gotten mail
What information does the sensor give you?
open / closed
so do I want something like value_template: "{{ is_state('switch.source', 'open') }}" ?
How do you plan to know if you've had mail and if you've checked the mail?
Then you really need to latch that with an input_boolean
I think I can do that with the automation. EG first open of the date, set the virtual switch to on. If switch is on, and opened again, set it to off. Regardless of state, set to off at midnight every night
(funny enough we literally just got mail 10 seconds ago and I got the notification 😂😂)
So you don't need a 'virtual switch'. Just use the automation.
Right, if all you care about is the moment when the door is opened
what if I want to be able to use the state of 'mail' in other places?
Use the boolean 🤷♂️
not to sound dense... but what do you mean? I understand what a boolean is generally, but not in HA.
Maybe that's what you meant by a virtual switch. It's a helper that tracks a boolean state.
🤯
A word of warning with your suggested approach...
If switch is on, and opened again, set it to off.
If you get two mail drops in one day, you'll think you've had none.
If you have no reliable way to know you've checked the mail, maybe stick with clearing the boolean at midnight.
@ivory delta yeah, it's imperfect. If I were to also go check it manually before mail has arrived, it'd think I have mail
No need to check before it arrives if you know when it's been opened by someone else 😉
I mean... I could also do image recognition of our mailman with our doorbell camera 🙂
Maybe you’ll find that it’s a trained bear
where I live, that actually happens 😂😂
I have a similar setup but with two sensors. Input boolean gets turned on when someone rings the doorbell. Input boolean gets turned off when I open the door. If it's on, that means someone has rung the bell and the door hasn't yet been answered.
I have flashy lights and stuff that continue for as long as the boolean is on. It's my 'go answer the door, you lazy swine' notifier.
measuring the delta between ring and open would give me so much social anxiety for the person waiting 😅
So don't measure it 😉
If it’s important, they’ll ring again
For me, it's so I know if my wife beat me to the door. If she's closer and answers it first, the light stops flashing.
thanks yall, this info on the booleans is super helpful and, in reading the documentation, obvious
@ivory delta I'm just joking, I see the utility in it for sure
I'm not sure if this is the right place, or if #integrations-archived would be more appropriate, but.....
I use a lot of custom: button-cards and would like to change the properties of them (name, color, etc) based on values/states of OTHER sensors/entities. Unlike templates in HomeAssistant, they use Javascript formatting and I'm struggling to learn it. Can anyone point me to a good resource where I can try and gain some knowledge about the commands/syntax required? Thanks!!
You'd want to ask in #frontend-archived about frontend stuff (including JavaScript 'templates')
Got it- Thanks!! 😃
When using default to guard against a variable not always being defined like this {{ my_variable | default }} what does it actually default to?
is there a minimum time until a sensor define via a template makes it to the list?
If you don't provide a default value, an empty string. You may want to specify an actual default:
| default('foo')
Nope. As soon as you restart/reload, as long as you haven't done it wrong.
Yeah I had a play in the template editor and ended up with {{ value_json.wifi_sta.connected|default(false) == true }}
i do not think i did it wrong since I see some of them
the ones with unit of measure %
but the ones without or kg or other
do not appear
here is the full
as a note I see them in the normal graph so the entities exist
So I got one question! I've been using a lot of time on templates and trying to figure out why my template is not working still I got a True result in developer tools. What I actual found out, I think that actual there is a difference between "True" and "true". Can someone explain this to me? Is it a string and a boolean, if so I think it should be handled as the same.
Here are two examples when using wait_template,
This will allow the automation to go on,
{% if states('light.dimmer_stue') == 'on' %} true {% else %} false {%endif%}
Neither one of there are working. Result for both of these are True
{{ states('light.dimmer_stue') == 'on' }}
{{ is_state('light.dimmer_stue', 'on') }}
true is a boolean True is a string. Home Assistant is case sensitive, as it is built with Python, which is case sensitive.
For what you want to do. Just do this: {{ is_state('light.dimmer_stue', 'on') }}
This will return true/false
However Lovelace and other parts of the frontend (like the template editor) will display the state as True/False.
Confusing but pretty.
will states('') also do the same? Also, I cant trust the template editor as it will state True/False, even if its true? I need to recheck my script
Actually I got that wrong. The template editor will display true/false. It's only Lovelace that capitalises the states.
ah, okey, thanks will try again
I've got some hard drive stats being reported on MQTT, but I'm having a hard time setting up the value template because the payload contains objects named "C:", "D:" etc so can't figure out how to escape or deal with the colon, e.g. value_json."C:".use value_json.C:.use etc all give yaml errors.
I have a question! I have a scenario where a user can do without a couple of cards, to remove complexity from a common view. Can we check against a currently logged-in user? Is there such thing as a "user template"?
I'm changing a bunch of things in an older configuration section that contains template sensors in the old format, and guess would want to update that. See for instance in this example in the docs, each sensor has some sort of ID (e.g. solar_angle and sunrise), are these the unique IDs in the new format?
Sorta, but not really
I’m the old config, those made up the object_id. Now the unique_id or name derives the object_id
Solved. Updating fixed it. Thanks for your time and help. 🙂
Hi, can anyone help to show two labels below each other in a custom button card. I have the template below but if i add another state it show behind the first state...
[[[
if (states['media_player.telenettvbox'].state == "off") return 'Uitgeschakeld';
else return states['media_player.telenettvbox'].attributes.media_title;
]]]```
Add a line break. Share your attempt at having multiple lines.
After allot of attempts i now have a two custom button cards below each other using a stack in card but it's partly working with to many space between the names and the card itself is a mess. 🙂
Tinkerer, any change to explain how i can add a line break. 🙂
You could try this: https://www.google.com/search?q=html+line+break
If that doesn't work, \n is the new line character.
Found it using "<br>".
@fresh tree posted a code wall, it is moved here --> https://paste.ubuntu.com/p/5nSW2XBNzg/
I'm getting the following error in log:
2021-08-21 19:22:12 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'person' is undefined when rendering '{{ is_state(person.michael, 'home') }}'
You're missing the quotes.
ahh 🙂
Stupid question I can't find the ansswer to: How do you get the length of an array? I've got a rest sensor pulling in some JS. I simply want the length of an array.
Just asked the question in #automations-archived but i'm looking for a way to determin what user triggered the switch so that I can decide which speaker should turn on. When my wife stars playing music her spotify account should be used. When I hit the same button in the interface my spotify account should be used. I was told this can be done with templates but I don't see how this should be done in a script. Any hints on were to start?\
|length 🙂
Bless you!
Got it working 😉
Question: I have a iotawatt that is being read every 30s, I retrieve the cumulative value of the amount of energy produced by my solar panels. The value returned is negative. I have a template that will calculated the absolute value as the energy screen requires a positive value.
This is done using a template:
friendly_name: "Solar Total Energy Output"
unit_of_measurement: Wh
device_class: energy
value_template: "{{ states('sensor.iotawatt_output_total_solar_wh')|float|abs }}"
attribute_templates:
last_reset: "{{ state_attr('sensor.iotawatt_output_total_solar_wh', 'last_reset') }}"
state_class: "{{ state_attr('sensor.iotawatt_output_total_solar_wh', 'state_class') }}"
the problem is that when I restart HA, where the original sensor just has no value (the graph of the history will show a gap)
the problem is that during that time, that template sensor will be set to a value of 0.
This totally mess up the energy screen or the energy_meter which if the reset happened at midnight, will see say a value of 3.5MWh , followed by 0, and then again 3.5MWh . So my daily meter now has a value of 7MWh
how can I define the template so that it doesn't return 0 during the time the entity sensor.iotawatt_output_total_solar_wh has no value?
Use an availability template.
availability_template: "{{ states('sensor.iotawatt_output_total_solar_wh') not in ['unavailable', 'unknown', 'none' ] }}"
can this use in combination with a normal template?
What is a "normal template"? Just add it as an extra option to your template sensor.
That's the one.
@autumn matrix posted a code wall, it is moved here --> https://paste.ubuntu.com/p/99XDGmrN8J/
Could someone help me out with this. I wanna trigger an action based on who pushes a button in the home automation interface
{{ (expand(states.person) | selectattr('attributes.user_id', 'eq',
trigger.to_state.context.user_id) | first).name == 'Ronald' }}
However, this does not seem to work and i'm struggling to find the attributes to use
Is there a way to convert color_name to RGB values in a template? There is a homeassistant.util.color.color_name_to_rgb function that does what I want.
You don't have access to that within templates. You could look at the code for that and try to reproduce it though.
@ivory delta is that in response to @valid hatch or to me?
Nice, double tagging...
I answered the most recent question. If I want to reply to an earlier one, I'll use the reply function to make it obvious
There was a similar question answered recently. I don't remember if it was in here or in #automations-archived, but the search function should find it.
Yesterday I asked it myself but replied with it that I found the solution. However when I tried to use the solution it didnt work so finding the answer continues
Ok. What doesn't work?
Well I thought this would work in a script because it gave True when using it in the template developertools
{{ ((expand(states.person) | selectattr('attributes.user_id') | first).name) == 'Ronald' }}
However when I log in with another user it also returns true as a boolean
What do you mean when you log in? What's the trigger?
The trigger is a button in the interface/app.
In this particular case; when my wife clicks the button it should use her spotify account, when I clicks the same button in the interface it should select my spotify account. For this I need to determin the user that clicks the button
Use a sharing tool for long posts. Don't edit extra in to fool the bot.
You'd have to debug the automation to see what details you get in the trigger object.
If you look at just the output of {{ expand(states.person) }} it shows state objects for all persons on your home assistant instance. My guess is that your account shows up first, so when you | first you're always selecting the first object. I suspect they're displayed in creation order.
No... the first follows a filter.
Oh, yes...
But that's a mistake in their second paste. Original is okay.
I don't see anything in that conditional that's comparing against "user who triggered this".
Yeah I suspect the same indeed. Trying to understand trace function but this doesnt give me the information I need
wow..how the hell did I miss that? sigh
Yes tried that one as well but in the template tester I got UndefinedError: 'trigger' is undefined
Yes, because you're outside of an automation...
won't work there.
They have the button. The issue is knowing what's in the trigger.
Take this over to #automations-archived, TiggerTime.
So I should ask what information is in the trigger of a button?
There is no "button" trigger. Here are the variables available for each trigger platform: https://www.home-assistant.io/docs/automation/templating/#trigger-state-object
Already dealing with this in #automations-archived 🙂
is there a guide explaining the {{ }} and {% %} syntax?
{{ }} prints a result, {% %} evaluates statements, see: https://jinja.palletsprojects.com/en/latest/templates/
Afternoon all , first time here i need to sum up some sensors
well derive some from existing sensors
i can create mysensor and set the state with '{{ states('sensor.existing') | float }}'
where i fail is with '{{ ( states('sensor.existing') | float / states('sensor.sensor2' | float )}}' it should give a numerical value but i get '0.0'
What are the values of the two sensors?
also i have around 12 energy monitoring plugs and i need to add each watts together to get a total is there a straightforward way to do this they are named energy01 to energy12
well typically something like 320 and 0.95
Not typically. What is it now when you say your other template gives 0?
Also... you have a mistake in the second half. Look closely and compare it with the first half.
well 267 and 9.725 and the result is 0.0 everytime
You are missing a closing brackett hetre: states('sensor.sensor2' | float
maybe I should start at the beginning 🙂
I have a current cost meter which delivers a watts value every 6 seconds via a serial port this works in the new energy tab as is but its wrong
first issue is that really its not watts its VA and the Vis assumed to be 240 where the nominal V is 230V but it drifts due to grid load
so my first attempt is VA * (gridactual volts / 240)
I have a smartplug on a lightly loaded ring near the breaker box which gives me a reasonable reference voltage.
So thats the first correction the next one is that va and watts are not the samething unless the load is resistive. so for example i might be drawing 75 watts with a VA of 125
However my unmeasured loads e.g shower , cooker immersion heater are primarily resistive and the powerfactor is close to one.
so what i want to do is correct for my knownloads and leave the unknown loads with a power factor of 1
It won't be quite right as i cant really get a read of the led lights but since there are 10 at 90 watts total its not a problem if they actually register a bit high.
So what are you actually asking for help with?
ok part one correcting the VA measured with assumed 240V to a VA with the realtime voltage
i've created a sensor which takes real volts and divides by 240 giving around 0.93 to 0.97 that works but when i create a sensor using VA x (my power factor) it results in 0.0
i know that state is recorded as a string but i thought | float would cast it to a float
actually using / in the first place was a lucky error as the templating tool says i'm trying to divide by zero
Your logic isn't wrong. Your template is.
so that means i must be getting a float that equates to zero
No. It means your template is wrong.
Read your template.
Good:
states('sensor.existing') | float
Bad:
states('sensor.sensor2' | float
ok can i paste a few lines
yes i missed a closing ) but even with it corrected it still gets a result of '0.0'
And this? #templates-archived message
the adding of sensor values ?
which is where i'm messed up since thats what it gives as a result
Go to the Dev Tools, experiment until it gives a value,.
You said you fixed the parentheses, so this will work:
{{ ( states('sensor.existing') | float / states('sensor.sensor2') | float ) }}
i have '{{ ( states('sensor.vawatts') | float * states('sensor.mypf') | float )}}' and it results in '0.0'
hmm {{ states('sensor.vawatts') }} = 292
{{ states('sensor.mypf') }} = '0.971'
{{ states('sensor.mypf') | float }} = 0.0
Yeah, no...
{{ '0.971' | float }} gives... 0.971
What you're describing makes no sense.
yes but seems to be the case in practice your string converted fine
i don't know why the string held in states('sensor.mypf') isn't converting but thats what is happening
ok i think mypf sensor is bogus
i replaced it with a helper numeric object and it works
so maybe i need to give it an entityid
sensor.mypf is an entity ID.
ok so its not that
my definition is
- sensor:
name: "mypf"
unit_of_measurement: 'W'
state_class: measurement
device_class: power
state: >
'{{ (states("sensor.energy03_energy_voltage") | float / 240.0) | round(3) }}'
I'm working on a sensor template for a zooz_multirelay(which defaults to the type outlet). I'm using an input to read a reed switch for my garage door. I'd like to change the color if the door is open in the lovelace dashboard.
is there a template item for icon color?
no
the docs show what's available
you'd need to use card_mod or a card that explicitly allows you specify the color, like custom button card
well that's annoying, seems like the most basic thing, but I'm guessing that topic has been overly beaten.
HA is an open source project. You're welcome to add that functionality.
It has been discussed often, and there are a number of options to do it. I mentioned two
some cards support state_color, which is a boolean that indicates whether the color should change depending on whether an entity is on or off. that color can be selected via a theme variable. https://www.home-assistant.io/lovelace/entities/#state_color
but i prefer to use something like custom button card, which is very flexible at changing color, icon, etc.
devs will never allow that. Source: They haven't in the past.
Thanks for the assistance, finally stomped my bugs 🙂
Hey, trying to get some data out of makers api (hubitat) but cant get the template or rest working
this is what the api responds with: [{"capabilities":["Refresh","EnergyMeter",{"attributes":[{"name":"energy","currentValue":"6.49","dataType":"NUMBER","values":null}]},"ReleasableButton",{"attributes":[{"name":"released","currentValue":null,"dataType":"NUMBER","values":null}]},"Switch",{"attributes":[{"name":"switch","currentValue":"off","dataType":"ENUM","values":["on","off"]}]},"PushableButton",{"attributes":[{"name":"numberOfButtons","currentValue":"3","dataType":"NUMBER","values":null},{"name":"pushed","currentValue":"1","dataType":"NUMBER","values":null}]},"HealthCheck",{"attributes":[{"name":"checkInterval","currentValue":"3720","dataType":"NUMBER","values":null}]},"Configuration","Actuator","PowerMeter",{"attributes":[{"name":"power","currentValue":"0","dataType":"NUMBER","values":null}]},"HoldableButton",{"attributes":[{"name":"held","currentValue":null,"dataType":"NUMBER","values":null}]},"SwitchLevel",{"attributes":[{"name":"level","currentValue":"99","dataType":"NUMBER","values":null}]},"Sensor","DoubleTapableButton",{"attributes":[{"name":"doubleTapped","currentValue":null,"dataType":"NUMBER","values":null}]}]}]
and i want this part as a energy template: {"name":"energy","currentValue":"6.49"
any suggestions?
There are lots of bits that look like that. Which one?
First line: [{"capabilities":["Refresh","EnergyMeter",{"attributes":[{"name":"energy","currentValue":"6.49"
Tried with a rest but cant get it to display
value_template: "{{value_json.attributes}}"
json_attributes:
- currentValue
but i might be off?
Yeah, a little 😂
It'll be something like... value_json[0].capabilities[2].attributes[0] to get to the object you want.
That's nasty... arrays could change order, so it'll break if it does.
hey all, I am trying to work out the best way to show on a little graph card or something the real time energy being consumed on some devices. I have power monitoring smart plugs on these devices and some template and statistic sensors which I will post below. The statistic sensor works, but the template sensor of realtime_power returns a state of unknown. Any ideas what I have done wrong here?
- platform: statistics
name: power_per_minute
entity_id: sensor.kitchen_fridge_smartplug_energy_total
sampling_size: 60 # This is assuming you are getting 1 sample a second. Adjust otherwise.
- platform: template
sensors:
realtime_power:
friendly_name: Realtime Power
value_template: "{{ state_attr('sensor.kitchen_fridge_smartplug_energy_total', 'total') / (1000 * 60) }}"
you're using the wrong entity_id in the realtime power
oh crap, what should be there?
You screwing with me?
Look at what entity is getting created from your statistics configuration…
Hi Guys, I am trying to show a sensor's negative value only but as positive. Does anyone know how i can do this?
- name: "Battery Discharge"
unit_of_measurement: "W"
device_class: energy
state: >
{% set batter_cons = states('sensor.battery_watts') | int %}
{% if batter_cons < 0 %}
{{ -batter_cons | int }}
{% else %}
0
{% endif %}
use | abs to return the absolute value or multiply with -1
{{ batter_cons | abs }} or {{ batter_cons * -1 }}
as you already defined batter_cons as an integer, there is no need to use the int filter again in your template
use one of the two suggestions instead of {{ -batter_cons | int }}
Let me see if i can figure it out
Very noob with templates still new for me
Woohoo
That seems to work.. Thanks
Sorry had just woken from an evening nap after putting my son to sleep… now that you’ve said it, it’s very obvious
Anyone know how i can use this in a custom: button-card?
{% for light in state_attr('light.all_lights', 'entity_id') if is_state(light, 'on') %}
{% set ns.res = ns.res + 1 %}
{%endfor%}
{{ ns.res }}```
You could make a template sensor from that Jinja code and reference it
It looks overly complicated
or maybe you have to do it that way for a light.group
I want to count the lights that are on and use it as a label in a custom: button card.
yes, I understand. I was thinking that something like {{ expand('light.all_lights')|selectattr('state', '==', 'on')|list|count }} would do it, but I don't know if that would work for a light.group
in any case, the answer to your question is to create a template sensor with whatever template you want and then just refer to to it in your custom button card definition
Seems that your template works fine, now figuring out how to add that to a custom: button-card...
ok, I've said twice to put it in a template sensor
Yes going to do that, thanks Rob.
ok, just checking 🙂
I'm tryting to make a working value_template for a rest sensor
Config: https://www.hastebin.com/pevegohevu.yaml
That request gives me this data: https://codebeautify.org/jsonviewer/cb52ffad
What i'm trying to do is getting the points, points_this_week and time_this_week for the students. Right now i get error messages like this:
homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.irene_duolingo_xp_stats. State max length is 255 characters.
Not really sure what i'm doing. Just some copy paste configuration 🙂
The state is limited to 255 characters. You're able to store more in attributes, so just move your data around a bit, vacum.
but the data i want is just a couple of bytes
That's not what the error message says. The value of your template is resolving to something longer than 255 chars or it wouldn't complain.
Stick your JSON into Dev Tools > Templates and then use your template to see which parts it grabs.
i have tried to make a sensor like this:
sensor:
- name: "Irene Duolingo XP points"
value_template: "{{ value_json.students.0.xp.points[0] }}"
but i get this as a result
oh. it looks like i can't attach an image here
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.
But text is better 😉
Test it in Dev Tools > Templates.
the old template did to much 🙂
{{ value_json.students[0].xp.points }}
i will try that @mighty ledge
@ivory delta How do i add all the data to test?
ah. i see it now at the demo template
It looks like {{ my_test_json.students[1].xp.points }} worked
0 works too for the other student
But it doesn't work in the config
the only difference is value_json in the config instead of my_test_json in the tempalate dev tool
Be more specific please
You said it doesn't work. That could mean anything.
no log file errors
the state is unknown
Template dev tools: https://imgur.com/a/xCA4eHd
Config: https://www.hastebin.com/isijuluqeb.yaml
States dev tools with state unknown: https://imgur.com/a/LnWqy7U
Wondering how to build my own entity from my media player(s) to reflect a log of the content played. I see the attributes I want to use and can access via template with state_attr('media_palyer.chromecast', 'media_title') and similar properties but how do I build a custom sensor with each of these for use in a lovelace logbook card? Any suggestions?
Thinking this may have been done by folks getting parental controls or similar visibility into media
a normal template sensor can do that
@dreamy sinew is there any trick to only logging state changes when new content is played? i.e. next song, or next episode is played and no logged state for when the player is not in use?
probably not. it'll update to whatever that attribute value is
ok maybe the logbook card can be customized to ignore certain sensor states... I'll toy around with this
Can someone help me with this, im kinda stuck, i want to make a binary sensor out of an attribute. With the template function in Dev. Tools i came up with this;
binary_sensor:
- platform: template
sensors:
toon_current_temperature:
friendly_name: "toon current temperature"
device_class: sensors
value_template: >-
{{ state_attr('climate.thermostat', 'current_temperature')}}
binary sensors are on/off only
And your indentation looks incorrect
how would one go about, making a sensor out of an attribute?
Like phnx and RobC pointed out, mind the type, sensornot binary_sensor and the indentation.
Probably something like this.
sensor:
- platform: template
sensors:
toon_current_temperature:
friendly_name: "toon current temperature"
value_template: >-
{{ state_attr('climate.thermostat', 'current_temperature')}}
hmm
i was going to come back with this;
- platform: template
sensors:
thermostat_current_temperature:
friendly_name: "Current Temperature"
unit_of_measurement: '°C'
value_template: "{{ state_attr('climate.thermostat', 'current_temperature') }}"
which seems workable (sorry for not using code format), but it doesnt show up
ill try yours @waxen rune
please format code:
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://paste.ubuntu.com/.
if you were still under the binary_sensor key it would still be wrong
got everything working, thanks for your input guys!
There must be something basic that I miss in my config. With my untrained eyes everything looks OK
Config: https://www.hastebin.com/isijuluqeb.yaml
States dev tools with state unknown: https://imgur.com/a/LnWqy7U Template dev tools: https://imgur.com/a/xCA4eHd
And there are no errors in the log related to what I try to do
how do you know that that's what you're getting back from the REST call?
Curl
But it’s a good question. Is it positive to verify the response somehow? It is a quite large response and I guess it is to be stored as a state
If I take that config and add -H for each header line and add \ for line breaks curl get that data
you could set it as an attribute
Oh. How?
