#templates-archived
1 messages Β· Page 57 of 1
You're mapping something to something
Number -> Text
Text -> Number
Same system - just "inverted"
Now I think I get what you guys mean, I'll try. Thanks
I lied, it was for processing conversations, or making a script return a value
This is a relevant thread for it though -> https://community.home-assistant.io/t/how-to-list-multiple-calendar-event-in-a-template/349139
How do I add attributes to a sensor? Is this valid? ```
attribute_templates:
snittpris: "{{ state_attr('sensor.electricity_price_hjemme', 'avg_price') | float + avg_nettleie_pris }}"
flytende_pris: "{{ states('sensor.strompris_m_nettleie') | float }}" # Bruk strompris_m_nettleie som state for flytende_pris````
Where does "avg_nettleie_pris" come from?
if you mean "a template sensor", examples are in the docs: https://www.home-assistant.io/integrations/template/#state-based-binary-sensor---device-tracker-sensor-with-latitude-and-longitude-attributes
it also depends on whether you're using the new or legacy template format (also described on that page)
In a template sensor yes, Thanks for your help, got it now.
Hello, I need some help with a little issue.
How do you write "smaller than, or equal" in a template?
You mean <=?
yes.
yes he does I belive
Weird, ok
I have a template to compare two temperatures from different sensors, but if I simply add "<=", then the template errors out.
Because states are strings. You have to convert them to floats or integers
I get "TemplateSyntaxError: expected token 'end of print statement', got '='"
oh, I have to put the = after the sign, not before
If you share your template, we might be able to help
I meant to say larger than, or equal
{{ state_attr('climate.thermostatic_valve', 'current_temperature') >= state_attr('climate.thermostatic_valve', 'temperature') }}
Didn't realize the = had to be after > instead of before, as is usual in 5th grade math
You might have to convert to float
I used to do that, but it turned out to not be necessary.
Wasn't sure about attributes
the template worked fine otherwise, it's just that occasionally the two temperature values were exactly equal, which would cause issues in the automation.
anyway, thank you for the help.
hello,
it possible to send one notification to my phone with the ups battery status ?
i have the ups battery entity in my hass
Do you just want to know when the UPS battery is low, or do you want constant monitoring?
Also, how often do you want it to report?
i want to sent to my phone the remaining battery (like this "90% battery")
for the time, is no problem for my, i have found the solution
Ok then, if you say you've found the solution.
i mean i have found the solution for the how often to send my the notification, but i dont know how to send the sensor metricsπ
Hi. Anyone who can give me a helping hand on getting a notification to work, that includes an if statement in the message? I am trying to change a part of the Message text based on data pulled from template. Is that even possible? (edited post to remove image)
service: notify.mobile_app_jonas_iphone
data:
title: Front door TEST
message: Unlocked by {{ if ('trigger.event.data.parameters.userId','1') }} Jonas
that's not how an if statement works
What is your actual goal there? That "if" statement will just return true or false, and I doubt that you want that just inserted in the text message
(if the syntax was correct, which it's not)
Unlocked by true Jonas
The goal was for it to check if the value was 1 and then add the text "Jonas"
and if it's not 1?
just nothing?
If you describe exactly what your eventual goal is, you'll get a better help
I'm guessing it's this:
I would like to map userIDs from the trigger to names of people so that I can display that name in the message
which is a straightforward mapping exercise
Alright. Got it. Will look into that. Thanks
this was posted earlier today and demonstrates the concept: https://community.home-assistant.io/t/change-numeric-sensor-states-to-text/281428
Thanks!
I don't know if this is what you meant by "any"... https://gist.github.com/Didgeridrew/88175322bf8028b43fc3612246fb8416
If the source text's language isn't English it will probably require extensive changes.
Hi! I've a derivative that sends me spikes up to 10000kWh when I restart HA.
(While the curved which is based on has no spike)
How can I avoid this?
In a more general meaning, when you want to avoid anomalies in a sensor (like calculated, or a motor starting), what's the "best" way?
Send 0 ? Send the previous State? Make it unavailable? Send a median value based on n last samples?
Thanks!
Hi. I installed the smartthings integration and now see my Samsung appliances in home assistant. when I look at the dishwasher sensor that shows the time it scheduled yo finish it has an offset of 00:00. So the completion time should be 7:48pm eastern time but it shows 11:48+00:00. What would be the syntax for a template to show 7:48
sensor.dishwasher_dishwasher_completion_time
Dishwasher Dishwasher Completion Time
2023-10-23T23:48:34+00:00
{{ states('sensor.dishwasher_dishwasher_completion_time') | as_datetime | as_local }}
And check out the timestamp_custom() example on this page
Yeah, this might be better if you just want the time component formatted like that.
{{ states('sensor.dishwasher_dishwasher_completion_time') | as_timestamp | timestamp_custom('%I:%M %p') }}
@bright quarry I converted your message into a file since it's above 15 lines :+1:
^ what's wrong with this? i updated my home assistant and my mqtt stuff doesn't work anymore.
mqtt explorer shows events fired such as; rtl_433/rtl433/devices/SimpliSafe-Sensor/1P7T3
@steel swift I converted your message into a file since it's above 15 lines :+1:
@steel swift easiest is:
availability: "{{ has_value('sensor.electricity_price_hjemme') and 'sensor.strompris_med_nettleie' | has_value }}"
or:
availability: "{{ states('sensor.electricity_price_hjemme') | is_number and is_number(states('sensor.strompris_med_nettleie')) }}"
both has_value and is_number can be used as function or filter, is_number can only be used if the sensor normally has a numeric state
has_value needs the entity_id as input, is_number needs the state (or any other value which you want to check)
I used both the filter and function now, just to illustrate they do the same π
when applying this availability template you no longer need the 2nd if statement
@steel swift I converted your message into a file since it's above 15 lines :+1:
yes
I now see that the other sensor you were checking on before was the actual template sensor
you can replace this: month >= 1 and month <= 3 with month == 2
and hour >= 6 and hour < 22 with 6 <= hour < 22
but month == 2 will only take february? as prices is at one level in january to march, and another level in april until december. So if month is more than or equal to one and less than or equal to three sounds right to me.
sorry, my bad
No problem, appreciate your help a lot
ok, so I do not need to use the AND
no, you don't need the and
but it might be more readable, so no worries if you want to use it
ahh, yes that is similar to what I am used to from some other languages I have been working with earlier.
@steel swift I converted your message into a file since it's above 15 lines :+1:
it is in the first if-sentence with NORMAL I am unsure.
@steel swift I converted your message into a file since it's above 15 lines :+1:
that first if statement will never be true, as the template will not be rendered in such cases because of your availability template
I suspected that, so I can remove that part of the sensor as as you say it will not be rendered if its not available?
yes, but the sensor will of course never report NORMAL then
oh wait, it will, there is a 2nd NORMAL
personally, i'd reorganize that a bit to make it easier to maintain, and you had an extra endif
{% set flytende_pris = states('sensor.strompris_med_nettleie') | float %}
{% set weekday = is_state('binary_sensor.workday_sensor', 'on') %}
{% set avg_price = state_attr('sensor.electricity_price_hjemme', 'avg_price') | float %}
{% if 1 <= now().month <= 3 %}
{% set avg_price = avg_price + iif(weekday, 0.3346, 0.2646) %}
{% else %}
{% set avg_price = avg_price + iif(weekday, 0.4014, 0.3314) %}
{% endif %}
{% if flytende_pris < avg_price * 0.6 %}
VERY_CHEAP
{% elif avg_price * 0.6 <= flytende_pris < avg_price * 0.9 %}
CHEAP
{% elif avg_price * 0.9 <= flytende_pris < avg_price * 1.15 %}
NORMAL
{% elif avg_price * 1.15 <= flytende_pris < avg_price * 1.4 %}
EXPENSIVE
{% else %}
VERY_EXPENSIVE
{% endif %}
Have been working some hours, have some knowledge and I am learning a lot along the way. With knowledge comes the ability to do things simple. I fully agree that this one is much cleaner, but I am still satisfied I managed to get it working in the end. I got rid of the extra endif somwhere along the road. I struggled a lot with this ending up with finding that I prsented the datas in a template card. There I got an error when sensor was unavaiable or unknown, and I blamed the sensor. When I put default in the template card, I got rid of the errors π
that's perfect, exactly what I needed, thanks!
In a general meaning, when you want to avoid anomalies in a sensor (like calculated, or a motor / fridge starting), what's the "best" way?
Send 0 ? Send the previous State? Make it unavailable? Send a median value based on n last samples?
Thanks!
unavailable
thx @mighty ledge - but why is it preferred?
because you don't want bad data in your data
yes, but then there's "some holes" in your data... but this is still better than for instance a median value (which would leave no hole)?
I mean especially if you're making a derivative or an integration later on this data.
the holes don't impact the derivative
OK, thank you!
I have a list of sensors and I wanted to build an automation to cover them all when they aren't getting updated via my SDR-RTL process I have. I was trying to be smart and use a template trigger in Automation but not sure how to craft the proper template for this and stuck.
Right now I have a loop where I can get all the sensors I want but not sure how to use that variable in other functions in the for loop like so
{% for i in states.sensor|selectattr('entity_id','search','_(planter|sink|sensor)_rssi')|map(attribute='entity_id') %}
states.{{ i | e }}.last_updated
{%- set ts_event = as_timestamp(states.{{ i }}.last_updated) %}
{%- set ts_now = as_timestamp(now())|round(0) %}
{%- set ts_delta = (ts_now - ts_event) %}
{{ ts_delta | round(0) > 3600 }}
{% endfor %}
I am able to get for example sensor.deck_sensor_rssi returned as i but trying to use it inside of the other logic I have isn't working. Also if more than one failed and I used this logic in an automation template trigger could I still use the {{ trigger.to_state.attributes.friendlier_name }} in the automation?
you're nesting templates
I'm not sure what this line is doing there:
states.{{ i | e }}.last_updated
there are several issues there
this returns a generator, and you want a list:
states.sensor|selectattr('entity_id','search','_(planter|sink|sensor)_rssi')|map(attribute='entity_id')
you need to add |list
for works on generators
And what is that i | e supposed to do?
The loop is not needed though, seems like he wants to find all entities updated in the last hour
it's currently output the time deltas, but yeah
i | e is jinja for escaping
{{ states.sensor |selectattr('entity_id','search','_(planter|sink|sensor)_rssi') | selectattr('last_updated', '<', now() - timedelta(hours=1)) | map(attribute='entity_id') | list }}
Something like this
That worked perfectly @marble jackal ! Thank you so much
no, that's a filter
keep in mind that e is also overwritten as a function to output e (math)
i.e use escape over e because your milage may vary in HA (when using it as a filter)
This is only a HA thing, use e to your hearts content in jinja outside HA to escape things
it's a stupid alias for escape
fyi
I never even thought of an e filter meaning "escape"
just like == is an alias for eq
yeah, it's odd
TIL
there's only 2 aliases for filters
e and escape, d and default
all the rest are for math stuff
but, when you think about where jinja came from, it makes sense that e is an alias
it was originally created to help w/ html and presenting forms
which use escape alot
that part in that line was certainly confusing, but it sitting there without any decoration was also weird
yeah, I think he was just using it to see what the line of text would be, then he tried to use it in the decorated line later
makes sense if nesting was possible
So I get this error, and I have searched and searched but cant find where this template are placed. Is it possible to find in some way? ````
homeassistant.exceptions.TemplateError: ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ (states('sensor.snittpris_med_nettleie_2') | float * 100) | round(2) }} ΓΈre' but no default was specified
the state of sensor.snittpris_med_nettleie_2 is unknown and you didn't provide a default for float, such as float(0)
Use the Visual Code Studio add on which allows you to search in your entire config
Thank you, I do not have a nettleie_2. I did as two sensors where quite similar. But nettleie was deleted and nettleie_2 renamed to nettleie. The sensor I have now, do have a float(0)
I can search from file editor as well, but something can be hidden in templates card inside DD, but havent found it there either.
Did some changes again, and hope I found them now. This is driving me crazy.
Is there an easy way to make two lights match each others states?
Example:
I want my hallway light to turn on/off if I turn on/off my chandelier.
I want my chandelier turn on/off if I turn on/off my hallway light
hi,
is there a way to reuse this example template light i just did for my bed room.
i have 10 rooms where i want to use the same logic but dont want to copy and paste the code. somebody has a idea how i could do this?
Use yaml anchors
But you need to be able to get the source light from the properties of your template light
Hi,
knows anyone's if it possible to send one notification to my phone with the ups battery status ?
actually i want to send the hass one notification when the power is off and who many battary i have
*i have conect the ups with usb cable and i use the nut server for conecting
Yes. Trigger the automation based on the UPS status (mine has the status "On Battery" when power is cut)
and as action send a mobile app notification. In the message you can use the template {{ states('sensor.ups_battery_charge') }} (you would have to modify the entity name according to your NUT integration) for the UPS percentage
thanks my friend, its workings
I have this zigbee sensor: sensor.smartplug1_energy which I unplugged / don't use for reasons.
I make a total of 20 of those smartplugs to get the total energy.
Unfortunately, I have to manually remove this specific plug 1 in the calculation, because if not, HA doesn't know it's unavailable and always return its previous energy value (4 days ago).
Is there a way to detect if it's really available/plugged?
https://snipboard.io/7PCw6u.jpg
If you show the calculation template, someone might know a solution
@mellow sigil I converted your message into a file since it's above 15 lines :+1:
But I understand the fact the energy value remains constant, so its derivative == 0 (on the constant part), so it's not problem for a derivative.
I'm maybe more interested to know how to detect it's plugged or unplugged, because neither none, unknown or such test work, it's still available for HA.
Ohhh I think I've got it.
Those plugs do NOT show availability because availability is disabled!
https://snipboard.io/AiNgOu.jpg
So it seems I've to set this somewhere as it's said here:
https://www.zigbee2mqtt.io/guide/configuration/device-availability.html#availability-advanced-configuration
So all I've to do is set this in configuration.yaml?
// Optional: Enable the availability feature (default = false)
availability: true
OK - sorry to have bothered π¦
Hey all. Trying to create an automation using team_tracker that triggers if the numeric state score attribute changes from 0 and then each subsequent change above 0. I believe the best way to do that would be via a value_template however Iβve no idea where to start with that.
ha-teamtracker's wiki has an example
alias: Automation - Team Score
trigger:
- platform: state
entity_id: sensor.team_tracker
attribute: team_score
condition:
- condition: template
value_template: >-
{{ trigger.to_state.attributes.team_score | int >
(trigger.from_state.attributes.team_score | int ) }}
action:
- your-action-here```
@bright quarry I converted your message into a file since it's above 15 lines :+1:
anything wrong with this? compatible with new mqtt format? my mqtt stuff recently stopped working after an update and idk why.
Thatβs one hell of a template light. Canβt wait to check that out. Thanks
is this ok:
- service: media_player.select_source
data:
entity_id: >-
{{ speakers }}
and when I call it for variable
media_player.hallway_ceiling_speaker,
media_player.bathroom_ceiling_speaker, media_player.office,
media_player.office_shelf_speakers
It will probably work, but I would enter the speakers as a list
Oh, and your service call needs an actual source setting
As service data
how check if a string state_attr('media_player.alfred','media_content_id'))
endsWith RADIO538.mp3
a regex to the resque
{{ 'foobar'.endswith('bar') }}
how you add to a list? just like [media_player.bedroom_ceiling_speaker, media_player.hallway_ceiling_speaker] I need only parenthesis here?
Or
speakers:
- media_player.bedroom_ceiling_speaker
- media_player.hallway_ceiling_speaker
- media_player.bathroom_ceiling_speaker
- media_player.office
- media_player.office_shelf_speakers
nice! thanks!
my state is showing 'null' so I have:
{%- if state_attr('sensor.alexa_last_called', 'Entity') == '' -%} as
{%- if state_attr('sensor.alexa_last_called', 'Entity') == 'null' -%} doesnt work
Is there another way to do it just in case the sate is blank and not null?
hi,
i wont to send to my phone one notification about the load and battery from ups. The code is this one
"service: notify.mobile_app_S10
data:
title: Ups is on battary
message: >-
The battary is {{ states('sensor.ups_battery_charge')}}%
The load is {{ states('sensor.test12')}}W'
the problem is on my phone the notification is in the same line, may know anyone how i can do this ?
The battary is {{ states('sensor.ups_battery_charge')}}%{{ '\n' -}}The load is {{ states('sensor.test12')}}W'```
{{ '\n' -}} makes a new line
it's work, thanks you
Trying to pull the list of unavailable lights from a template sensor. The sensor works, but the entities are tucked away behind the sensor's attributes
what does that mean?
sensor:
- platform: template
sensors:
unavailable_lights:
unique_id: '0a7476cc-d6c1-40ba-8ae1-606518c3497f'
friendly_name: Unavailable Light Entities
value_template: >
{{ states.light | selectattr('entity_id', 'contains', 'light.bulb_') | selectattr('state', 'in', 'unavailable') | list | length }}
attribute_templates:
entities: >
{{ states.light | selectattr('entity_id', 'contains', 'light.bulb_') | selectattr('state', 'in', 'unavailable') | map(attribute='entity_id') | list | join(', ') }}```
The sensor itself is working fine. In template editor, I'm triying to retrieve the list reported by the sensor. I'm currently doing : {% set entity = "sensor.unavailable_lights" %} {% for item in states.sensor %} {{item}} {%- if loop.first %} entities:{% elif loop.last %}{% else %}{% endif -%} {% endfor %}, but that's reporting everything, not just the unique_id of the devices
for item in states.sensor.unavailable_lights.attributes.entities seems to be returning the names as strings, which I can work with
yeah, the better way is just state_attr('sensor.unavailable_lights', 'entities')
and if you remove the |join(', '), it just stays as a list that you can iterate on
I guess 'entities' doesnt count as the name. TypeError: state_attr() missing 1 required positional argument: 'name'
?
If I run it by itself: {{ state_attr('sensor.unavailable_lights', 'entities') }}, it returns that type error
which I understand to mean sensor.unavailable_lights doesn't have an attribute field named 'entities'
does it?
the sensor was pasted above, to me it does
it just returns null for me if the attribute doesn't exist
I certainly don't get that error message
that just indicates that you didn't call that function correctly
okay, that's odd, you're entirely correct
this returns that error: {{ state_attr('sensor.unavailable_lights') }}
Hello everyone,
I am getting the error message TemplateRuntimeError: cannot assign attribute on non-namespace object for
{% set area = states('input_select.apexcharts_dropdown_areas') %}
{% if area == '-- - --' %}
{% set ns.list = ns.list | unique(attribute='entity_id') | list %}
{% else %}
{% set ns.list = ns.list | unique(attribute='entity_id') | selectattr('entity_id', 'in', area_entities(area)) | list %}
{%- endif %}
The input_select contains strings. Would someone maybe help me understand where the issue is?
You didn't actually create a namespace, you just started using ns
Like this guy: #templates-archived message
You don't actually even need a namespace there
Oh no, so simple
I keep forgetting that you cannot just use a namespace or an array or an object, you always have to initialize them first.
If an attribute doesn't exist, none is returned (which is shown as null in devtools > templates if it's the only item
none is not the same as an emtpy string ('') or the string "null"
You need to check for {% if state_attr() is none %} using the test none or {% if state_attr() == none %}
Hi, I want to check if a state change of a switch was triggered by an automation or external (button, physical,..). Using the context.* does not work. Since parent_id is alway set (and changing). And user_id is never set.
Hi, {{ strptime(state_attr("sun.sun", "next_rising"), "") }} errors out.
I'm trying to get this rest endpoint working, its a json output of my ISP's disruption page
sensor:
- platform: rest
resource: "https://grm.glasnet.nl/api/getNotices"
name: glasnet_disruptions
value_template: "{{ value_json.storingen }}"
I know the current output but dont know the output when there are no disruptions
i also know that if there are multiple it just adds one to it within storingen.
How do i parse this in a way so i can get a tile with all disruptions and mabye a page for the updates
the endpoint is publicly accessable
Hey there. I'm using a template to check the existing volume level of media player, however I'm running into an issue because sometimes the "volume_level" attribute doesn't exist. Is there a way of testing to see if the attribute exists before continuing?
{% if states.media_player.virtual_study_alexa.attributes.volume_level %} is my template... I thought that would work, but it doesn't..
Instead I get WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'volume_level' when rendering
You should use state_attr('media_player.virtual_study_alexa', 'volume_level')
that will return none instead of an error when the attribute doesn't exist
and is one of the reasons why this warning is in the docs
Ok! THANK YOU! That worked!
- if:
- condition: template
value_template: "{{trigger.event.data.devicename == "upbath-vanity"}}"``` This is wrong, but I don't know how to make it right. `devicename` is a field sent by an event, I want to perform additional actions if a specific device sent the event
Got it working to this point it now says the service that has the issue and some attributes but not sure it will show it for all of them if there multiple
Current status ```
- platform: rest
resource: "https://grm.glasnet.nl/api/getNotices"
name: glasnet_disruptions
json_attributes_path: "$.storingen[:1]"
json_attributes:- regio
- netwerk
- diensten
value_template: "{{ value_json.storingen[0].diensten }}"```
but not sure how to do it better
New question. I have a variable labled "new_volume". I am trying to use it to set the volume...
volume_level: { new_volume | float }
However, I am getting error saying: expected float for dictionary value @ data['volume_level']
I have it set to float, so I'm not sure where I am going wrong with this one π¦
Without testing it I would guess you are missing the second curly bracket around the template
volume_level: {{ new_volume | float }}
and the quotes around the template π
Yep. Those were it π Thank you both!
Wasn't sure about those anymore. Don't they usually convert it back into a string?
if you don't add them, it will be interpreted as a mapping
you'll always need quotes around templates
that tells the yaml that the field is a string and it should remain a string
we then take that string and analyze it as a template
Now that you are saying it... memory kicks back in π
One line templates with " - multiline ones without
That's what I meant
those are essentially indicators to yaml that say "the next lines that are indented are part of this field and this field is a string"
the |- or >- the minus just removes leading whitespace
which is 100% meaningless for pretty much everything we do in HA
because the template algo strips leading and trailing whitespace
In markdown cards it matters
whenever you see someone use the -, it means they don't understand what the tempaltes do
yes, markdown is the only place it matters
I tried to spell this out in one of the pinned posts on the forums
not sure where it is anymore
TBH, there is a difference between > and |, but I can't remember. I'm sure it's an easy google
| and > can make a difference, eg when sending messages
IIRC, it was meaningless to HA
Now that the markdown is working as I want (at least I hope), it will not be touched again. π
| leaves newlines in
ah
message: |
this
will
be
5
lines
so > must convert them to spaces
Yah, I'm sure there is
There is also a teacher at Hogwarts dedicated to it 
My issue w/ yaml tutorial sites, is that they never cover anchors properly
none of them show this, which I guessed at one day randomly and it worked
platform: state
<<: &declare
entity_id: sensor.xyz
state: "on"
it's the most used anchor for me, due to the nature of HA and it's rigid validation structure
yes, that one is nice, never saw <<: on yaml websites
exactly
it's basically "merge this dictionary into this other dictionary"
but, they only show the use of it
i.e.
<<: *use_anchor
...
they never showed that you could use that to delcare the anchor
before I knew about that one, i had anchors for each key
exactly
same here
then someone asked on the forums and I played around with it for a couple of hours
best discovery ever
I saw it one of Marius' configs he shared π
interesting!
You remember which one?
I wish I found that sooner, I only discovered it a few years ago
I never look at other peoples config, I probably should more often
@quick jasper sorry for the delay response thank you this will work
it was more recently than a few years ago.. I think I added it to my config more like a few months ago..
yea i dont get this.
trying to make unknown amount of entities based on the json api is harder than i expected haha
well crap so i would have to make a intergration to get the thing i want working
It looks like my automation isn't handling the list it's being given.. ervice: select.select_option data: option: Always Off target: entity_id: '{{ resets }}'
Error: Template rendered invalid entity IDs: select.craftroom_relay_config select.frontporch_relay_config select.diningroom_relay_config select.officeceiling_relay_config
if you want a variable number of sensors based on the incoming rest data, yes
i got rest working atm atleast so i can get the current disruption
aah okay, this is going to be more of a pain than i expected haha
if you have a static number of entities, then no, you can do it w/o a custom integration
yea its variable, its a json api from my ISP, with all their disruptions listed in it
if you just want to get 1 sensor based on information in a dynamic list of data, then yes you can do that too
that could work to, i'm only trying to get a certain list of data from the data
i wouldnt mind having it in 1 sensor
might be nicer to
my main goal was if no disruptions: no disruptions
and for each if there are, region, service, network, status
post the data
Link to data fine, or a dump fine?
link is fine
yes
k
regio is region
netwerk is network
diensten is services
details.status is status
atm i got one sensor with 3 attribues working but i dont know how it will be if there are more entries in the json
as untill yesterday it was this but x3
there will be
but you can make a list for the attributes
but you'll need to make template sensors
i.e. 1 rest sensor, 4 template sensors
one per data i want correct?
mabye a 5th one, but that should easy to be added i think
detail.gebeurtenis to also list what is wrong
also thank you for helping me, I'm a complete noob in this
I did something like this, but it was with a card to display severe weather alerts, if that is of interest
I didnt save the data to sensors, because the data would be dynamic
https://github.com/deadlypantsd/severeweather (just in case you want it)
@serene tiger Use this for your rest sensor:
rest:
- resource: https://grm.glasnet.nl/api/getNotices
sensor:
- name: Outages
unique_id: outages
value_template: >
{{ value_json.storingen | length }}
state_class: measurement
unit_of_measurement: Count
json_attributes:
- storingen
Then...
Well actually
do you want to just have the closest outage?
or if it's just for notifications, that 1 sensor should do your work
and I can hlep with anotification message
if you want this stuff in the UI, then we can make a static number of outages, lets say 5, and go from there
Preferably all was thinking of a card, so also looking at @languid pendant's card
ah, we could use autoentities to get the information out
it's a custom card that would allow use to dynamically create UI elements that display the info
w/o having the sensors
yea looks that way, currently trying to read the yaml to see how to use it
the card he linked
yeah, you don't need that
that's custom button card w/ a bunch of stuff
ifyou just want a dashboard w/ outages, you can do this w/ auto-entities and the sensor above
That card uses autoentities. I just put it behind a conditional card and in a browsermod pop up
atm used a markdown card as i had something similar for packages from 17track
but auto entities might be better yea
well it would just allow you to have pretty separate cards
markdown also has the ability to add icons and such to it
custom button card allows you to make a specific card that looks and feels how you want it
but it's complicated
yea that is overkill for me haha
Got it roughly working https://prnt.sc/3T9Tj1yb97MD
when i'm home i will try to work it out into into a better way, thank you for the help with the sensor @mighty ledge
@silent vector I converted your message into a file since it's above 15 lines :+1:
Oops
How would I create a dictionary with namespace in a loop.
I can create this
foo:
sh: 'ds'
santa:
zha: 'zva'
But it seems like it's not possible to put that under 1 key
all:
foo:
sh: 'ds'
santa:
zha: 'zva'
you cant
make key value pairs and then use dict.fromkeys
Yeah I have {{ dict.from_keys(ns.fields) }}
Dictionary updates can only do 2 sequences though
I have 2 separate sets adding to ns.fields
the value for a KVP can be a dictionary
Oh as in
{% set ns.fields = ns.fields + [('all', {})] ?
if that's how you want to do it, yes
The challenge is I'm not sure how to make the dictionary all go under 1 key all as I have
2 different sets adding to ns.fields because it's in a loop.
hello, i'd like to get the decimal part of a float in a template. Is there a nice method to get this ? and also I only want to have 2 digit (i.e. 4.1 -> 10 or 6.2355 -> 24)
Figured it out
just add it to a dictionary after
set x = {'foo': dict.fromkeys(...)...
Yeah I did
{{ {'all': dict.from_keys(ns.fields) } }}
{% set x = 2.1367 %}
{{ x | round(2) - x | int }}
seems so simple π thx
That will give 0.14. based on your example you might want to multiply it
FYI...
{{ x % 1 }}
Or do that
Hehe, I already thought it must be possible with modulo.
lol yah, it's so simple you wouldn't think it would work
ok here is my line {{ (states('sensor.out_pool_sensor_ble_yc01_temperature') | float / 4) % 1 }} but return value is 0.625 for a start value of 3.625
Yes, that's what I already mentioned, you need to multiply with 100 (and then round it)
oops sorry I've missed your comment π¦
make sure to use parenthesis
ok guys, i know i just stop finished to be ill, but {{ ((states('sensor.out_pool_sensor_ble_yc01_temperature') | float / 4) % 1) * 100 | round(0) | int }} return 62.5 and not 62
Anyone have good code for a esp8266 with single relay and ultrasonic sensor, I have everything wired up. just need a good front end button card
How does that relate to templates in HA?
i'm sitting on a script with variables. but if i paste the variable with templating at the end of a String it will be parsed with simicolons:
Script: media_content_id: media-source://media_source/local/'{{media_to_play}}'
output: media_content_id: media-source://media_source/local/'fantasy sms.mp3'
how can i fix this?
is there like a script help place?
getting bounced around channels...
Yeah, you'll need to be more clear about what exactly you want
its really kind of got to do with everything
but here goes
I built a esp8266, with esphome to trigger a relay, and report status using a state text binary sensor.
this all works, but I need some front end help to figure out how to make it somewhat close to the cover entity
I liked the way MyQ looked in HA but the api can go pound sand
You make it a cover entity in esphome which is #diy-archived or their own discord
a cover entity ahhh okay cool
I will take a look at diy
so I have a text_sensor can it be used for cover value?
Did you ask over on the separate ESPHOME server?
it's not a channel here, it's a completely separate discord server
does it matter what I am using in the backend?
I am now on the front end asking a template question
in templates...
this was an old question and general, incase anyone had a quick link
ok, I wasn't sure because it seemed like you arrived here assuming this was the esphome channel
Frontend is in #frontend-archived
so using the cover template and asking about how to set up the value portion of it is frontend?
okay Thanks! I'll try another channel π
You just said you're on the frontend
this channel is only for jinja templates, if the value portion requires a jinja template, you're in the right place
sounds good thank you
i'm sitting on a script with variables. but if i paste the variable with templating at the end of a String it will be parsed with simicolons:
Script: media_content_id: media-source://media_source/local/'{{media_to_play}}'
output: media_content_id: media-source://media_source/local/'fantasy sms.mp3'
how can i fix this?
π€¦
is there a way for me to get a device sensor from a different entity on the device? e.g. I'm trying to find and read sensor.upstairs_east_left_window_ip when given light.upstairs_east_left_window
@fading stratus I converted your message into a file since it's above 15 lines :+1:
so you want to do what? provide the IP or the light to them?
I would like to have a single script i can provide the list of light entities for easier readability
ok, so...
{% set entity_id = light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | first | default('') %}
{{ states(entity_id) }}
where light is the vairable you put in from the script
if light is going to be a list, then it would need to be adjusted
Yeah, I'll handle looping it - I didn't realize you could traverse the device ID like that. I just don't understand the templating, lol
thanks, now to understand it, haha!
just copy/pasate this
{% set light = 'light.cabinet_wled' %}
1
{{ light | device_id }}
2
{{ light | device_id | device_entities }}
3
{{ light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | list }}
4
{{ light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | first }}
5
{{ states(light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | first) }}
{% set entity_id = light | device_id | device_entities | select('search', '^sensor(.*)_ip$') | first %}
{{ states(entity_id) }}
in the template editor
shows you what it's doing
but you have to change the light
in line 1
Hi all, I am using a DMX addon for HA and they have you create the devices/entities in the configuration.yaml file. I need to create 24 fixtures with 9 channels each. They all have the same channels but just need to be incremented. Is there a clean way to do this in the configuration.yaml file or programatic way?
@vestal crater I converted your message into a file since it's above 15 lines :+1:
my state is showing 'null' so I have:
{%- if state_attr('sensor.alexa_last_called', 'Entity') == '' -%}
as
{%- if state_attr('sensor.alexa_last_called', 'Entity') == 'null' -%}
doesnt work
Is there another way to do it just in case the sate is blank and not null?
not defined doesn't work for some reason
is it possible to set an icon color through a template sensor?
If the card you're using supports templates for the color, you can use any entity
does anyone have experience with nodered JSONata templating?
I'm trying to get frigate to telegram notifications working via nodered
{
"message": "",
"data": {
"photo": {
"url": "https://HASSURL/api/frigate/notifications/{{payload.after.id}}/snapshot.jpg",
"caption": "Activity detected in the garage. Here is a photo.",
"timeout": "120"
}
}
}
Trying to filter a list of matching results from a state engine query: {% set bulb = ["diningroom","livingroom"] %} {{states.select | selectattr('attributes.options','defined') | selectattr('entity_id','contains','_relay_config') | selectattr('entity_id', 'contains', bulb) | map(attribute='entity_id')}}
state engine reports TypeError: can only concatenate list (not "str") to list
How can I end up with a list of entities to perform actions?
My first thought was to use a for item in bulb, but that doesnt return a list, just a bunch of strings
there are 2 quotes before _relay_config
typo in discord, sorry
and you need to add | list at the end, otherwise it's still a generator
you can test the template in developer tools > templates
oh wait, I see where it goes wrong
use this:
{% set bulb = ["diningroom","livingroom"] %}
{{
states.select | selectattr('attributes.options','defined')
| selectattr('entity_id','contains','_relay_config')
| selectattr('entity_id', 'search', bulb | join('|'))
| map(attribute='entity_id')
| list
}}
or
{% set bulb = 'diningroom|livingroom' %}
{{
states.select | selectattr('attributes.options','defined')
| selectattr('entity_id','contains','_relay_config')
| selectattr('entity_id', 'search', bulb)
| map(attribute='entity_id')
| list
}}
ahh, it must have been the `| join('|') I was missing
oh, that's a whole statement - bulb | join('|')
yes, it converts your list to the same string for bulb in the 2nd version
the search test allows regex as input, and in regex | is or
That's basically what I wanted, to perform selectattr('entity_id','search',bulb) with both items
I use search instead of contains, contains doesn't allow a list as input
I thought contains would be faster than search, but I have no proof, just a guess
but you can not use contains here, as you want to check for 2 values
you were checking if a string (eg sensor.foo_relay_config) contains the list ["diningroom","livingroom"]
which resulted in your error
ahh, gotcha
@lethal bison you can do it in one search filter if you want
or maybe not, at least not with my regex knowledge π
found it:
{% set bulb = 'diningroom|livingroom' %}
{% set search_string = '(?=.*_relay_config)(?=.*('~bulb~'))' %}
{{
states.select | selectattr('attributes.options','defined')
| selectattr('entity_id', 'search', search_string)
| map(attribute='entity_id')
| list
}}
is there a tidy way to put default values of 0 into these sensor values, so the sum still works if any of the data is missing?
{{ [
states('sensor.solis_daily_grid_energy_purchased'),
states('sensor.solis_energy_today'),
states('sensor.solis_daily_energy_discharged')
] | map('float') | sum }}
Is it just to put float(0) after each states call? Or can I add another map that puts in default(0) at the end?
(I'm having trouble testing using the developer tools template feature, because I can't generate UNKNOWN input values reliably... is there a trick to that?)
@sacred haven map('float', 0)
btw, you can do:
{{
[
'sensor.solis_daily_grid_energy_purchased',
'sensor.solis_energy_today',
'sensor.solis_daily_energy_discharged'
]
| map('states')
| map('float', 0)
| sum
}}
ooooh thx! this is great advice
one small issue to banging around on forum threads etc is it's easy to fall into outdated or suboptimal habits
yes, and 2023.11 will bring new templating stuff
oh cool! looking forward to that then π
I am having fun with templates today; I want to show a Mushroom Chip card on the dashboard with a little alert if the UV value is over 1.5, but not otherwise. Here's where I'm at:
- sensor:
- name: "uv_level_if_above_threshold_for_notification"
state: >
{% set rounded_val = states('sensor.current_uv_index') | float(0) | round(1) %}
{{ rounded_val if rounded_val > 1.5 else 0 }}
(Yes, I called it uv_level_if_above_threshold_for_notification. I was a Java coder by trade and that's how I name things! srynotsry)
what is your goal here? If you want to use it in a conditinal card, you should create a binary sensor
or wait until next wednesday, because then numeric states can be used in conditional cards
oh wait, mushroom chips can be conditional out of the box
I just posted in #frontend-archived, funnily enough. I want to feed it into an auto-entities (with a "state>0" filter), then feed the auto-entities into a Mushroom chip card. So I get a compact row of "things HA thinks you need to know about right now." It'll also have light groups that are on.
My current config uses normal condition mushroom chips, but it's tedious to maintain / hardcode the list of everything I want to show. Inserting auto-entities is going to clean that up.
but for what do you need the sensor then?
I only want to show the chip when the value is above 1.5, and I also want to format the chip value to prepend a string (I omitted this above). So the template I'm using is actually
{% set rounded_val = states('sensor.current_uv_index') | float(0) | round(1) %}
{% if rounded_val > 1.5 %}
Current UV: {{ rounded_val }}
{% endif %}
My next plan is to set some attribute on the sensor like "notification=true", then have auto-entities show everything where "notification is true" and "value is not 0/empty string"
does that make sense? it should mean, I think, that I can create sensors or helpers and have them show up in the mushroom chips automatically whenever they have anything to tell me
I would use a template chip then, not creat a sensor for it
hmmm so I concede I had not seen the template chip option, lol
(I am just kinda banging around learning HA as a I go, please bear with me, I am not necessarily taking the most efficient paths...)
thx for the pointer!
hmmm if I do that, though, I don't see how to merge it in with the rest of my chips that I want to show in the same card, that are coming from the auto-entities... I shall continue to experiment, maybe there is a way
(moved to #frontend-archived )
sorry, I drifted OT there, this isn't really templating any more
I have a humidity sensor that is significantly out of line with all the rest of the humidity sensors in my house. My plan is to make a template sensor helper that will include the math necessary to adjust it to be close to the others and use that value in automations.
When I go to create the helper, I put in {{sensor.guest_bath_humidity_old}} - 17 for the template, but it tells me that This template does not listen for any events and will not update automatically.
When I used any variation of int(states(sensor.guest_bath_humidity_old)) I get a warning of Sensor None has device class 'humidity', state class 'None' unit '%' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'int(states(sensor.guest_bath_humidity_old))' (<class 'str'>) .
Obviously, I'm doing something wrong, but haven't figured out what that is yet. Would someone please point me in the correct direction.
You need quotes around the entity id when using states()
Wow. Thanks. I have no idea how I missed that since I copied the states() from my
templates where I have a whole bunch of them (including this exact one).
Also, this would be the "proper"/most logical/"best" way of making this correction, right? Is there another way that might work better/be more in line with the way HA is supposed to work?
there's a compensation integration
although it's in dire need of some updates, the dev is super lazy for that integration and hasn't updated it in a while
typical for that guy
super typical, that lazy ass
me thinks this was directed at me. What's the name of said integration? I didn't see anything that jumped out at me when I was looking.
and me thinks this was self-referential... π€£
it's called compensation
yes, I'm the lazy ass π
Is it a default helper type that can be created from the UI? If so, I'm not seeing it. It's not listed as "compensation <anything>" in the list of helpers, and the Integration specifies that it's a "Riemann sum integral sensor"
It's not in the UI, it's yaml only
it'll never be in the UI because the UI can't handle unknown length lists
gotcha.
I've been waiting for the core team to make an element that can handle that to get it into the UI
doesn't sound to me like you're the slacker, then! π
Well, it's not really a high priority
quick-and-dirty guide on expanding a light group to expose it's members in a template?
variables:
lights_in_group: |-
{{ expand(states.light | selectattr('entity_id','contains','group_')
| selectattr('entity_id','search',(trigger.event.data.area)))
| map(attribute='entity_id')|list}}```
This works in template editor, but returns an empty list in the automation
I'm writing a template in to my configuration.yaml l,basically it calculates out certain power consumption for me but I can't find a good guide on how to set the unit type. It's defaulting to none in the template but Wh is being filled in by the front end. I want kWh. Is there not a way to set the unit in the template?
mind if i ask a few stupid questions?
No such thing as a stupid question in my opinion.
you haven't heard my questions yet
What are they?
Button-card template 'live_tile_card' is missing!
type: custom:button-card
template:
- live_tile_card
- live_tile_with_picture
name: Aurora
color_type: icon
variables:
i have the template sitting in a file called live-tites.yaml sitting the templates folder
how do i include this into my config so that the card can find the template?
i have a view of these includes going on
i tried template: !include etc etc
it tossed me an error
what do you classify it as?
none of that has anything to do with Jinja templates
it's a #frontend-archived question
some Minimalist thing, I imagine
ok ill go over there
with unit_of_measurement
Jinja that's why I couldn't find my answer I should have been looking for jinja templates not ha templates. π
Thanks!
hey guys, i'm not sure if this is the right answer but i'm trying to make an IR blaster with esphome to control my air con and one of the things with it is that the bits the air con is receiving for the speed can be calculated like so (based on what others are saying since i'm very new to all this):
speed (int) -> convert to binary, reverse the digits -> bitwise shift 4 digits left (i think from what people have told me) -> convert to hex -> get compliment
so as an example, if the speed is 4, converting it to binary would make it 0100, which reversed would be 0010
bitwise shift that and you geto 0010 0000, which converted to hex is 20, then the compliment of that is DF, and that's the info i need to send to my esp device
is there a way to do that process in a template? so the whole convert to binary, bitwise shift, convert to hex and compliment it? or should i just do a bunch of if/else statements instead?
There is a way, but Iβm not at a computer to test it out as I donβt have the calls memorized. Bitshifting is the only gotcha, it might not exist in jinja.
yeah, i can't find much out about it unfortunately
i think i might just have to make a bunch of if/else statements to get it working
If you shoot me a reminder in about 12 hours Iβll take a look at it
time zones may make that hard but i'll give it a shot π
here's an example of constructing a bitmask:
- data:
entity_id: input_number.zones_violated
value: >-
{% set orig_value = states('input_number.zones_violated')|int %}
{{ orig_value|bitwise_or(2**state_attr(trigger.entity_id, 'index')) }}
service: input_number.set_value
is there a way to convert from decimal to binary?
if so, if there's a way to convert from binary to a string, i can just do some string manipulation on it to act as the reverse bits and bit shift, then once done i could convert it to hex?
I would probably use a python_script instead
I just don't know if you need packages that aren't avaialble
that's ok, i think if i'm going into that much effort i think i'd rather just do some if/else statements
wait, there's a way to convert decimal to binary!
{{ '{:b}'.format(test) }} ```
is there something like a ternary operator in jinja? something where i can go
test == 0? 1 : 2
or similar?
maybe iif is similar
https://www.home-assistant.io/docs/configuration/templating/#immediate-if-iif
hmm - i was hoping for something shorter but that might do
thanks!
actually that looks perfect, thanks!
hey guys, is there a way to use a for loop to concat a string x times? i'm trying to take a number, say 1, and put a 0 in front of it 3 times to end up with a string of 0001, but for some reason it's not working - here's my code:
{% for i in range(0, 3 ) -%}
{% set test = "0" + test | string -%}
{{ test }}
{% endfor -%}
{{ test }}```
and the output:
```Result type: string
01
01
01
1```
You have to use a namespace
a namespace?
ah ha!
{% for i in range(0, zeroes ) -%}
{% set ns.paddedBinary = "0" + ns.paddedBinary|string -%}
{{ ns.paddedBinary }}
{% endfor -%}```
gives me an output of:
```Result type: string
01
001
0001```
thank you so much!
@steel swift I converted your message into a file since it's above 15 lines :+1:
@steel swift All your checks have not weekend in it, you just don't output anything when it's weekend
Ohh, how could I miss out on that. Thank you π
@steel swift I converted your message into a file since it's above 15 lines :+1:
Trying to add an entity to a list when that entity state is on
This works if it actually is on, but it fails when it's not:
alias: Master Bed White
sequence:
- service: light.turn_on
data:
kelvin: 2700
brightness_pct: 80
target:
entity_id:
- light.masterbed_fan_light
- light.masterbed_cans
- >
{% if is_state('light.masterbed_closet','on') %}
light.masterbed_closet
{% endif %}
mode: single```
error is an empty element in the array:
Error: Template rendered invalid entity IDs: ['light.masterbed_fan_light', 'light.masterbed_cans', '']
entity_id: >
{{
[
'light.masterbed_fan_light',
'light.masterbed_cans',
'light.masterbed_closet' if is_state('light.masterbed_closet','on')
] | select() | list
}}
@junior star 
@plain warren I converted your message into a file since it's above 15 lines :+1:
is it possible to create a sensor that contains the energy consume of a single cycle, if I have a washing machine with sensors: sensor.washingmachine.status that has "run" and "stop" to say that it is running or stop, and sensor.washingmachine.energy that contains the total consumtion in KWh? if so how? with automation or with a trigger template?
the sensor needs also to be reset on each new cycle
Probably use a modification of existing 'energy' incremental sensors, using the [stop] function as a counter reset?
I guess you mean with utility meter, but how to reset it when the sensor.washingmachine.status is 'stop'? with automation?
Would something like this work, to have a script wait until all items in list are true?```
action:
- condition: and
conditions: template- wait_template: "{{ is_state(multiple_sensors, 'on') }}"```
and a second question: Is it possible to display the members of a light group that are currently unavailable? I've tried many variations of
{{ expand(state_attr('light.group_livingroom','entity_id'))}}, but all come up empty.
A variant of {{ state_attr('light.test', 'entity_id')|select('is_state', 'unavailable')|list }}
You didn't say what you actually tried
{% set group = ('light.group_'+single) %}{{"Group = " ~group}}
{{ expand(state_attr('light.group_'~single,'entity_id'))}}
{{ "State of "+group+": "+states(group)}}
{{expand(group)|list|count}}
{{expand(state_attr(group,'entity_id'))|list|count}}
{{ expand(states.light) }}blah
{% for item in group %}{{is_state(item,'on')}}{%endfor%}```
{{ lights.entity_id }}
{{ expand(lights) | list }}```
{{ state_attr('light.group_diningroom', 'entity_id')|select('is_state', 'unavailable')|list }}
[]
after looking at the 'States' developer tool, it appears the entity_id that contains the group's members is removed if the entity becomes unavailable.
Then it's easy
@final parcel I converted your message into a file since it's above 15 lines :+1:
Is that possible please? π
yo, here's a 1 liner
{% set value = 4 %}
{{ '%0X%0X'%(15 - '{:04b}'.format(value) | list | reverse | join | int(base=2), 15) }}
or
{% set value = 4 %}
{{ '%0XF'%(15 - '{:04b}'.format(value) | list | reverse | join | int(base=2)) }}
Ah, cool, thanks so much!
You can also index into a list but this is confusing to read:
[2,1][test==0]
anyone here confident with using the calendar event start / end triggers in templates?
I've currently got a template working, but it triggers in the morning on day of an event and during, not the start and during as I'd prefer
is it a good solution or there is something better? https://community.home-assistant.io/t/measure-energy-usage-of-washer-cycle/485471/4
I have a table of oil depth against volume for an oil tank that has a slightly unusual shape making calculating remaining oil based on a sensor measuring current height non trivial. Idea is to use this to perform a lookup and conversion from height to volume. As I want to use the lookup for multiple cards and in some cases more than once for the same card is there a better option than using a custom_template for a macro and calling that with the depth to convert? (Besides writing a dedicated integration/helper)
I think I have thought my brain into a knot.
I wanted to check if the state of any entity matching the search changes from GOOD and return "true" if it does.
{{ (states.sensor|selectattr('entity_id', 'search', 'sensor.eq3_battery')|selectattr('state', '!=', 'GOOD')|map(attribute='entity_id')|list)|length > 0 }}
But my approach is too limited
- I am only getting feedback from the first entity to change state
- I should really monitor every change of state to any state that is not
GOOD, i.e. if the same entity changes fromGOODtoMediumit should trigger and then again when it changes fromMediumtoLow
Tried setting a namespace and stuff like that and creating if/else, but I think this should be possible with a one-liner like the above. I just don't see it yet π¦
You can do a couple of things -
- Remove the
> 0and just use the change in the length as a trigger - Create a template sensor and use the list itself as an attribute, then use the state of that entity as a trigger
If possible, since I am reducing working code, I would prefer not to create additional "helpers" like template sensors.
If I remove the > 0 then the template will return the count of sensors that are not GOOD, so it will not change when the state changes from e.g. Mediumto Low. It would trigger if another sensor changes state though. So it is one better than what I had π
But would it be possible to monitor that change without creating e.g. a variable to store the previous length? I did not find a mapping/piping that directly tracks changes.
You need an additional entity to trigger on, if you also want to trigger on the second entity to change
How many different states are there
4 states (good, low, unavailable, unknown)
How do you mean? You mean I need to iterate through all entities that have batteries?
No, i meant you need to use what Rob proposed
Is there also a medium state? You mentioned that above
medium was just an example because they are all caps.
Currently they are GOOD and LOW plus the system's unavailable and unknown.
Create a template sensor with a list of entities in each state in separate attributes
That's what I wanted to propose as well, you can also give every state a weight, so MEDIUM 1, LOW 2, etc, in that case a change from medium you low will also cause a state change
Any idea guys pls? π
hello, i have this code:
@quiet kite I converted your message into a file since it's above 15 lines :+1:
i want to create switch to set state form this select:
@quiet kite I converted your message into a file since it's above 15 lines :+1:
this shoudl works good?
this code is better, but change state from this switch dont works:
@quiet kite I converted your message into a file since it's above 15 lines :+1:
works better if i keep good types... i need to sue select, not input_select
That was what I am trying to avoid. If I need to create a template sensor I do not really save a lot of code compared to manually checking each state change separately.
Maybe I need to look into python scripts π€·ββοΈ
Perhaps your optimization attempt isn't worth it
The real advantage of the template sensor is that it is dynamic, if entities are added or removed, the template sensor will adjust
if you have a state trigger with a list of entities, you'll have to change that when entities are added or removed
Since the sensors will always have the nomenclature, so the template will always include all of them
I can see the hourly forecast in the UI, but can't find an entity for it in the developer tools
(can't upload an image)
That is relative. I could reduce a 50 liner to a <10 liner. And with some failed improvements I would have cut the file count from 12 to 3.
Is it crucial? No. Is the current solution poor coding? Yes.
(poor on my part because HA does not allow for a lot of things (like templating everywhere) which forces me to use approaches that I find suboptimal and cannot find a workaround that feels elegant)
{{ is_state('climate.mitsubishi_hvac', 'off') or
state_attr('climate.mitsubishi_hvac','current_temperature') >= 24 or
is_state('binary_sensor.living_room_warmed_up', 'on') or
is_state('binary_sensor.office_warmed_up', 'on') or
is_state('binary_sensor.bedroom_warmed_up', 'on') or
is_state('input_select.bedroom_status', 'Off') }}```
is there a way to make is_state('binary_sensor.office_warmed_up', 'on') only wait if it goes from OFF to ON? I don't want to continue if the sensor is already ON
is it because its an attribute in another entity instead of its own entity?
You can have lists and dictionaries (and combinations of them) in attributes
it's not part of any weather entities i can find in the developer tools
Forecasts are no attributes anymore, but retrieved by service calls
But how I can feed the sensor by this?
Create a template sensor and set the attributes: https://www.home-assistant.io/integrations/template/
yes, that was my point
Is there a way i can call Emby for a remote control card like this ?
- type: button
icon: mdi:netflix
tap_action:
action: call-service
service: remote.turn_on
data:
activity: https://www.netflix.com/title
target:
entity_id: remote.living_room_tv
hold_action:
action: none
that's something for #integrations-archived
Is not a sensor im trying to but a template card ? π
you first need to know how to perform the action
and you can't use templates anyway in tap actions
Okay make sense thanks π
but you want to perform a service call, so you need to know how it works for emby
Goodmorning! Im subtracting 2 timestamps from eachother which result in an X amount of seconds. How can i convert this into hours and minutes, so i can TTS the hours and minutes to my phone?
I tend to just TTS hours and minutes seperate because else i get a in the afternoon TTS as extra
got it:
{{ 3660 | timestamp_custom('%H', false) }}
{{ 3660 | timestamp_custom('%M', false) }}
use use the easytime macro's I made
I want to document a Template sensor I created. Apart from a screenshot, is it possible to copy the code and configuration of the sensor. I was going to copy the YAML but I created it using the UI and can't see where they are saved.
that information is likely only available in the hidden files
Or you go to the sensor's settings and select template settings. There your template will be shown.
hello everyone.
newbie here, so dont hit me too hard.
ive made and setup this "template"
- platform: template
sensors:
tempo_formatado:
friendly_name: Data e Hora
value_template: >
{% set days = ['Segunda', 'TerΓ§a', 'Quarta', 'Quinta', 'Sexta', 'SΓ‘bado', 'Domingo'] %}
{{ days[now().weekday()] }} - {{ now().timestamp() | timestamp_custom('%d/%m/%Y %H:%M') }}
its working, its shows the accurante day of the month, with all the formating i want in the template editor
But how do i add it to homeassistant so that i can go and fetch the entity "tempo_formatado" and disply its value on a simple card on my frontend? π€
if you put that in configuration.yaml in the sensor section, just add the entity to your UI
like you would any other entity
@thorny snow I converted your message into a file since it's above 15 lines :+1:
and when i try to reboot the home assistant to update / verify the file, i get
The system cannot restart because the configuration is not valid: Integration error: platform - Integration 'platform' not found. Integration error: sensors - Integration 'sensors' not found.
you have to put that template in the sensor section
you just paste that at the root level
i.e.
sensor:
- platform: template
...
make sure your indentation is correct as well when you add it properly
Ok, we getting somewhere, but now the "error" grew lol
The system cannot restart because the configuration is not valid: Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got None extra keys not allowed @ data['tempo_formatado']. Got {'friendly_name': 'Data e Hora', 'value_template': "{% set days = ['Segunda', 'TerΓ§a', 'Quarta', 'Quinta', 'Sexta', 'SΓ‘bado', 'Domingo'] %} {{ days[now().weekday()] }} - {{ now().timestamp() | timestamp_custom('%d/%m/%Y %H:%M') }}"}. (See ?, line ?).
you probably didn't indent everything together
indentation is important in yaml, make sure that all your indentations line up w/ the indentations in the documentation
tried to send a picture but it doesnt allow me !
we don't want pictures of text
funny thing is that the filed editor says its all good
post what you've tried
`sensor:
- platform: template
sensors:
tempo_formatado:
friendly_name: Data e Hora
value_template: >
{% set days = ['Segunda', 'TerΓ§a', 'Quarta', 'Quinta', 'Sexta', 'SΓ‘bado', 'Domingo'] %}
{{ days[now().weekday()] }} - {{ now().timestamp() | timestamp_custom('%d/%m/%Y %H:%M') }}
`
yes, you just indented the first 2 lines, you ddin't indent the rest with it
if the docs show
x:
Y:
Z:
when you indent it, it should still have that same waterfall look.
x:
Y:
Z:
....it really is all spacing uh?
thanks everyone, damn that was strangely hard, like the coding part was the easy one LOL
YAML is just JSON w/ spaces
that's one take π
YAML is Python for data nerds π
Good evening everyone! I've set up a switch using Wake-on-LAN and Karpach's software to power on and off my computer. Here's the template I'm currently using:
shell_command:
sleep_on_lan_desktop: 'curl http://192.168.0.52:5001/shutdown'
wake_on_lan:
switch:
- platform: wake_on_lan
mac: C8-7F-54-A0-FD-79
name: "PCBRYAN"
host: 192.168.0.52
turn_off:
service: shell_command.sleep_on_lan_desktop
Now, I'd like to turn this switch into a media player. Is it possible to create a media player template? Thank you.
No you can't turn a switch into a media player. How would a switch play audio?
@frigid vale I converted your message into a file since it's above 15 lines :+1:
Yeah that is not going to support any of the media services.
It was only for the on/off and later to add my sonos soundbar.
Also, if you must abuse the integration like that you can use: value_template: "{{ is_state('switch.pcbryan', 'on') }}"
With some single quotes in place of double π
Fixed.
Hi, bear with me, I'm new to the "inner" workings of HA.
I'm trying to get a calculation on a utility meter I created, which tracks the energy of shelly2 plugs.
The helper is working fine and showing me the daily energy consumption (needs utility meter as shelly only shows the sum and resets from time to time).
So far so good. Now I tried to use this new sensor to do a calculation to give me the respective cost:
When I try this in the dev-template i get this:
{{ states('sensor.monthly_rack') | float 0.20.98 | round() }}
{{states('sensor.rack_monthly_cost')}}
3.4472766666665997
unknown
I've entered this in the configuration.yaml:
template:
- sensor:
- name: "Rack monthly cost"
unit_of_measurement: "β¬"
state: >
{{ (states('sensor.monthly_rack')| float * 0.2 * 0,98) }}
- name: "Rack monthly cost"
why does the calculation work in the template test but not when I put this in the config (I get "unknown" on the created sensor)?
Help MUCH appreciated as I never did this. And this example will get me going with other calcs
state: >{{ (states('sensor.monthly_rack')| float * 0.2 * 0,98) }}
Notice the inconsistent use of comma and points to define decimals
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
@tribal cloak I converted your message into a file since it's above 15 lines :+1:
Something is wrong but I'm really struggling
Found it: There was one extra line I had pasted wrongly.
Now with this in the config it works:
template:
- sensor:
- name: "Rack monthly cost"
unit_of_measurement: "β¬"
state: >
{% set state = states('sensor.monthly_rack') | float *0.2*0.98 %}{{ state | float }}
@tribal cloak you can simplify this, and I would advice to add an availability template
template:
- sensor:
- name: "Rack monthly cost"
unit_of_measurement: "β¬"
state: "{{ states('sensor.monthly_rack') | float * 0.2 * 0.98 }}"
availability: "{{ states('sensor.monthly_rack') | is_number }}"
I think that's because he didn't format his code here
ah, you're right, if I copy the message it's on the next line
oh, nice that was a total guess π€£
added that thx!
@tribal cloak I converted your message into a file since it's above 15 lines :+1:
you should remove the first template: line in your templates.yaml
that one you already have in configuration.yaml
I deleted that line in the configuration.yaml, so I put it in the templates.yaml.
But the issue was just a few extra spaces at the beginning of some lines (so hard to see). YAML is super sensitive on this. Using BBEdit on Mac and it's hard to align everything
no, the line should be in configuration.yaml, otherwise you don't inlcude the file
template: should be removed from templates.yaml
Hi guys I have a rest sensor which currently spits out a string for a time in the format "15:00" - my value template is as follows:
fajr:
friendly_name: Fajr
value_template: "{{ state_attr('sensor.salah_data', 'Fajr') }}"
How do I cast this to a proper homeasistant time so it can be used in automations?
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
you can use this in a time trigger:
fajr:
friendly_name: Fajr
value_template: "{{ today_at(state_attr('sensor.salah_data', 'Fajr')) }}"
device_class: timestamp
availability_template: "{{ state_attr('sensor.salah_data', 'Fajr') is not none }}"
So I replace my entry for fajr in the configuration.yaml with the above and it will be correctly casted to a 'real time?
it will be converted to a datetime isoformat string
you can then use sensor.fajr in a time trigger
I'm not sure what you mean with a real time
Ah nice - I suppose I meant a datetime isoformatted string. Thank you, I'll give that a go
I think that did the trick because now the Fajr sensor displays as 10 hours ago (its value is 31 October 2023 at 05:07) - instead of the 05:07 string previously
@analog mulch I converted your message into a file since it's above 15 lines :+1:
Sorry I begun to feel like it was too long to post here and was going to move it to the forums
Thanks for taking a look! https://dpaste.org/AiYQs
How could I template it in an automation to trigger x mins before the datetime?
I would do that in the template sensor
for 10 minutes
fajr:
friendly_name: Fajr
value_template: "{{ today_at(state_attr('sensor.salah_data', 'Fajr')) - timedelta(minutes=10) }}"
device_class: timestamp
availability_template: "{{ state_attr('sensor.salah_data', 'Fajr') is not none }}"
then use the template sensor in a time trigger
Is there an easy way to duplicate the fajr sensor so I have a fajr_minus_ten and retain the original fajr sensor?
nothing is jumping out at me wigster
Thanks for looking. Is there some way of tracing trigger based sensors? Or do I have to just dump the variables into attributes?
That's a good idea!
You can also create an event and look at the event data
actually, you could simplify your triggers that way
currently testing:
platform: template
value_template: >-
{{ today_at(state_attr('sensor.salah_data', 'Fajr')) -
timedelta(minutes=10) }}
to retain the original value
- trigger:
- platform: template
value_template: >-
{% set midnight = as_local(as_datetime(state_attr('sun.sun','next_midnight')))%}
{{ now().minute == max([5,midnight.minute+1])}}
- platform: time
at: "00:00:10"
action:
- variables:
hour_local: "{{ now().hour | int}}"
hour_solar: >-
{% set mid = as_local(as_datetime(state_attr('sun.sun','next_midnight')))%}
{{((now() - mid+timedelta(hours=24)).seconds/3600)|int}}
T_curr: "{{states('sensor.inpo_praha_temperature')|float}}"
- event: WIGSTERS_TEMPLATE_VARIABLES
event_data:
hour_local: "{{ hour_local }}"
sensor:
...
@analog mulch ^
then your automation could just listen to WIGSTERS_TEMPLATE_VARIABLES
That seemed to have worked!
or you could just watch the event in developer tools -> events tab
Thanks again @marble jackal for all the help
no problem
Do you mean that it's possible to add actions to triggered sensors or do you mean I should create an automation for debugging?
`- platform: template
sensors:
garage_main_brightness:
value_template: {{ state_attr('light.garage_main','brightness') }}
- platform: template
sensors:
garage_main_brightness:
value_template: state_attr('light.garage_main','brightness')`
your first one is missing quotes around the template. the second is just bad syntax
i agree with the second, do you mean value_template: {{ "state_attr('light.garage_main','brightness')" }}
got you, thanks
pickup_start: '2023-11-01T16:30:00Z' is an attribute, in this case tomorrow.
How can i tell if this date is today, tomorrow, or later this week
i made something absolutely terrifing, which works.... until we go from 31e to 1e of the new month hahaha
{% set days = (now() - state_attr('sensor.whatever', 'pickup_start') | as_datetime).days %}
{% if days == 0 %}..
{% elif days == 1 %}..
... etc
this actually looks at the calendar?
because i scraped the day and compared it to the scraped day of the month, resulting in crap from 31 to the 1e
ill have a look thx!
with {{ days }} i get -1 so need to switch places
ya, sry
np! at least i can figure this stuff out nowadays
spoke to soon π¦
{{ (state_attr('sensor.tgtg_dirk_van_den_broek_amersfoort_groningerstraat_verrassingspakket', 'pickup_start') | as_datetime - now()).days }} resulting in 0 days, because its 21hours from now
but i need tomorrow
Guys, can somebody help me to create binary sensor with decoupled button on Tasmota smart plug please?
I used SetOption73 https://tasmota.github.io/docs/Commands/#setoption73 but it just send MQTT message {"Button1":{"Action":"SINGLE"}} and immediately after CLEAR
I tried this but it doesn't work
{% if is_state('binary_sensor.bathroom_button','On') -%}
{{ False }}
{%- else -%}
{{ True }}
{%- endif %}
{%- endif %}```
several things wrong with that
just fixing the syntax, this is what you'd want:
{{ value_json.Button1.Action == 'SINGLE' and not is_state('binary_sensor.bathroom_button','on') }}
oh yes.. sorry, I copy here few times modified version π
but this doesn't work as well
I think because it's checking all MQTT messages and when it receive message without Button1 it's error so my sensor failed
I also tried it with regular sensor but it had True value just for second and after no value
{% if (now().date() + timedelta(days=0)) | string == boxdag %}vandaag
{% elif (now().date() + timedelta(days=1)) | string == boxdag %}morgen
{% else %}vanaf overmorgen
{% endif %}```
seems to work now. Keeping if for now
comparing strings instead of numbers
You can subtract dates too ya know
((β¦ | as_datetime | as_local).date() - now().date()).days
i see if i can make that work. I sort of always end up going timestamp first, and go from there, because thats the syntax i sort of understand lol
got it! resulting in 1
is that result a string?
No, it's an integer
what's the right way to look up values in a dictionary if I want to find the key that is less than or equal to my lookup value?
This is what I have, and it works, but I assume there is a better way:
{% set mapping = {
-10:[67,'heat'],
0:[68,'heat'],
10:[69,'heat'],
20:[70,'heat'],
40:[71,'heat'],
60:[72,'heat'],
70:[73,'off'],
80:[74,'cool'],
150:[75,'cool'] }
%}
{% set lookup = 45.2 %}
{{ mapping[mapping | select('le',lookup)| reverse | first] }}
That's a clever way to do it
referring to the mapping variable twice seems like a kludge but if there's not a better way I'll leave it as is. Thanks
I would like to monitor my car's fuel consumption. I have VW integration in place that gives me the fuel level in %. I already created a template sensor that converts that to L.
How can I configure a (meter?) sensor that it monitor the decrease of the fuel and respect whens it's filled up?
whats the best way to turn a binary sensor on if the temp of a sensor is rising more than .5 degrees in the last 10 minutes or so
Hey, how can I make a * 10 ^ x calculation in a template?
{{ ((states('sensor.eheim_ph_control_kh_value') | float / 2.8) * (10 ^ (7.91 - (states('sensor.eheim_ph_control_current_ph') | float)))) | round(2)}}
Hi! When I am generating variables in a trigger, am I guaranteed that they are evaluated sequentially? i.e. if I define var1 from a template, then in the var2 template, var1 is already defined? Or can the order be indeterminate?
variables:
var1: "{{this.state|float+1}}"
var2: "{{var1+1}}"
I think it's {{10**x}}
works, thank you!
I'm trying to get this history_stats sensor working, but although I've reloaded the yaml and tried a few different configurations, I can't get it to appear in Developer Tools -> States or anywhere. Can anyone spot the issue?
sensor:
- platform: history_stats
name: Fred has been at work today
unique_id: fred_times_in_office_today
entity_id: person.fred_bloggs
state: "work"
type: count
start: "{{ now().replace(hour=0, minute=0, second=0, microsecond=0) }}"
end: "{{ now() }}"
Or do I need to do a full system restart or something?
No guarantee, but I have never seen this to be an issue
I use it in many scripts/automations
Yes
Ah I thought reloading All YAML config would be enough?? That works for other templates
First time you add a new integration you need a HA core restart
Ah does history_stats count as a new integration?
Yes
Thank you, I will try that
Thank you, that did work, though I was briefly confused by who Fred Bloggs was when I forgot to de-sanitise the example π
Itβs an ordered dict, it should be resolved in order
Anyone know if it's possible to split my custom sensor so it not only outputs the state, but also has some of the {{ value }} as attributes to the sensor?
you'll have to share your custom sensor and the integration it's using.
@sturdy yarrow I converted your message into a file since it's above 15 lines :+1:
that's only the template
Yeah, I am basically just re-calculating the Nordpool price to add all the extra my power provider charges me. So this template that I will put into my config is just giving me the value I need to pay per kwh. But I also have some math to add to a helper meter, but that would be an attribute if this is possible? As {{ prisTime }} is the price * my current consumption..
You'd have to duplicate the template in the attribute you want it in, assuming this is a template sensor.
So basically make two sensors, one for each value I want outputted?
No, in your template sensor, duplicate the template in an attribute
but instead of outputting the variable that is the state, you output the variable that you want
I'll give it a shot! Thank you!
@south portal I converted your message into a file since it's above 15 lines :+1:
That was the bot's fault
My message: Hi. Can someone please offer some assistance? I've been trying to control my Phillips Hue bulb with HA without a bridge via Google Home (Because you don't need a bridge to add to Google Home) I can turn it on and off and get the state but can't adjust the brightness when I try to do so I get this error in Lovelace: "Failed to call service light/turn_on. extra keys not allowed @ data['brightness']".
Script for adjusting brightness
light template
You are duplicating service on set_level
also do not post this twice
the bot did it's job and hid the post because you went over the number of allow lines for a single message.
Your script needs to use the brightness variable
how?
By using the brightness variable as an input, i.e. your script needs to use that variable in whatever it's using the brightness for
post your script
I have a script for off and another one for on
ok, well what do you expect set level to do then?
idk
alright, then remove it
if you aren't setting the brightness on the light and you don't have a script, then you don't need it
I am setting the brightness
then you need a set level script
I have a script to set the brightness to brightness, since I am using the Google assistant api I had to send a text command to Google assistant that says: set brightness of bedroom ceiling light to β{{ brightness }}β
So how do I get set-level to call that script?
you just said you only had the turn on and turn off script
I feel like I'm taking crazy pills
if you have a set level script, post it
otherwise we will continue to go in circles here
alias: Set bedroom ceiling light brightness
sequence:
- service: google_assistant_sdk.send_text_command
data:
command: Set brightness of bedroom ceiling light to "{{ brightness }}"
mode: single
icon: mdi:ceiling-light-multiple
format it please
how
google "format code discord"
` alias: Set bedroom ceiling light brightness
sequence:
- service: google_assistant_sdk.send_text_command
data:
command: Set brightness of bedroom ceiling light to "{{ brightness }}"
mode: single
icon: mdi:ceiling-light-multiple `
Your script is already using the brightness variable
so all you need to do is remove the duplicate service: input_boolean... line
I know but why do I get an error when I try to adjust the brightness?
sorry if I'm not being very clear.
again, it's because you have a duplicated service line
I've said this 2 or 3 times now
so, look at your code, read the duplication and remove the one not calling your script
np
wait the brightness adjuster works but the light isn't updating.
light in the UI?
if yes, that's expected because you don't have a level_template
and because you're going to some google device, you likely won't have that
problem solved it was becuase of the quotes around the varible because it passes the command on to google asisatnt
Grammarly does not work on discord
question for ya fellers. i tried {{ as_timestamp(states('sensor.date')) | timestamp_custom('%B') }} in the dev tools template tool thingy dingy and it works. however, when i add it to my config, and check yaml i get the error "Error loading /config/configuration.yaml: invalid key: "{"as_timestamp(states('sensor.date')) | timestamp_custom('%B')": None}"
in "/config/sensor.yaml", line 17, column 0" what gives?!
i made another one for day of the month and that works, but month doesnt
quotes where exactly?
Dude
it wont let me post an image
{{ as_timestamp(states('sensor.date')) | timestamp_custom('%B') }}
A wise man once said:
RobC:
You need to share what you added
sensors:
month:
value_template:
{{ as_timestamp(states('sensor.date')) | timestamp_custom('%B') }} ```
where would that go exactly?
my man. preciate ya, p
I have a custom template that converts a differential pressure in Pascals to Inches of Water.
I'd like to add a 5 minute rolling average. What's the best way to do this? Should I use statistics on the raw value, then convert it after?
Right now I'm doing the opposite but getting errors trying to get statistics to find the converted value.
w/ the stats integration
I think that's what I am trying?
sensor:
- platform: statistics
name: "Pressure Differential 5-Min Avg inH2O"
entity_id: sensor.pressure_differential_inches_of_water
max_age:
minutes: 5
you can also try the filter integration
which might be more what you're looking for if you want moving average
Template is
template:
- sensor:
- name: "Pressure Differential in Inches of Water"
unique_id: pressure_differential_inches_of_water
unit_of_measurement: 'inH2O'
state: "{{ states('sensor.press_diff_pressure') | float / 248.84 }}" # Conversion factor from pascals to inches of water
device_class: "pressure"
state_class: "measurement"
It's saying it can't find the sensor.
Ok let me try filter
that looks better
Doen't seem to be working - have had it running for ~10 mins (window is 5mins) and the filter entity showed up, but it has an unknown value.
Has the source sensor changed state?
That or wrong entity id
I did have a bad unit value. I removed the unit alltogether, we'll give it 5 minutes see if it updates.
I'll get a forum post going this is just way to challenging
Hi, im trying to just get the date and not the time on one of my lines that just tells me the countdown to the next bin day. And i have no idea about yaml etc.
type: entity
entity: calendar.garbage
attribute: (what to i put in here)
thanks
it's not really that hard, just post what you tried. I use the filter all the time.
I am playing around trying to create a template sensor for my met.no integration. I am currently trying to just print the current temperature in the developer tools/template. I am just seeing "weather is undefined" when I try to access weather.home
Any ideas?
Yeah that was definitely one mistake!
should I access the temperature through state_attr() with second argument 'Temperature'?
sure
{{ state_attr('weather.home', "Temperature") }} gives me None
lowercase?
you'll want to look at what is available in your developer tools/states
Yeah that's it π
And template sensors are still only defined in yaml by editing a config file?
Oh neat!
(at least for simple templates)
I'm trying to use a template to show time since a dehumidifier tank was full and my second as_timestamp is failing.
FULL for {{ (as_timestamp(now()) - as_timestamp(states.sensor.dehumidifier_tank_last_full,0) | int ) | timestamp_custom("%M", false)|int }} minutes right now that's just returning the current minutes of the hour, which means the second as_timestamp method is returning 0 because it's failing. anybody see anything obvious I'm doing wrong? the sensor is a template of its own. it looks like...
- trigger:
- platform: state
entity_id: binary_sensor.dehumidifier_1fa0_tank_full
from: "off"
to: "on"
sensor:
- name: Dehumidifier Tank Last Full
state: "{{ now() }}"```
that returns a string that looks like a date time
states.sensor.dehumidifier_tank_last_full - remember this returns the state object, not the state
yes, or use the states() function
you're missing the leading states., but you should use states('xxxx') anyway
hrm as_timestamp(states(sensor.dehumidifier_tank_last_full),0) results in 'sensor' is undefined
You can do datetime math to make that simpler, BTW. As an example:
{{ ((now() + timedelta(minutes=5)) - now()).total_seconds()//60 }}
you're unnecessarily converting everything to a timestamp and then turning that timetamp difference into a formatted string
cool, thanks. I was just working off code I found, heh
any idea on how i can sum the values of 40 sensors without blowing my brains out?
it's for a solar array - i can get the power of every panel but i have 40 of them and this feels like i'm going to die if i have to do this for each unique panel
{{ [ states('sensor.power_1_1_1'), states('sensor.power_1_1_10') ]
| map('float') | sum }}
Does anyone know how to do regex matching against entity states? The reason being, I'm using last notification entity from my phone companion app. I need to read states from notifications that will vary in content.
Context: Attempting to create conditions, within a trigger to do matching against the content of the state. Since the state is the text provided by the app notification on my phone, there isn't a set of expected responses. But I do know the responses I want to react to contain certain phrases.
Do they have anything in the entity_id which is the same for all of them, but unique for all other sensors
Or.. are they the only power sensors for that integration
There is an attribute that contains the text I need to evaluate if that's what you mean
oops you're not repsonding to me lol
only gives me
sensor.power_1_1_1
and then the other sensor would be
sensor.power_1_1_10
and so on
i thought there was a FR for this a while ago i'm not sure if they ever pulled trigger on this cuz there's gotta be a better way to add values than YAML
the only thing that is the same with them is that they all start with sensor.power
no other entities besides them have sensor.power in them in that exact context
Do they all start with sensor.power_1_1
unfortunately not.
here's a list of 5
sensor.power_1_1_1
sensor.power_1_1_10
sensor.power_1_1_11
sensor.power_1_1_2
sensor.power_1_1_3
They still all start with sensor.power_1_1
the only thing that's static is
sensor.power_1_
oh why did it do that
hm doesn't like the lonely _ _
underscore
Because it's markdown for italics
{{ states.sensor | selectattr('object_id', 'search', '^power_1_') | map('states') | select('is_number') | sum }}
no attribute lower :/ not sure what that means
it's measured in Watts if that adds any context
if that helps
Not much
What does this return
{{ states.sensor | selectattr('object_id', 'search', '^power_1_') | map('states') | list }}
AttributeError: 'TemplateState' object has no attribute 'lower'
Hello everyone, i'm trying to create a 3d visual of all the lights at home, and after I finished all the light work etc and doing the link beetwen the pictures and the light state I get a loading icon that never goes away. Anyone knows what it can be?
That last version? That can't be
Wait
2023.10.1 for sup
Sorry
{{ states.sensor | selectattr('object_id', 'search', '^power_1_') | map(attribute='state') | select('is_number') | map('float') | sum }}
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Corrected above
85.13999999999999
LOOKS RIGHT!
suns's going down so not suprising how low it is lol
ill check it out tomorrow when the suns up but thanks so much for the assist i was dreading having to code that device by device - you're a lifesaver!
Replying to my own ask as I figured it out π
I put up a post with more details - https://community.home-assistant.io/t/templates-to-convert-pressure/634816
I'm a total freaking programming newb, would anyone be willing to help me work through the language to pull specific attributes out of a entity ?
I've spent the last few hours digging through forum posts, trying to figure this out, and I think I am close, but still getting a invalid config for sensor error
I created a sensor.yaml file, which I know is working, trying to add a new platform to pull the sensor attribute using value_template and state_attr per recommendation on a github forum
You've still not really posted what you tried (specific lines of code and specific error messages). Until you do, nobody is really going to have anything much to say.
Personally I think you're probably better off trying to make a template helper in the UI, much easier than mucking about in yaml.
I didn't want to flod the chat with a bunch of code and stuff
Is the template helper the preferred route for peopel who can't navigate the .yaml well?
I actually just got the sensor to show on my dashboard, but the value is "unknown"
sensors:
sensedge_co2:
value_template: "{{ state_attr('air_quality.laseregg_air_quality', 'Carbon_dioxide') }}"
device_class: Carbon_dioxide
unit_of_measurement: ppm```