#templates-archived
1 messages ยท Page 5 of 1
oof
makes automations less useful then
convert it to json. but i'd switch to yaml
Worked (from trace)
set_color_temp:
Day: 222
Night: 370
8pm: 370
After9pm: 370
color_temp_condition: 7
color_temp: 222
color_temp_condition1: 7
I never use the GUI, but I guess it's done to avoid issues with states like on and off and when adding templates
but it makes it difficult to check for true and false on attributes, or to add json
I'd assume they just treat it as a 1 dimensional object for easy UI parsing
and by it I mean all variables
Just makes it easier since I'm on mobile doing this 99% of the time when I have a second to just create automations through the UI. If I wasn't using yaml would be fine.
something like this is only possible in the GUI when changing it in the raw yaml editor
condition: state
entity_id: light.foo
attribute: is_deconz_group
state: true
why are you always on mobile? That slows down the automation process x10
I do most of this early in the morning when I get up. Would rather not go sit in front of a computer at 5am lol. It definitely does slow it down. When I have a big issue such as a formatting issue or need to make major changes/testing I do use a desktop to speed this up. I should probably get a cheapo one too lol
I have a cheapo laptop
I wonder if the UI will ever get to a point where it doesn't mess with yaml?
nope, it never will
there's too much variability in yaml, it would be a mess
the UI would have to handle anchors, sort order, object typing, sort order of the objects. And that's just what comes to mind off the top of my head
Interesting. Didn't know all of that.
isn't it converted to json before ending up in automations.yaml?
it's returned as a dictionary, yaml accepts json
yeah, but I though when saving an automation in GUI, it's converted to json, and then back to yaml for automations.yaml
dictionaries are not sorted, object typing would need to be handled by the UI
it may be, I don't have that memorized. Still doesn't change what would need to be handled by the UI
the limitation is not yaml, it's the UI
it's the UI's ability to mimic yaml or json.
I just assume they tried to make the basics as user friendly as possible. So they automatically add quotes everywhere, becuase that is correct in most cases (eg to: "off" in a state trigger, or for a single line template).
But for the exceptions, so when you add json instead of a template, or when you actually want to check on a boolean value, it makes it more difficult
na, I think it was a "hey, everything's a string and it should work" kind of deal
extended typing and guessing what the user intentions are, is pretty difficult.
and it leads to unintended bugs
Hey everybody, I have a whitespace question.
I have a template sensor with a value_template that uses the indent() filter. This works correctly in Developer Tools, but when I check the state it appears the indentation is removed.
**{{ y.name }}** {{ y.last_changed | as_local | relative_time | indent(25 - y.name|length, true)}} ago
post all the jinja.
friendly_name: Alarm Trigger Last 10 Minutes Relative
value_template: >
{% set x = expand('binary_sensor.total_alarm')
| sort(reverse=true, attribute='last_changed')
| list %}
{% if x | count > 0 %}
{% for y in x %}
{%- set diff = as_timestamp(now()) - as_timestamp(y.last_changed) -%}
{%- if diff < 60*10 -%}
**{{ y.name }}** {{ y.last_changed | as_local | relative_time | indent(25 - y.name|length, true)}} ago
{% endif -%}
{% endfor %}
{% else %}
{{ 'No changes found.' }}
{% endif %}```
so are you saying that the indent between y.name }} ** and {{ y.last... is not working?
FYI, states have exterior whitespace removed and they are limited to 254 characters
yes in Developer Tools this jinja looks like
**Main Garage** 5 seconds ago```
but if I call the state of the sensor in a markdown card ```{{states('sensor.alarm_trigger_last_10_min_realtive')}}``` I get
```Side Garage 1 minute ago
Main Garage 1 minute ago```
yep, that's the behavior of states
use a markdown card or send it as a notification. Storing it as a state with a template sensor will truncate whitespace.
I see. I was trying to save myself from keeping multiple cards all updated with this every time I make a change. (You know what they say about premature optimization ๐ )
Just for clarification while I have you what are the whitespace trimming rules? it keeps a single space and line return?
all extra whitespace is removed
@split iron posted a code wall, it is moved here --> https://hastebin.com/giwojehoxe
it's possible that's the case as well. But you can just use HTML, which will be preserved.
oh... can you point me to a doc on that I didn't know I could produce html directly (and thanks for all your help BTW)
There really ins't a doc on it, it's HTML
I meant... for the card config
I can take it from there then ๐ (I thought you meant there was some special HTML card or something)
no, all markdown inside and outside home assistant renders html
markdown is a language... kinda
it's used by many different softwares
Also, I know my example looked dumb, but I have some really long sensor names that can make the list hard to read when multiple entities are showing up. It is just easy to trigger the garage from my desk. Anyway, Thanks again!
How would I prevent this automation from triggering itself and causing a loop. I just noticed it's doing that.
https://dpaste.org/UW5e3
The goal of the automation is sometimes zha groups when turning on to a different color temp than previous on state will turn on incorrectly and not turn on on the new color temp. This is a Backup to correct that when it happens. However in me targeting the script to run again I'm also triggering off script Start and creating a never ending loop. It needs to be parallel to watch multiple scripts.
How many of such scripts do you have that needs monitoring? Perhaps it's easiest to just make one backup automation monitoring each script, instead of one master automation to monitor all scripts?
A lot. Each light group has a day/night script and some have 2 additional scripts. So at least 18. I do that so the script can be manually triggered from the frontend. In theory I could refactor them to consolidate them to 1 script per group and create a variable to pass which light setting to use. I would rather avoid that for now if possible.
I thought of a single automation per script or even including it in the automation that fires the scripts. Or including this In each script but I figured that was a lot of unecessary code duplication.
To anyone following this thread this was my solution. Use ย instead of the jinja indent() filter.
**{{ y.name }}**{{' '|safe*(25-y.name|length)}}{{ y.last_changed | as_local | relative_time}} ago
Yeah...if it is on the scale of say 5 scripts then I would argue it's not worth the effort to write a master automation. But 20...sure, I can see the value proposition.
Definitely a future state refactor will be to consolidate. But for now I am hopeful there's a way to use this automation.
Would be nice if the trigger data for events included what triggered it. Similar to what the logbook does. That would make this easy. But it doesn't show what called the script in the data only the logbook. Is there a way?
Seems like there is a need for a bit of memory. Can you write the entity id of the light group that the automation targeted on the previous run to an input_text? Then add a condition to check whether the current run's target is different from the last run's.
Why does this need to run in parallel and not "Single"?
20 light scripts to monitor.
That's possible. Curious if I need multiple input texts then and a dictionary to avoid Inteference on the chance more than 1 script is fired at exactly the same time. Then just check the last updated of the input text as well.
Yup maybe that could work.
Of course, another angle is, does the undesired behaviour happen because of the firmware on specific models of bulbs? You could in principle change the bulbs...
It's the coordinator. The network is great the bulbs are good. Sometimes the way the coordinator processes group messages they fall out of order. They have to be in order.
It's a sonoff zigbee 3.0
Ah
Yeah it's rare but would like to fix it.
If it's an issue with the coordinator's behaviour, someone in #zigbee-archived may advise better. Surely there is a way to enforce the order of the commands transmitted.
Assuming this is an issue with zigpy and not with the dongle specifically.
I talked to the dev. Not that simple lol. I think I said it wrong it's not an issue with sending. It's an issue with how the bulbs receive it. Because group commands are multicast. Once the message is sent nothing the coordinator can do with how the command is received. I wish it was simple.
Right. And who knows what is interfering en route.
Don't know the network is extremely responsive. Repeaters everywhere. It also caused an issue with the "enhanced transition" feature. That's how I find out about the issue with how the commands are received by group bulbs. Receiving specific commands is fine. But zha groups don't receive a specific command to each bulb. They listen for a group command that's blasted everywhere.
What does Failed to load blueprint: while scanning for the next token found character '%' that cannot start any token mean? Can I not use Jinja Templates as part of the yaml? Or is it only limited to values?
The relevant lines in question look like this:
{%- if true == true%}
- delay: 10
{%- endif %}
You can't do that
You can only template values unless you play more advanced games
Just use if/then
So there is no way to dynamically add or remove attributes?
That's not what that was trying to do
What do you mean by that?
That was part of a script/automaton action, and like I said 'if/then' among others
What if I have a blueprint for a template that has an entity selector input and an integration which does not support actions on lists. I would do a for loop over all entites and perform the action on each entity itself. E.g.:
action:
{%- for entity_id in input_entites %}
- service: light.turn_on
target: "{{entity_id}}"
data:
transition: 1
brightness_pct: 50
{%- endfor %}
Right, you can't do that
You should use the repeat: construct
Maybe read the entire script syntax page in the docs ๐
Or for each, actually
Yeah the docs are a bit overwhelming as I have to juggle between the Jinja docs, the blueprint docs, the templating docs and the script docs.
But how would I insert all entities in a repeat construct if I am unable to fill the for_each items dynamically?
So
repeat:
- for_each:
{%- for entity_id in input_entites %}
- {{entity_id}}
{%- endfor %}
is fine?
But only as a variable as it's a blueprint
Doesn't matter
So like:
repeat:
- for_each: {{input_entities}}
?
Oh ok, thank you very much. I presume macros are basically a no-go then?
You can do whatever you want within a given template, but not globally
The delay can also be done like this:
- delay "{{ 10 if whatever else 0 }}"
Manually traversing the data structure given by the input selector seems a bit cumbersome but at least I see a way forward now.
Thank you again for your time.l
ah, now I know why you said that earlier
The delay was just a placeholder for some kind of action as the blueprint is somewhat more complicated and originally included three recursive macros.
For more context see also the forum post: https://community.home-assistant.io/t/using-templates-in-automation-blueprints-to-modify-whole-actions/446358
yeah, that's a fine way to have an optional delay
Hello. I want to detect an netrance event to the home. This event will be calculated as boolean true or false. I have frontdoor motion sensior, and I have sensor on my doors, on/off sensor.
This is my code:
{% set frontdoor_last_changed = as_timestamp(states.binary_sensor.front_door.last_changed) %}
{% set time_diff = (frontdoor_movement_sensor_last_changed - frontdoor_last_changed) | abs %}
{{ 15 > time_diff > 0.5 }}```
Do you think this is ok? I want to catch time window when I stand in front of my door up to 15 seconds (to open my door by key, or by app) and then to catch last changed event when the door hits status on from off.
What do you think? Should I consider some other approach?
newby here. How can i get only the entity_id out of {{ states.media_player | rejectattr('state','eq','unavailable') | list }}? Trying to get the list of all my media players
| map(attribute='entity_id') before list
Awesome. Thanks
Not sure if this is really a template or automation question, but if I have a simple trigger using state with time set like:
platform: state
entity_id:
- sensor.kitchen_camera_detected_object
to: person
for:
hours: 0
minutes: 1
seconds: 0
from: none
Is it possible to make the time conditional based on some factor? For instance Id like to do something like if sun is above horizon 1 minute, otherwise 0
You probably want to add quotes around none if that is the state of that entity
And you can use #templates-archived in the for: part
As also explained in the docs https://www.home-assistant.io/docs/automation/trigger/#holding-a-state-or-attribute
The example you provided would be:
for:
minutes: "{{ 1 if is_state('sun.sun', 'above_horizon') else 0 }}"
Hmm all I did was change the view to yaml and this is how it showed ๐คท
Will give that a try thanks
Well, none will be a completely empty state, not the string "none"
So if the state is actually the string "none" you really need the quotes
Well dumb question is how can I tell if its none or "none" lol
Does the state show the actual word none in
> states
In that case it is a string, because all states are strings
And then you need the quotes
yes it shows none
If it shows nothing at all as it's state, it's none without the quotes, but I've never seen that
Okay, so use quotes
Could anyone give me some quick help with this automation: https://community.home-assistant.io/t/turn-on-light-switch-scene-script-or-group-based-on-motion-and-illuminance-more-conditions/257085 ?
i a a bit confused on how to set the illumination cuttoff and the time after which the light should go off..
i am trying to use the helpers but i dont really know what to set there..
I am trying to use an input_text to be used to produce a list of matched entities. As it is now it works just as expected. I wanted to try to filter using regex not (!) so I can use regex to exclude some entities but its not working, I don't know if my regex is bad or I am doing something wrong.
here is my template:
{%- set device_name_list = states.sensor|selectattr('object_id', 'search',
states('input_text.entity_selector'), ignorecase=true)| map(attribute='entity_id')| list -%}
^(!WiFi)(living_room_ac*.*uptime)$
I am tring to exclude any sensor that has "WiFi" in the name. And include living_room_ac_anything-else_uptime at the end of the line.
Maybe I should make the list first and then search with regex?
I tweaked the regex, now it works
^(?!.*WiFi)(living_room_ac*.*uptime)
Am I doing something wrong trying to populate an input_select using a template:
service: input_select.set_options
data:
options: >-
{%for item in states.media_player | rejectattr('state','eq','unavailable') |
map(attribute='entity_id') | list %} - {{item}}
{%endfor%}
target:
entity_id: input_select.echo_list
I get State max length is 255 characters. Should I interpret this as my template returns a single string looking like an array, instead of an actual array?
I was getting an error saying that it was not a dictionary
Let me get the exact error
hm, can't get the error back again. the code is {{states.media_player | rejectattr('state','eq','unavailable') | map(attribute='entity_id') | list }}, says acttion ran, but I don't see the input_select updated
What is the rest of the code?
Any idea what is causing these errors (added them in the dpaste link)?
https://dpaste.org/Xfqji
My guess is that you're using 'area' before it's actually defined
This also looks wrong:
- service: "{{ trigger.event.data.entity_id }}"
data: {}
An entity_id is not a service
Unless it's a script?
Oh, never mind. It is a script
alias: "AUTOMATION: Refresh speaker list daily"
description: ""
trigger:
- platform: time
at: "00:00:00"
condition: []
action:
- service: input_select.set_options
data:
options: >-
{{ states.media_player | rejectattr('state','eq','unavailable') |
map(attribute='entity_id') | list}}
target:
entity_id: input_select.echo_list
mode: single
Running this with a run action. But it's part of a simple teat runs at midnight
Move area?
I don't know if you can reference one variable from another in that section
It's weird because it works 99% of the time. Then suddenly explodes with errors.
Ok, regarding to the above issue with the template. I went in the developer tools, and looked at the input_select, and the options are updated. Looking in the GUI under helper tho, the options are not. And on reboot it resets ๐
Hello,
I have a template sensor which is on/ off when my TV is on/ off.
I have a Button in LoveLace which should be shown the icon in normal white (when TV is off) and yellow (when TV is on) (these colours are my normal on/ off colors)
If I use an input_boolean in the card it does that automaticly.
@stone bane posted a code wall, it is moved here --> https://hastebin.com/posevosupo
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
In both cases, you're applying |int to 60
You need to surround the expression in parentheses and remember order of operations
I'm having a hard time getting energy sensors to work. Does anybody see anything wrong with this template sensor?
The "state" itself works fine when copied into the template-editor.
template:
- sensor:
- name: "Energy House"
unique_id: house_total_energy
state: "{{ (states('sensor.house_channel_a_energy')|float + states('sensor.house_channel_b_energy')|float + states('sensor.house_channel_c_energy')|float) | round(4) }}"
state_class: total_increasing
unit_of_measurement: kWh
device_class: energy
Line 1: template: instead of templates:
๐ฉ my bad, it actually is "template" in the yaml-file, I just copied this line and made the typo here.
What is the error that you are getting with this sensor? That it's value is not monotonically increasing?
I got the error "float got invalid input 'unknown' when rendering template". So I added "availability" to the sensor. Now the error is gone, but the sensor still doesn't show up.
availability: >
{{ states('sensor.house_channel_a_energy') | is_number
and states('sensor.house_channel_b_energy') | is_number
and states('sensor.house_channel_c_energy') | is_number }}
No errors concerning this sensor show up in the logs? It totally doesn't appear in Dev Tools > States?
correct, I just restarted home assistant and nothing shows up. Not in the logs and not in the Dev Tools. Other template-sensors in the same file work.
Could you dpaste your full block of yaml under
template:
- sensor:
Maybe it's an indentation issue above or below this yaml for the energy sensor.
Any idea what is causing these errors (added them in the dpaste link)?
https://dpaste.org/Xfqji
Good people! Can someone help me out? I've been at this for a few days and everything I've tried when wrong in some way or another... I have two power sensors: one measures the electricity usage of the entire house - including the electricity from the solar panels. One measures the electricity the solar panels generate - including what goes back to the grid. I want to have accurate energy reading. This is what I've tried: https://pastebin.com/jvJU1SmF - but I always get very funky results, usually making it appear that I've generated or consumed tens of thousands of kWh.... Don't know why or how to fix it... Thanks in advance!
May not be related to the problem you are seeing, but what is {{ nothing }}?
I read that having value '0' would cause problems, so I kind of made it generate a faulty value...
I'm not very confident about that 'solution', but as I've said, I've been at this for a while and this is just the latest attempt to hopefully magically fix this ๐
I found out what the issue was: as I understood the docs name is optional and is like "friendly name" and unique_id can be used for the entity_id. As soon as I removed the quotes from name it worked like a charm...
Thank you for your help!
Why is the state_class set to total_increasing? Seems to me that this sensor's value may not monotonically increase over time.
Is this not necessary for it to be used in the energy dashboard?
And {{ nothing }} would refer to the value of a variable named nothing. That doesn't generate errors?
Doesn't seem to .. should I lose the brackets then?
Let's back up for a second. What's the objective you are trying to achieve? To track total energy consumed in your house? Or total grid energy used in your house?
I'm trying to make custom sensors to use in the energy dashboard. One should be 'grid consumption', one 'grid return'
Total energy consumption of the house I have, but I can't see how much of it is from the grid and how much from the solar panels..
Right...I don't use energy dashboard myself, but I think it expects you to provide direct measurements of the energy coming in via your meter and your solar production. Do you have sensors directly measuring these?
Only for the solar production
And that works fine
So I figure: grid input = house consumption - solar input
But only if total house consumption > solar production
So grid input needs to be monotonically increasing too. It seems to me that the way you've set up your grid input sensor now, it's value could decrease. Eg. On Day 1, house consumption = 100 and solar production = 50, so grid input = 50. But on day 2, house consumption = 200 and solar production = 160, so grid input = 40.
Assuming both your house consumption and solar production sensor are monotonically increasing.
Makes sense, but how? ๐
The easiest way? Get a sensor that measures the incoming grid energy lol
๐ thanks mate..
Otherwise, I think you'd need:
- A house consumption sensor that measures total energy consumed every Xmin. After Xmin, reset to 0
- A solar production sensor that measures total energy generated every Xmin. After Xmin, reset to 0
- A grid input sensor, which starts from 0. Every Xmin, if house consumption > solar production, add (house consumption minus solar production) to the last value of the grid input sensor.
But seems to me to be quite janky, esp to keep the values strictly synced by time.
I'll look into this when I get home.. thanks for thinking along!
FYI, use https://regex101.com/ to test your code in the future. Will save you headaches.
Any idea what is causing these errors (added them in the dpaste link)? The automation works a bunch of times and suddenly stops with these errors.
https://dpaste.org/Xfqji
I think one of your lights is somehow missing an entity id.
That's based on a quick glance on my phone though. I could be wrong. But the error seems to be saying it's failing to get an attribute from something at least
How do I integrate mqtt sensor if the value is transmitted under space separated name?
When I try to integrate it into HA like following, I receive a message that space separation isn' allowed.
mqtt:
#!include_dir_merge_list configs/mqtt
sensor:
- name: "CAN-Board"
state_topic: "voron/klipper/status"
unit_of_measurement: "ยฐC"
unique_id: can_board
value_template: '{{ value_json.status.temperature_sensor CAN-Board.temperature }}'
device_class: temperature
so value is transmitted under temperature_sensor CAN-Board
value_template: "{{ value_json.status['temperature_sensor CAN-Board'].temperature }}"
How could a light be missing an entity id lol?
It could be missing any other attribute, I just noticed you're specifically looking for that at one point
Check all of your entities in that domain using the dev tools. You can grab the whole domain and hopefully it'll help you track it down.
As in pull this {{ states.light }} it works 99% of the time then it fails not sure on what.
Wondering if it's missing the color temp?
Well, time to break it down. You'll have to look.
Going to be a lot of sifting lol I have over 50 bulbs
But this part of your template should be filtering that out: selectattr('attributes.color_temp', 'defined')
Yeah it should be. Very weird.
Especially because it works but at some point on something it fails and stops all runs of the automation.
Are you sure your area has lights in it? As in, the string manipulation you're using definitely produces the right output and that area has lights?
Yep pretty sure. Going to double check.
I think I had 2 areas that the area was not rendering for. Now that you mentioned it. I just fixed those yesterday for a separate issue.
Aha!
Also, is your input_text variable just [area]_light? If so, I'd set that separately/using the area variable if you can, just to avoid updating it in one place and not the other.
You could also put your input_text and script in the area, so you are less dependant on the string manipulations
Trying to evaluate in the template editor: https://paste.debian.net/1251168/
when one item in the list is play it should show ffffff
Is the title exactly the name of the list item? Or is it "Family Guy S01E02 - Title Goes Here"?
states.media_player.bhtpc.attributes.media_series_title matches the list item
when it's playing
don't escape the quotes
I know it's kinda hard as you can't replicate: states.media_player.bhtpc.attributes.media_series_title but my jinja code is correct?
the template editor blows chunks if i don't escape the quotes
{% set variables = {
"toons": ['Family Guy', 'The Simpsons', 'South Park']
} %}
{{ variables.toons[0] == "Family Guy" }}
-> True
you also quoted the list, so it became a string
ah oops
that was because you quoted the string, and then used the same quotes for the series names
How would I pull the correct input text/script for the area?
{{ expand(area_entities('whatever') )|selectattr('domain','eq', 'input_text')|map(attribute='state')|list|first }}
Something like that. Depends on what you want to do
I see. I can make that work thank you.
https://paste.debian.net/1251171/
Please have a look. Is there the equivalent of a while loop in jinja
That is unnecessarily complicated
i tried using expand() but couldn't get it to work with the varible...
it seems like you just want this:
condition:
condition: template
value_template: "{{ state_attr('media_player.bhtpc', 'media_series_title') in toons }}"
oh
and if you just want to check whatever triggered, this:
condition:
condition: template
value_template: "{{ state_attr(trigger.entity_id, 'media_series_title') in toons }}"
using "in" I should of figured that out. thanks again.
np
I know it's not efficient way but out of curiosity is there an equivalent of a while loop that could be used around the for loop. educational purposes
loops in Jinja aren't very sophisticated
The Jinja docs are linked in the channel topic
if you were to try to do what you were trying to do, you would create a namespace with a variable in it, loop through the other list setting the variable to true if you find an entry that you like, then use the value at the end of the loop as the result
but it's all very overly complex and I avoid loops in Jinja wherever possible
Yeh that's where I got to, using setting a ns.value running the loop then using the {{ ns.value }} after but couldn't get it to work. agree its complex and will take your advice onboard. Cheers mate.
@final mural posted a code wall, it is moved here --> https://hastebin.com/azahelokuv
I have the following template that will tell me which sensor in the group is on
{{ (states.binary_sensor|selectattr('entity_id','in',state_attr('binary_sensor.ringsensorsall','entity_id'))|selectattr('state','eq','on')|list)[0].name }}
But when nothing is on then it displays unavailable - is there a way from this template to ignore unavailable and just dont display anything?
I'm trying to create a sql sensor but I'm getting value 'unknown'. The goal is to get the value at the beginning of the day of a total kW sensor.
- platform: sql
queries:
- name: "Total Energy BOD"
unit_of_measurement: "kWh"
query: "SELECT * FROM states WHERE entity_id = 'sensor.total_energy' AND last_updated > datetime(date('now', 'start of day')) ORDER BY last_updated ASC LIMIT 1;"
column: state * 1000
Any ideas what I'm doing wrong?
No templates in there. I suggest #energy-archived
Ok posted in #energy-archived
Any one able to assist a pleb like me?
I have some MQTT messages coming in, but how to make sensors out of them is hurting brain.
ctp_cr3000_topic,{"connected":"true","tags":{"Water_Tank":{"AI_Slot1_CH0_DA_Raw":6605}},"timestamp":"2022-08-21T05:22:35.000Z"}
Message looks like this, any tips?
From what I understand a template and sensor object are required.
is there a way to get unit_of_measurement: be a template unit_of_measurement: > as such
i tried didn't work ...
Hm was checking this trend sensor:
temp_falling:
entity_id: sensor.outside_temperature
sample_duration: 7200
max_samples: 120
min_gradient: -0.0008
device_class: cold
I read the manual but still dont get how to mix this around to get what I want. This one indicated if the temp is falling at a rate of at least 3 degrees an hour.
If I want 2 degrees an hour, what setting should I change then? ๐
Wait there was a formula there, but how do I know how many sensor updates my sensor do?
Trying to create a template that goes over all my window sensors and then reports back those that are open in a string format. How od i create a list that i can add, remove and iterate over in a template?
How do you know which sensors are window sensors?
And are they really binary_sensors?
I have a very simple template today that goes through a number of sensors that i specify (one by one) and then creates a string that returns the one that is open or if multiple are open it returns โmultiple openโ. Now i would like to change that to it returning all of the ones that are open. I was thinking i could create a binary sensor group and someone use that one. Just not sure how.
Actually found a sweet solution. I did create a group and the following syntax
{{ states | selectattr('entity_id','in', state_attr('binary_sensor.doors_and_windows_test','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | join(', ') }}
seems to work. But it reports the Entity name rather than the Device name.
Not sure how to format as code in discord
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
In any case, that's what I would do
Alright. So the solution would be to rename the binary sensor to the same thing as the device then to get the correct text?
For instance for me right now that template returns
Altanndรถrr - Kontaktalarm, Livingroom Left Window - Kontaktalarm, Livingroom Right Window - Kontaktalarm
And i donโt want the โ - Kontaktalarmโ part in the string
You might need .replace(' - Kontacktalarm', ''), and to surround the rest in parens
Where?
At the end
Awesome! Thanks a lot
Did it work?
No, it will report nothing
As in โempty stringโ?
You can try it
Seems like it reports nothing like you said. I wonder how i can test for that. I would like it to say โAll Closedโ.
|default('All Closed', True) before the join()
is there a way to check the last time a state changed via templating? i'd like to check that the last change done to the brightness value on my bulbs for example is above a certain threshold
another use case is to check if the last time motion sensory went off is below n seconds for putting into a sensor
@inner mesa does not seem to work. Reports โresult type: stringโ instead of All Closed
what did you do?
{{ states | selectattr('entity_id','in', state_attr('binary_sensor.doors_and_windows_group','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | default('All Closed', True) | join(', ') | replace(' - Kontaktalarm', '') }}
add |list before the |default()
Your template only updates once per minute now, if you would expand the group, it will update instantly
A, l, l, , C, l, o, s, e, d
Once every second then
No
oh
{{ states | selectattr('entity_id','in', state_attr('binary_sensor.doors_and_windows_group','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | list | default('All Closed', True) | join(', ') | replace(' - Kontaktalarm', '') }}
@marble jackal not sure i understand that
just start with states.binary_sensor instead of states
put the default() part after the join()
{% set bs_list = expand('binary_sensor.doors_and_windows_group') | selectattr('state','eq','on') | map(attribute='name') | join(', ') | replace(' - Kontaktalarm', '') %}
{{ iif(bs_list, bs_list, 'All Closed') }}
That should also work if you can't get the default working
Moving default to after join and removing the list seems to have done the trick.
Final sensor
{{ states.binary_sensor | selectattr('entity_id','in', state_attr('binary_sensor.doors_and_windows_group','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | join(', ') | default('All Closed', True) | replace(' - Kontaktalarm', '') }}
I'm trying to exclude a user_id from an event trigger using limited templates like this:
- platform: event
event_data:
user_id: "{{ not 111222333 }}"
# or
user_id: "{{ not in [111222333] }}"
but it doesn't work. How do I do this at trigger level?
I'm trying to avoid regular conditions because I have a lot of different triggers for this automation...
yeah, you can't do that
๐ฟ
you're providing a value, not creating a conditional about what to accept
the way to do it is via a condition
oh so not even 111222333 or 444555666 would work?
that will just always be "true"
which will match nothing
again, you're providing a value, not a test
okay thanks alot!!
wait a minute
what about {{ trigger.event.data.user_id if trigger.event.data.user_id in [111222333,444555666] else 'yeet' }}
you can do that in a condition
ahhhh, probably not because "The event_type, event_data and context templates are only evaluated when setting up the trigger, they will not be reevaluated for every event."
you can't use trigger.xxx in the trigger
value_template: >-
{{ state_attr('light.kitchen', 'brightness')|int(0) == 0 and
(as_timestamp(now()) - as_timestamp(light.kitchen.last_changed)) >
500 }}```
whats wrong with that?
first:
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
oh and states.light.kitchen.last_changed
that was it, the missing states, thanks
also default= is not required on type filters so I don't use it (didn't actually know you could specify it as default=)
brightness is already an int, no need to convert it
brightness doesnt exist if the bulb is off
therefor it needs a default and int(0) is cleaner than default(0)
Then check for it being none
Or check if the light is off
is_state('light.kitchen', 'off')
Or state_attr('light.kitchen', 'brightness') is none
i will probably be changing it to < n so would rather not have the extra check when it's not necessary, if i merley wanted to check for on or off i would do that
There seems to be something wrong with (as_timestamp(now()) - as_timestamp(states.light.kitchen.last_changed)) > 500
as that should mean if it last changed more than 500 milliseconds ago should it not? unless timestamp does not equal the unix timestamp format
it worked the first time I triggered the script after fixing it, but is not triggering now and to test i removed that part and it continued past the condition
apparently it's in seconds not milliseconds?
now() is only evaluated once per minute
ah
And that is indeed seconds
is the template a trigger or a condition?
Use 0.5 instead of 500
- condition: template
value_template: "{{ state_attr('light.kitchen', 'brightness' )|int(0) == 0 and (as_timestamp(now()) - as_timestamp(states.light.kitchen.last_changed)) > 5 }}"
sorry I misread until now
No need to convert everything to timestamps
now() - states.light.kitchen.last_changed > timedelta(seconds=0.5)
thanks
@inner quiver posted a code wall, it is moved here --> https://hastebin.com/aqisajagel
Hey there, i am trying to setup a switch.command_line.
Currently i am facing issues with the command_state and value_template.
While my sensor.rest works like a charm, the same template does not work with a switch.
any ideas?
not viable as the state is sadly not set via POST requests but as query-encoded get requests....
command_on: "curl -s 'http://<ip>/remote?action=MONITORON'"
command_off: "curl -s 'http://<ip>/remote?action=MONITOROFF'"
you can GET or POST with the RESTful switch
how exactly would i do this?
Per Documentation you can choose between post, put and patch.
URLencoding is not mentioned anywhere.
the only viable solution i can see is to utilize the params with a template. where the current state would have to be inverted, which would invalidate switch.turn_on or switch.turn_off srevices or can the intent of the switch-action be read from within the template?
I just got it...
value_template: "{{ value_json.monitor == 'on'}}"
possible return values are only "on" or "off". but i still need a comparison..
the sensor accepts "on" or "off" directly
What would be the correct way in an automation to update a dynamic list (ie. input_boolean.chore_*) of input booleans to off. I can get the list of all current chores, but I am not sure how to call the input booleans service turn_off from my teplate in the automation. I currently have https://kopy.io/mwe7o for my automation
Most definitely not that
I'm almost certain I posted a similar solution here in the last week
Here's one: #automations-archived message
Another: #automations-archived message
Templates don't do anything, services do
awesome... ill play around with that.. still learning the whole "Scripting" part of HA. I have been a super user of node-red in HA, but trying to covert everything to automations/scripts now
Thank you for the guidance!
while i have you, is there a way to loop over an automation with different params? example: I have a daily "validate enough chores are done for {child}" that makes sure they are up to date on their weekly chores. I have 3 automations, one for each child. The only difference in the automation is the input boolean match (chore_{childName}_chore_name) and then I have a script that sends a phone notification to them which i made script names be the same, except for the child name. Does that make sense? is it possible to combine into one script with a list to iterate over, or do i need an automation for each child that checks their own chores? https://kopy.io/V4fZr is the automation
Hi, I want my sensor to reset at 5am and it doesn't work, what is the problem? https://pastebin.com/vUsHyEzy
Your start is later than the end for most of the day
I have to rewrite it the other way around, do I understand correctly? @inner mesa
You'll have the opposite problem then
That integration measures statistics for a period of time
That's not true
At all
There's no 'reset' for that integration
Trying to split out the hourly forecasts of the weather.openweathermap entity and found this template:
Timestamp: {{ (i.datetime//1000) | timestamp_local }} Temperature: {{ i.temperature }}
{% endfor %}```
from the following webpage: https://community.home-assistant.io/t/beginners-templating-question/182773
When I try it out in the template preview page on the developer tools I get an error:
```TypeError: unsupported operand type(s) for //: 'str' and 'int'```
This:
Timestamp: {{ (attr.datetime//1000) | timestamp_local }} Temperature: {{ attr.temperature }}
{% endfor %}```
returns the same as well
There's no difference between the two
Sure I just wanted to double check that there was not an issue with just iterating on i. Any idea why I am getting that type error?
What value does that attribute have?
@opaque marlin posted a code wall, it is moved here --> https://hastebin.com/decaxajixa
Yeah, the biggest issue I am running into is my lack of understanding of the way HA structures attributes like that and why there is a specific entity type called weather but all of the forecast data is packed into a single attribute
It's just how it was written
I'm sorry I am a little confused, what is this?
Whoop replied to the wrong message. You said:
attr.datetime|as_datetime|as_local
Timestamp: {{ (attr.datetime//1000) | timestamp_local }}
This is the solution:
Timestamp: {{ attr.datetime|as_datetime|as_local }}
Oh gotcha, thank you so much!
Out of curiosity, what is the difference between the two?
The first assumes that value is a timestamp in seconds, not a string
Ohhh alright that makes sense
So the final piece to the puzzle, if I wanted to create a new template sensor that pulled in just the first set of attributes, how would I go about that? I found this:
https://farmer-eds-shed.com/weather-forecast-based-automation-and-notifications-with-home-assistant/
Where it looks like they address a specific element in the set of attributes. I am still a little lost on the structure of the attributes. Can I do a similar thing as they did? Is there any way to see an entities attributes in like a json structure or something?
So in this case each hour is a separate dict?
yes
you can stick this in
-> Templates to see the attributes in JSON if that helps:
{{ states.weather.openweathermap.attributes }}
Yeah that does help thank you
So how do I access a single element in that dict? ie [1]states.weather.openweathermap.attributes?
you were already doing that in the loop above
states.weather.openweathermap.attributes.temperature
but better as state_attr('weather.openweathermap', 'temperature')
this is all explained here: https://www.home-assistant.io/docs/configuration/templating/#states
linked in the channel topic
Ah yeah perfect that returns a single value, how to you select the next element in the list?
[1]
Yupp I read that but was having a hard time wrapping my head around it
as in:
{{ state_attr('weather.openweathermap[2]', 'temperature') }}?
Jinja docs are in the channel topic as well
no
that woudn't make any sense
first, "temperature" there is just an integer, not a list
Ah thank you. Did not understand the difference between jinja and yaml
you would need to find a list, like "forecast", which you already used above
they are completely different
state_attr('weather.openweathermap', 'forecast') is a list. state_attr('weather.openweathermap', 'forecast')[0] is the first element of the list
and so on...
Wow thank you so much. This has been massively helpful
I suggest playing with it in
-> Templates, where you see the results in real time
Yupp that is what I have been doing. Very useful feature
#node-red-archived would be better
right - ok thanks
Morning ๐
I'm experimenting with excluding loop from this one https://dpaste.org/vnzGM and I think I need a little help ๐
This is part of a cert expiry notifier, and the base logic is: if something is below the set X days threshold, send a notification.
Now I can get as far as mapping state as_timestamp, but I'm stuck with running math operations after doing this.
I've got this far:
|selectattr('attributes.error', 'equalto', 'None')
|selectattr('attributes.is_valid', 'true')
|map(attribute='state') | map('as_timestamp')```
the values look like: 2029-03-14T08:13:08+00:00
so essentially what I'd need to do here is: as_timestamp(state)|float - as_timestamp(now()))/86400) to have the diff, and |int compare that to my input_number (which is set in days), and |count
is there a way to do that in the stack of filters, or I really need to split things up and run the math ops in a loop, build up some ns var and |count at the end?
something like: selectattr ( 'as_timestamp(state)|float - as_timestamp(now()))/86400', 'gt', input_number...|float))|count
Hi is there a simple way to have template sensors trigger on State changes as per usual, but to limit the rate to no more than once every say 30 s? I am triggering off something that mostly changes once every few minutes, but sometimes itโs every second and I want to ignore it then.
Help needed. How do I fix this to show sensor.idle_state when switch.plug_voron is on?
{% if is_state('switch.plug_voron', 'on') %}
sensor.idle_state
{% else %}
Off
{% endif %}
{{ states('sensor.idle_state') }}
You can't make changes to the attribute itself when using selectattr
I have a trigger-based template sensor with the following variables defined:
- trigger:
- platform: state
entity_id: sensor.plug_kitchen_oven_energy_last_state
variables:
from_state: "{{trigger.from_state.state | float('no value')}}"
to_state: "{{trigger.to_state.state | float('no value')}}"
counter: "{{this.state | float('no value yet')}}"
sensor:
...
What does this.state contain -- the trigger state or the state of the sensor being defined in the sensor section
this.state will be the state at the moment of the trigger
variables isn't a valid option for state triggers
unless this is new, but I don't remember seeing anything like that.
That's new
when was it added?
only for templates?
Any trigger I think
hmm, nice
TIL
Ah, the new part is that they have this
they are limited templates, makes sense.
They were only available on MQTT triggers and something else for a long time
yeah, they had the trigger_variables (or something like this) for a long ass time, but they were useless unless you were using MQTT. These seem much better.
The trigger_variables can be used in the trigger themselves, the variables in the trigger are rendered after the trigger happened, and are not limited to limited templates as far as I know
The trigger_variables are limited
You can change it to a trigger based template sensor on a time pattern
Ah, that's what I get for skimming
that makes them pretty powerful for template sensors. Time to rework some crap.
oh man, I can rework just about all my template sensors to reduce code
and remove unwanted sensor changes from triggers
Have to get inventive with the triggers tho, but you could probably use yaml anchors to dupliacte the code from one trigger to another
I really need to get into trigger entities sometime...
so, they have a niche use, but now they have a much better use
You can do a string comparison with the state though:
{{ expand(integration_entities('cert expiry'))
|selectattr('attributes.error', 'equalto', 'None')
|selectattr('attributes.is_ valid', 'true')
|selectattr('state', '>', (now() - timedelta(days=states('input_numer.whatever') | int).isoformat()) | list }}
Is there any option to sum some enititys? Like any Helpers oder anything?
a non-specific question gets a non-specific answer:
{{ states('sensor.a')|float + states('sensor.b')|float }}
Can i sum all entitys of an specific area?
now you're getting more specific ๐
perhaps just ask the final question
{{ expand(area_entities('some area'))|map(attribute='state')|map('float')|sum }}
like, what exactly are you trying to do?
I have multiple power outlets that can measure power consumption. Now I want to get the sum of every sensor in my room. After this i want the sum (W) converted to kWh.
so create a template sensor with what I just provided, then use the Riemann Sum integration to convert to energy: https://www.home-assistant.io/integrations/integration/
and #energy-archived can help with that
Am I correct in the assumption, that there is no other way to access last_changed apart from using the state object, i.e. states.sun.sun.last_changed?
Correct
sensor:
name: Leistungsaufnahme Jakob
state: >
{{ expand('group.steckdosen_leistung')|map(attribute='state')|map('float')|sum }}
device_class: power
unit_of_measurement: W
now i have my sensor with my sum of all W. The Problem is i don't find my enitity in the Riemann Sum integration... Any Idea?
#energy-archived can help
Hi there. Keen for a little help here please. I have an entity called sensor.solaredge_inverters and want to be able to extract the attribute connectedOptimizers from it. Here's the State attributes:
inverters:
- name: Inverter 1
manufacturer: SolarEdge
model: SE8250H-AUL00BNU4
communicationMethod: WIFI
cpuVersion: 4.15.119
SN: xxxxxxxxx
connectedOptimizers: 24
friendly_name: solaredge (Inverters)```
I figure I have to do something like: {{ state_attr('sensor.solaredge_inverters.inverter 1', 'connectedOptimizers') }} ?
...but that doesn't work. Help? ๐
hello everybody
I've managed to confuse the hell out of myself and my lack of yaml is frustrating me. I'm trying to calculate out my houses power consumption, however, my inverter and battery doesn't provide a single value for that. So I have to do a calculation:
battery_day_discharge + grid_active_power + (input_power - grid_exported)
the code i have:
{{states('sensor.battery_day_discharge')|float|round(0)+states('sensor.grid_active_power')|float|round(0) + states('sensor.input_power')|float|round(0) - states('sensor.grid_exported')|float|round(0)}}
except what that does is: battery_day_discharge + grid_active_power + input_power - grid_exported
@harsh patrol To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
That should not make a difference, but you could add the same parenthesis as you did in your example
But 5 + 4 + 3 - 2 and 5 + 4 + (3-2) have the same result
You could try something like
{% for inverter in state_attr('sensor.solaredge_inverters', 'connectedOptimizers') if inverter.name == "Inverter 1" %}
{{inverter.connectedOptimizers}}
{% endfor %}
Thanks. Iโll give that a try when I get back to my computerโฆ cheers!
you don't want to do a for-loop.
{{ (state_attr('sensor.solaredge_inverters', 'inverters') | selectattr('name', 'eq', 'Inverter 1') | list | first | default({})).get('connectedOptimizers') }}
Iโll try that too. Thanks very much
how can i check if the last_updated of an entity is older than 2hrs from now?
So i can get the last_updated with {{ states.sensor.mi_11_battery_level.last_updated }} but i want to see how long ago that was, basically,
{{ now() - states.sensor.whatever.last_updated > timedelta(hours=2) }}
ok, wow, i didnt know that.. thanks a lot
my wife seems to have trouble keeping her phone charged... so i set up HA Companion app on it, so she can see its battery level etc, and i can notify her when it gets low
but sometimes she does not have the app running, and HA just shows "93%" or whatever, even though it was last updated like 20hrs ago
that's going to happen
iOS also does other goofy crap like pop up messages that say "Are you sure you want this app to have access? click here to revoke" Etc
well now i can atleast show it in the HA UI's throughout the house, that her battery level has not updated in quite some time
so if your wife is bad with tech, it's going to be a problem because of iOS.
I don't know if android does that, but it's a constant problem for me with my family with iOS
yeah, android tries to 'battery save' constantly
i even have the HA app set to 'autostart' and not locked to avoid battery saving etc.. but it still closes sometimes
really frustrating
Hi there, I'm having problems getting 'scan_interval' to work with a rest API call. I have the code in a rest.yaml file so could it possibly be a formatting issue?
- resource: https://transportapi.com/v3/xxx
scan_interval: 86400
sensor:
- name: Departures
json_attributes_path: "$.departures"
json_attributes:
- "all"
value_template: "ok"
Due to rate limits I only want the API to be called once a day, then use a button calling homeassistant.update_entity to trigger an update.
yep, that should work, but it will update when you reload or restart because that's the first scan.
Thanks @mighty ledge, will need to debug some more then.
howdy ๐ can I get all plex media players with anything like integration_entities('plex')?
it looks like these are available in the core device registry with a plex identifier, but that above doesn't turn up much:
...
"identifiers": [
[
"plex",
...
I get a "[]" back in template dev
don't need regex for that, slower than just using selectattr('domain','eq','media_player')
are the media_players unavailable?
if you also do expand(), yeah
yeah I expand - ok that makes sense
I get a total of three, so I imagine that any perf diff is in the noise
trying to build a sensor that lights up when any of those clients are available - looks like that's gonna be much easier than I originally thought haha
let me turn one on and see what's up that way
actually the server was off ๐
oh perfect, thanks folks, that solved it all
Can anyone explain to me what the โscopeโ of a Yaml anchor is: must it be within the same file, or even within the same key at the parent level. Secondly where does it end โ does it include everything that is on a level under the key in which it is defined, ie until it hits the next key on the same level?
It's per lline. The scope is from the definition onwards in the same file. It ends when the same anchor is redefined (which Hass yaml processor doesn't support IIRC).
And yes, the definition is for everything below the same level.
I use them mostly for my dashboard, for example so I don't have to repeat the config for all cards when I use lovelace-state-switch which was created by some genius ๐
I use them for card_mod styles ๐
You guys should use lovelace_gen...
no need for anchors
I use anchors for repeated triggers/entity lists in automations. I.e. the trigger has an entity_id list, which I use as a variable to do crap later.
Tbh Iโm surprised neither of you use it. Itโs basically โuse jinja to write your configโ
I wrote a whole autogenerated UI that builds my interface based on entity type and organizes each page nicely depending on the number of entities on screen
I like the GUI editor better.
The nice thing for me is that I just add an entity to my lovelacegen config, reload, and the entity is in all the places I expect it to be
Does lovelace_gen even work now?
Yeah
Cool. I really thought it didn't.
Iโll maintain it if you abandon it
Yeah but it doesnโt need any updates
I think I wrote the last 1 or 2 PRs that fixed things
Tbh I thought it would break with bdracos yaml loading changes but it worked without a hitch
That's what I assumed too.
I just thought the lack of upset people meant there were not that many users...
Hahaha
I think there are more users than you think
Although mushroom cardsโฆ. Make it less useful
In conbo with your auto entities
๐
I really miss a Mushroom entities card to be used in combination with auto-entities
hi, is it possible to create a sum helper.. where i can add and subtract values from?
kind of like the shopping list, but all elements should be summed together
Hi, I'm looking for more documentation around the Jinja2 select('search', 'xxx') filter
I can find the default userdoc around select(), but it doesn't explain how to use the search...
Can I provide multiple values to have as OR statement ?
It's with the rest of the extensions
if you are referring to the pinned post, then I already looked at that... the select is described in 3 sentences, but the tests are not explained
Test string is search(find, ignorecase=False) will match the find expression anywhere in the string using regex.
The link in the channel topic
cna I do select('search', 'value1', 'value2' ) ?
not that easy to use regex... I want to search for 2 specific mac addresses in a list
I'll give that a try, thanks
You can do it, the syntax is odd tho
How would it look then?
I've got this little template to tell me how many days since my utility meter reset. It increments after 24 hours. What I'd really like is for it to increment when it's the next day. How can I easily substitute the time of last_reset for midnight to achieve this?
{{(now() - state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime).days | int }}
you put the card in options.
here's my media player one
that shows media-players using the media-control card
- type: custom:auto-entities
card:
type: vertical-stack
card_param: cards
filter:
include:
- domain: media_player
entity_id: '*_echo_dot*'
options:
type: media-control
exclude:
- state: standby
- state: unavailable
- state: 'off'
vertical-stack could be replaced with the entities card as well.
you can use auto entities to do anything, even combine it with layout card
which really isn't needed anymore but it's possible
So, you combine that with mushroom cards, entity field is auto populated on the cards
so you omit that from options
Ah, I'll dig into this after my holiday
yah, take your time. Lemme know if you have questions. I doubt you will because once you see the yaml, it's straight forward.
I suspect it's already midnight, but it doesn't look like it because it's in UTC timezone
It's not, because it's been reset by an automation. I can't (as far as I know) use cron for a 28 day bill cycle.
you have to math it out if you want it from midnight
use today_at() to get midnight
Oh, so you can't just substitute 00:00:00 from a datetime? I'll take a look at `today_at()' I haven't come across that yet.
depending on what you want it could be as simple as replacing now() with today_at().
today_at() gives a datetime object
if you leave it blank, it returns midnight
if you provide a time, it'll give you that time of day
i.e. today_at('07:00') is 7am
Just been mucking around in the template dev tool to understand this.
{%- set reset = state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime %}
{{(today_at() - reset).days | int }}
{{today_at() - reset}}
returns
0
11:25:24.600799
It's getting close - I'd like it to be 0 if today_at() is the same day, 1 if the next and so forth.
a-ha!
{%- set reset = state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime %}
{%- set reset_day = strptime(reset.date() | string, "%Y-%m-%d") | as_local %}
{{today_at()}}
{{reset_day}}
{{(today_at() - reset_day).days}}
2022-08-24 00:00:00+10:00
2022-08-23 00:00:00+10:00
1
Accidentally edited this message in to oblivion ๐ฆ
I'll try to recreate it...
entity.date() was what I needed. Then just had to change it to a datetime again.
that's overkill
{%- set reset = state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime | as_local %}
{{ (now().date() - reset_day.date()).days }}
Sorry about that mess of editing. I turned off the PC, switched to mobile and somehow edited my message when I thought I was replying.
Gah, that is much nicer. Thank you. I will update my template:
{%- set reset_day = strptime((state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime).date() | string, "%Y-%m-%d") | as_local %}
{{(today_at() - reset_day).days}}```
With what you've written.
I'm really learning coding as I'm going and as such I keep stumbling in to messy solutions. Much clearer in hindsight ๐
nooo
you keep adding crap
you don't need to strptime anything
you have 2 datetime objects, you don't need to adjust anything.
Just this:
{%- set reset = state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime | as_local %}
{{ (now().date() - reset_day.date()).days }}
as_datetime makes a datetime object
as_local takes the object and turns it into your timezone
strptime is redundant in your case.
Yes, I was trying to show you what I ended up with, and saying that I will use your code now that I've seen it.
strptime takes a string and turns it into a datetime object, which as_datetime already does
ah
Just thought I'd share my end result before I shred it ha! I follow what you're saying completely. Thank you as always
So, now().date() and today_at() effectively provide the same output. Any reason to use one over the other? Does now cause the sensor to update often as now is constantly updating?
no, now().date() returns a date, today_at() returns a datetime. Dates are just dates, Times are just times. Datetimes are dates and times combined.
there are plenty of reasons to use one over the other, it depends on what you're trying to do
now will cause the template to update once a minute
today_at would require you to add a trigger to your template sensor because it would only update when sensor_monthly_energy_off_peak updates
but that might update enough
now().time() returns a time (just for the sake of complemeness) ๐
and dates, times are not timezone aware, where datetimes are
Ah, got it. That's all pretty intuitive with the naming then. I had it in my head that I needed to work with date times when subtracting dates or times. I see.
lots of crap with times
I found an epic community post on all things dates and times tonight but there's a lot to digest in it.
This is all because utility_meter can't take a fixed length billing cycle (28 days). So I've made an input_text for the billing cycle and an automation that resets the meters just before midnight. All I have to do is call the service at some point in the day and it will reset every 28 days there after.
I'm sure this is where I find out there was a heaps easier way...
Yeah... it's also not optimized. Most of that stuff isn't useful at this point
The guy who originally posted it made it when as_datetime, as_local, timedelta, and today_at didn't exist and he hasn't kept up with the times
he also doesn't know templates well but pretends he does
I'd take that whole thread with a grain of salt.
I'm not saying you can't learn something from it, but it's really outdated and it has bad information in many of the posts
So you know the one I mean. There's useful basics in it for me all the same. One thing I've learned with HA is that post content gets deprecated very quickly and I'm always comparing what some post said, compared to the documentation.
Ended up finding .date() through the links within template documentation of course.
it's the one by finity, correct?
Yes, that's the one.
Yep, then heed my warning ๐
it's mostly copy/paste from other sources
think of it as 'word of mouth'
or the 'password' game
where one thing is passed to another and another, and you end up with something completely different
Yep, understood. Good from far, but far from good.
right
Your best resources for templates on the forums comes from a small list of people
I'm sure I'll learn who they are with time. Still very new to this
123, robcoleman (robc), thefes, myself, pdbruckner, and there's a few up and comers who are actually learning it instead of copy/pasting
I already recognise a few of those
I'm sure I'm missing names, but that's active people
there's another guy, I can't remember his name
also topics/questions from mariushvdb have alot of good information on templates in complex situations
I'll take a look
I have a tuya switch (connected through localtuya) that reports W, A and V as attributes rather than separate sensors. How can i make it into a kWh sensor so that i can add it to my energy dashboard.
make a template sensor extracting the watts. Then use the integration integration to produce the kWh sensor.
so you'll end up having 2 additional sensors
how do i create a template extracting the attribute?
check out the docs here for creating template sensors. -> https://www.home-assistant.io/integrations/template/
you'd use state_attr('entity_id', 'attribute') replacing your entity_id and attribute
as the code
this is a close example
https://www.home-assistant.io/integrations/template/#state-based-sensor-exposing-sun-angle
but all you need for the code is "{{ state_attr('entity_id', 'attribute') }}"
Thanks!
Managed to get the sensor working. Now what method for the Reimann helper do i use? Tried reading the docs but was unclear.
Hi - Looking to create a template that tells whether the logged in user is on the home wifi or not. First step would be getting the user name in the template. To simplify the first step I am testing the below template but nothing seems to be working as expected and the documentation I can find is very limited though it seems it is possible to retrieve the user name.
How would I create an if statement like below where "user" is the current logged on user?
`binary_sensor:
- platform: template
sensors:
user_on_wifi:
friendly_name: User Wifi
value_template:
{% if user == 'Test1' %}
true
{% endif %}
false`
The first sensor (the W) is working and reporting correct but the reimann sensor (kWh) is reporting unknown. Does it take some time for it to start working?
"logged in" is a frontend thing
that makes sense, so would have to happen on the front end... the end purpose is for use in a dashboard.
just keep in mind that you'll only be able to see the user on the browser you're on. The other browsers will see what user is logged on there
so it's rather pointless as you can already see that information.
in the lower corner
several custom cards provide the ability to change behavior based on the user who's currently logged into that browser instance
i.e. Me logged on device A will not be able to see who is logged into device B
The end goal is for cameras. While on home wifi I want the camera card shown to be WebRTC as it is near real time. However this will not work off the network so then I want it to use the custom frigate card. So my thought was to get who is logged in, then check if their device (phone) is on the home network, then choose the correct camera card.
Thanks
I'll check it out, thanks
Any help on how to troubleshoot?
It depends on the update rate of your first sensor and your first sensor needs to have data in the database. Get more info in #integrations-archived as this is the template channel.
so I have a restful sensor for remaining time of battery charge, but when not plugged in it returns the value of unknown, I have tried searching the forums and web to change this to text of my choice, any ideas ?
You need to set the availability template I suspect, but without seeing your sensor it's hard to say
Is it possible to create a sensor that has the lowest value of a one hour sliding window?
Yes, with a trigger based template sensor. Time pattern trigger on each hour to reset it to that value, and trigger on each state change of the source sensor, compare that to this.state and pick the lowest
https://hastebin.com/uxoxuhujif.swift this is the code, it basically gives me a time remaining for a charge, I just want to try to get the template to return (not charging or unplugged) instead of unavailble when the charge is not operating.
Are the variables ('switches/trigger_switches') not dicts? switches.items()| it appears the error is saying it's not a dict
https://dpaste.org/Wsv3J
I would just write them as YAML, then it's a dict for sure
But I think the mult line format is making it a string
Ah yes remove >-? That fixed it. The GUI automatically converts it to a yaml dict. After saving*
I want to create a single script that handles persistent notifications. Is it possible to variablize actions because some notifications may have more than one action. Is it possible to variablize it so that a single action could be passed to a script or even 2 or 3? I assume it's possible as it's a list I'm just not sure how
Here's an example of what I'm referring to with more than 1 action in a notification https://dpaste.org/1QcfA
it's the same as any other variable, you just have to build the list of information to pass it
actions: "{{ actions }}"
now it's a variable
Something like this?
{% set test = ['action: 22','test: true'],['action: 44','test: false'] %}
{{ test }}
Still a little confused. How would I convert what I sent for example to what you're saying? 2 separate actions
right now you have 2 lists as a tuple
In your example you are creating separate lists, it should be only one list
You had this ([{}],[{}])
no, he was missing the dictionary {}s
So this?
{% set test = ['action: 22','test: true','action: 44','test: false'] %}
{{ test }}
so he just had 2 lists of incorrect syntax
you're missing the dictionary indicators
Oh yeah, whoops
{} -> dictionary
[] -> list
[{...}, {...}]
list of dictionaries
list -> [ item1, item2 ]
dictionary -> { 'key1': 'value1' }
now put them together with what you have above
{% set test = {'action': '22','test': 'true'},{'action': '44','test': 'false'} %}
{{ test }}
Better?
that might work, but it's not a list
that's a tuple
a tuple is ()
but tuples are special in that they are implied when you use a comma without the () surrounding the item
also, keep in mind that you're turning your numbers and booleans into strings
which is a separate issue
I noticed that I wasn't sure if I needed it to be a string
it can be whatever you want
the key needs to be a string
because that's what yaml requires
in normal circumstances, key's can be any object as well
I see. So what would work for sure since you said "might" earlier lol
{% set test = [{'action': '22','test': 'true'},{'action': '44','test': 'false'}] %}
{{ test }}
your ending ] is in the wrong spot
oh now it's in the right spot but you have an extra one
and now its fixed
your list...
{% set test = [{'action': '22','test': 'true'},{'action': '44','test': 'false'}] %}
\-----------item1------------/ \----------item2--------------/
your dicts
{% set test = [{'action': '22','test': 'true'},{'action': '44','test': 'false'}] %}
\-key1/ \k2/
I fixed it lol. I was just copy and pasting from above. Alright perfect this should make creating these notification automations 10x easier.
Makes sense
yep
should be good to go
but keep in mind
you don't need to do that for your variable
you can use yaml
in your yaml, you're simply going to pass exactly what you would normally pass
your script will have:
actions: "{{ actions }}"
and your script data will simply be what you normally pass
using your example above....
service: script.my_notify_script
data:
actions:
- action: 22
test: true
- action: 44
test: false
I would pass that ^? It didn't occur that's the same thing as what I did.
Learning a lot from Pepperidge farm
when you have multiple lines that have key: value, it makes it a dictionary
so paring it with my examples above
this is a dictionary in yaml
key1: value1
key2: value2
a list...
- item1
- item2
so a list of dictionaries....
- key1: value1
key2: value2
- key1: value1
key2: value2
Yep I didn't think about that. I remembered that for lists but I don't use dictionaries that often to remember they can be done in 2 different ways and are read the same.
Thank you for the additional explanation
np
Hi, I'm working on adding something like this project to my setup: https://community.home-assistant.io/t/screen-time-for-the-kids/452149
I've created the history stats as described in the post and created some helpers (toggle) to turn screentime on and off. I've also created a helper (number calles time_available_for_foo_this_week) with the available screentime for that week, during holidays that will be more and it can happen that I manually give them extra time, love to do that with an automation. I need some help for two things:
- When I look at the history stat, it could be that the total time is 1.75 -> how can I display that as 1 hour and 45 minutes.
- How can I display the amount of time that is left for that week or where can I calculate that -> so time_available_for_foo_this_week - time_used_by_foo_this_week
what's the name on the sensor, and what's the state? Post a screenshot of the sensor in the developer tools -> states page
also, post a screenshot of the entity on the same page that contains the time_available_for_foo_this_week
I want the various variables to be {} when '' because I am trying to use a single service call to start the persistent notification and then a single to remove it. When removing a bunch of the variables will need to be {} but it seems my iif statements aren't working as I see in debug '' when it should be {}
https://dpaste.org/v7oFX
it needs to be an empty list
[] without quotes
also, you don't even need to do that
just use chooses in your script based on the presence of the variable
{{ actions is defined }}
if you want it to dynamically add or remove actions if it's present or not, that's much harder to do and i'll have to write the code for you probably
channel: "{{ iif(channel != '',channel,{}) }}" that didn't work. I'm doing something similar in an automation and '{}' works.
well channel isn't a dictionary, is it?
@uncut fractal posted a code wall, it is moved here --> https://hastebin.com/umiwuzasok
No. Just trying to get it to pass it. Seems to work for this. Just as data is {} when empty . Formatting is off there in the link. But it works.
https://dpaste.org/hPaEz
@uncut fractal use a share site
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.
^
|
@uncut fractal your pastes don't include the state, which is the most important part
- service: notify.mobile_app_daniels_s21
data:
message: "\"clear_notification\""
data:
tag: Garage
This is the alternative I'm trying to do in a single Service call. The rest of the variables will not be passed.
3.42 for the sensor and 6.0 for the entity
@silent vector what's a normal service call look like
This. https://dpaste.org/6Thm5
Then the clear notification service call is the one I just sent ^
Hello,
could you please point me, why this secondary information doesn't work?
primary: PS5
secondary: |-
{% if is_state('sensor.ps5_175_activity', 'playing') %}
'{{ state_attr(''sensor.ps5_175_activity'', ''title_name'') }}'
{% else %}
'{{ states(''sensor.ps5_175_activity'') }}'
{% endif %}```
type: custom:mushroom-template-card
primary: PS5
secondary: |-
{% if is_state('sensor.ps5_175_activity', 'playing') %} {{ state_attr(''sensor.ps5_175_activity'', ''title_name'') }}
{% else %} {{ states(''sensor.ps5_175_activity'') }}
{% endif %}
I think..
yep. tried to add some stuff to my restful sensor so it shows something else other than unavailable when its not showing time remaining and it justs , does not work lol oh weel there goes that idea
@uncut fractal you'll have to make tempalte sensors.
template:
- sensor:
- name: Time Used
state: >
{% set t = timedelta(hours=states('sensor.schermtijd_jinte_deze_week') | float) %}
{{ t.seconds // 3600 }} hours and {{ t.seconds % 3600 // 60 }} minutes
availability: "{{ states('sensor.schermtijd_jinte_deze_week') | is_number }}"
- name: Time Remaining
state: >
{% set t = timedelta(hours=states('sensor.schermtijd_jinte_deze_week') | float) %}
{% set r = timedelta(hours=states('input_number.beschikbare_schermtijd_deze_week') | float) %}
{% set d = r - t %}
{{ d.seconds // 3600 }} hours and {{ d.seconds % 3600 // 60 }} minutes
availability: "{{ states('sensor.schermtijd_jinte_deze_week') | is_number }}"
you have quotes around your returned value, turning it into a string.
what are you talking about? Please elaborate
doesn't work either
What does it say? To not 'work'?
it just displays the whole if ... else statement as secondary information
not the status of that sensor
are you sure that field accepts templates?
yes
Try >? It does accept templates
Instead of |-
its a template card
that doesn't mean that field accepts templates
the docs say that field accepts templates
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensor'][1]['state']. Got "{% set t = timedelta(hours=states('sensor.schermtijd_jinte_deze_week') | float) %} {% set r = timedelta(hours=states('input_number.beschikbare_schermtijd_deze_week') | float %} {% set d = r - t %} {{ d.seconds // 3600 }} hours and {{ d.seconds % 3600 // 60 }} minutes\n". (See /config/configuration.yaml, line 92).
so it should work.
it accepts, if i just put {{ state_attr(''sensor.ps5_175_activity'', ''title_name'') }} it will display titel of the game
copy the text I wrote again, it had an error in it that was corrected, you copied prior to the correction
And playing is a valid state? As in, in developer tools it's there?
I use this https://hastebin.com/uxoxuhujif.swift tells me how much time is left for charging ev battery, but when not plugged in I have been trying to get it to display disconnected or un plugged rather than unavailible
that is a mangled template, what's the state of states.sensor.peugeot_308_hybrid.attributes["energy"][0]["charging"]["remaining_time"]?
yay backup
Mushroom template cards just show the template when it errors, try to fix it in devtools
Playing looks like an attribute activity
it gives me the remaining time left of charge (peugeot api is a bit messed up to be honest) but if car is not plugged in its state is unavailible, were I would prefer the test to say disconnected...
Yes, I get that, but I need the exact state
i.e. what does it look like when it has 4 hours and 10 minutes
I tell you what ill plug it in now and tell you ๐
Any thoughts on this one? I know you're busy lol.
But if I just create entity card with this sensor, it will return Status as playing
Can you post to dpaste the developer tools section of this entity
in your script use,
variables:
passed_data: >
{% set ns = namespace(fields=[]) %}
{% if actions is defined %}
{% set ns.fields = ns.fields + [ ('actions', actions) ] %}
{% endif %}
{% if persistent is defined %}
{% set ns.fields = ns.fields + [ ('persistent', persistent) ] %}
{% endif %}
{% if sticky is defined %}
{% set ns.fields = ns.fields + [ ('sticky', sticky) ] %}
{% endif %}
{% if tag is defined %}
{% set ns.fields = ns.fields + [ ('tag', tag) ] %}
{% endif %}
{% if channel is defined %}
{% set ns.fields = ns.fields + [ ('channel', channel) ] %}
{% endif %}
{{ dict.from_keys(ns.fields) }}
@silent vector
then in your notification
use
service: ...
data:
message: ...
data: "{{ passed_data }}"
just fill out the ... with whatever you were planning on doing
Makes sense thank you. Not something I would have thought of. Maybe in a few more months something like that will come naturally
what's the output of the template in the template editor?
that worked, I will adjust some parts to make it work for other sensors & entities as well, thanks a lot. Will need to learn more about these template. ๐
๐
have fun, i'm sure you'll be back ๐คฃ
yep just as I thought the state is how much time is left before full
max number it goes too from empty is 4:15
unavailble
gets to 0:01 then when it hits 0:00 it auto stops the charge in car so it becomes unavailible.
right, but you aren't using the terms I like
so when it becomes unavailable, what does the actual attribute say
does it actually have the word unavailable?
yep
can you show this to me, take a screenshot of the attributes in developer tools -> states page
use imgur
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.
I'm very confused by your statements vs your code, so I'm having trouble trusting what you're saying.
your code is looking for the letters H and M, and then you change the result to be 00:00
however you're telling me that the information coming out of states.sensor.peugeot_308_hybrid.attributes["energy"][0]["charging"]["remaining_time"] is already in the HH:MM format.
so, either your code never worked, or you're not telling me the correct information
took screen shot of why on, just shooting downstairs to disconnect
ok, so you're not telling me the correct information
my man, i'm not asking about your template sensor.
I'm asking about sensor.peugeot_308_hybrid
in order to fix your template sensor, I need to see sensor.peugeot_308_hybrid
not your template sensors state.
ok sorry bud, my bad here you go
its the whole car, energy 0 is battery, energy 1 is the combustion engine
ok, sorry to ask this again, but can you plug it in and show me the attributes when it's plugged in?
specifically, I need to see the format of this field
308_hybrid_remain_time:
friendly_name: "remaining charging time"
unique_id: "r3ma1n1ngcharg1ngt1m3"
icon_template: "mdi:timer-outline"
value_template: >
{% set battery = state_attr('sensor.peugeot_308_hybrid', 'energy') | first %}
{% if battery.charging.remaining_time %}
{{ strptime(battery.charging.remaining_time, 'PT%HH%MM').strftime('%H:%M') }}
{% else %}
Not Charging
{% endif %}
availability_template: >
{{ states('sensor.peugeot_308_hybrid') not in ['unknown', 'unavailable'] }}
replaced and rebooting now yo try
you don't need to reboot
reload templates
developer tools -> yaml -> check config, then if passes, click reload template entities
lol really all this time i thought if its in config and changing reboot lol
you almost never have to reboot
at most you'd have to restart
reboot = reboot hardware
there's 3 levels to HA
reboot = rebooting the hardware
restart = restarting home assistant (hardware stays on)
and reload = reloading a configuration (home assistant and hardware stay on)
HA the never ending learning curve ๐ not a bad thing.
100% bud, thank you again
state disconnected.... now not charging ๐
np
its also valuble help if I change car in future as I will base template off of current one if it reports null unplugged.
its quite crazy what info some of the intergrations can get, I would say the bmw and vw ones are more in depth (windows, dooors, locks etc).
the peugeot one is sketchy, the location one is down (not intergration, but peugeots own as even official app shows my car at home when I am 100 miles away lol).
so for now I have the tronity added which allows me to use the tracker still as well as log trips on map card for tracking side of things
If I put {{ states(''sensor.ps5_175_activity'') }} i get TemplateSyntaxError: expected token ',', got 'sensor'
you don't need to escape your quotes in the template editor, only have 1 in each spot
'' = escaping your quotes
' non escaped quote
oh, I see improvements
If I put this in {{ state_attr('sensor.ps5_175_activity', ''title_name'') }} i receive TemplateSyntaxError: expected token ',', got 'title_name'
so what do you notice?
Because you're using 1 ' and 2 '' 1 or the other you can't mix inside the template.
would you not be able to find a obd gps tracker with open api and go from there?
I'm sure I would, but then I have to buy that and pay for it
{{ state_attr('sensor.ps5_175_activity', 'title_name') }}
thanks that worked
Thanks to petro and a few others (TheFes, etc.) over the last few months I'm learning enough to actually be able to help lol.
on my older car it needed a dongle for net pulls, but over here in uk the network 3 used to offer a data pay as you go sim that even if you did not top up they still gave you 600mb data a month more than enough... anyway thank you I wont take the chat off template talk anymore. Thanks for your time again.
One more question.
Will this construct work to put an image instead of icon if condition is met?
Like this
{% if is_state('sensor.ps5_175_activity', 'playing') %}
{{ state_attr('sensor.ps5_175_activity', 'title_image') }}
{% else %}
mdi:sony-playstation
{% endif %}```
how much did that cost you?
if a normal image URL works, then yes.
Even when mixing icons and pictures?
it depends on the mushroom card
if you can use an image for the mushroom card in the icon field, then you can do it
if you can't, then no
this of course assumes you can template that field as well
No you can't. You need picture for a picture. It only takes icon as far as I know. You can template in picture I use it all over. But I tried using picture in icon in a template and found out you can't mix. Picture is solely for url
ah, ok then no you can't
they were doing it free ๐ฎ promo only lasted one month lol it was supposed to be 3 months, but I think they did not expect 100,000 to get them in first month
a year later they done another promo for 250mb one and that ran out after a week they have not done it again, but I kept both sims as they still work.
type: horizontal-stack
cards:
- type: custom:mushroom-template-card
entity: switch.printer
primary: Printer
secondary: '{{ states(''switch.printer'') | title }}'
picture: >
{% set status = states('switch.printer') %} {% if status == 'on' %}
local/icons/custom_icons/plug.png {% elif status == 'off' %}
local/icons/custom_icons/plug-off.png {% endif %}
hold_action:
@velvet sigil that's one way you can template pictures only in a mushroom template card though
you can optmize that
All Mushroom cards support pictures
entity_picture yes but not picture
You need to set icon_type to picture
And then set the picture url in the icon field
Pretty sure you can't I just tried. I remember asking the dev.
type: horizontal-stack
cards:
- type: custom:mushroom-cover-card
entity: cover.bedroom_shades
icon_type: picture
icon: local/icons/custom_icons/light-bulb-off.png
name: Daniels
That doesn't work ^
It's added in v2.0
https://github.com/piitaya/lovelace-mushroom/releases/tag/v2.0.0
Yeah that's entity_picture that's if it has it or through customization. I wish it was picture lol. But I tried and asked the dev about that exact thing because I thought the same
https://www.home-assistant.io/docs/configuration/customizing-devices/#configuration-variables
Ah, you mean like a picture card
I would say this should work, but I'm on holiday, so I can't check it myself
I think we're confusing the 2 types of pictures. Only template cards allow passing 'picture' urls and in order to get a picture on other cards entity_picture has to be used and you have to set that in customization for that entity.
Here's the dev's answer to my request
https://github.com/piitaya/lovelace-mushroom/issues/600#issuecomment-1179111098
give me an error
At path: icon_type -- Expected one of "icon","entity-picture","none", but received: "picture"
Well, seems clear what you should use then
@silent vector it should indeed be entity_picture
yeah, but its useless for me as the idea was to replace an image on condition
If there's only a few images you could just save them and pass them as urls. But you can't mix icons and pictures as far as I know. you would need to make the icon a picture too.
I guess the images are passed as urls as a state of attribute
That would be the only way for it to show an image. Show the dev tools. It is likely a url
Aaah, right, I finally see what you mean. You can't provide the picture, it already needs to be provided in the entity config
I wish I was wrong though I would love to use pictures everywhere at the card level not customizations
I still think you can use pictures @velvet sigil if the title_image is a url. But you can't use the icon mdi: .. you will need to make that an .png to use both the way you intended.
this works
{% if is_state('sensor.ps5_175_activity', 'playing') %}
{{ state_attr('sensor.ps5_175_activity', 'title_image') }}
{% else %}
/local/icons/custom_icons/PlayStation-logo-1994.png
{% endif %}```
There you go
great, thank you all for help
Hello all. I had a template break on one of the new updates. I have done some research and trial and error but can not get it to work again. not sure what needs to be changed to get this working again. This was to calculate the rain rate from a rain input from my weather station.
state: >-
{% if ((states.sensor.atlas_rain.state|float) - (states.sensor.rain_10_minutes_ago.state|float)) > 0 %}
{{ (((states.sensor.atlas_rain.state|float) - (states.sensor.rain_10_minutes_ago.state|float))*6) }}
{% else %}
0
{% endif %}
You should use states('sensor.foo') instead of states.sensor.foo.state and you should add defaults to your float filters
state: >-
{{ [0, )states('sensor.atlas_rain') | float(0) - states('sensor.rain_10_minutes_ago') | float(0)) * 6] | max }}
Or add availability in case of a template sensor:
state: >-
{{ [0, (states('sensor.atlas_rain') | float - states('sensor.rain_10_minutes_ago') | float) * 6] | max }}
availability: >-
{{ states('sensor.atlas_rain') | is_number and states('sensor.rain_10_minutes_ago') | is_number }}
that gives me a value but incorrect. I should explain more the sensor.atlas_rain is the value from weather station. I need to subtract the value of sensor.atlas_rain that was recorded 10 minutes ago by current value.
You have so many unneeded parenthesis that it's hard to figure out what you are actually trying to calculate
You are also multiplying something by 6
with the old way i had it it take rain input - rain input reading from 10 mins ago then multipled that number by 6 to give estimated rain rate per hour
I took the sensor yaml from his video in the description he has a pastebin link to the yaml. it worked for over a year until last update of HA. https://www.youtube.com/watch?v=vRO9zzrlbPI&t=411s
That's what my example does as well
It makes an array with 0 and the result, and takes the highest value of those two
What value do you get, what value do you expect it to be and what are the current states of the source sensors?
@marble jackal it should give me a value of 0 at the moment since its not raining . I get 19.85 with first example you gave me. My weather station does an incremental reading so if i have a reading of 4.45 now and it rains .20 inches the reading will increase to 4.65. that why i need to subtract the 2 readings to get the rain amount then multiple by 6 to get in/hr. i hope i am relaying this right.
So what are the values of both sensors are this moment
Are they both 4.45 now?
3.33 is the reading of sensor.atlas_rain. sorry the value with the template is 19.98 not 19.85
that makes since 3.33 *6 is 19.98. it looks like it is not finding the value at 10 mins in the past. how do i get the reading of sensor.atlas_rain 10 minutes ago. is there a template to get the value 10 minutes in the past
Aaah, I was under the assumption you already had a sensor for that
Did you just make sensor.rain_10_minutes_ago up?
If this sensor doesn't exist, your previous sensor might have worked, but never gave the correct result
It just always defaulted that to 0
But you might be better off using a derivative sensor https://www.home-assistant.io/integrations/derivative/
i have a sensor it uses influxdb for stats. here is the example.
- platform: influxdb
host: 123454-influxdb
port: 8086
database: xxxxx
queries:
- name: Rain 10 Minutes Ago
unit_of_measurement: in
value_template: "{{ value | float }}"
group_function: first
measurement: '"autogen"."in"'
field: '"value"'
database: homeassistant
where: 'time > now() - 10m AND "entity_id"=''atlas_rain'''