#templates-archived
1 messages Β· Page 8 of 1
And there should be an ( before states() (you close it after `float*7)
- platform: template
sensors:
airconlr01a_current_corrected_power_usage:
friendly_name: AirConLr01a Current Corrected Power Usage
value_template: >
{% if states('sensor.airconlr01a_current_power_usage') | int > 10 %}
{{ (states('sensor.airconlr01a_current_power_usage')| float*7) | round(2) }}
{% else %}
{{ states('sensor.airconlr01a_current_power_usage') | round(2) }}
{%endif %}
availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"
unit_of_measurement: W```
yes that did it π
thanks guys you have been really really extremely helpfull today, I apreciate your time π₯°
need to implement this in a bunch of places but i think i can figure it out for now, will be back if not π
Btw, now you updated, there is a complete new integration for template entities. The template integration
You are using what is now called the legacy template sensor format
yes i know a lot has changed since 2021.04 to now
when you say template integration you mean in the gui or in yaml
ok got you, just found it
ill read about it thanks π
how can I expand a domain and then search for attributes in a certain state? I tried this but it is blank:
{{expand('domain.climate')|map(attribute='preset_mode')| selectattr('state', 'eq', 'none') | map(attribute='name') | list |join(', ') | default(none) }}
attribute='attributes.preset_mode'
once you do that, the map(attribute='name') won't do anything
so if you're trying to find preset_mode eq none, then it should just be
{{expand('domain.climate')| selectattr('attribute.preset_mode', 'eq', 'none') | map(attribute='name') | list |join(', ') }}
does eq=equal?
yep
cause that still comes up blank
is preset mode equal to the word 'none'?
yes
attributes.preset_mode, sorry
yes
no i'm telling you to use attributes.preset_mode
not attribute.preset_mode
missing an s
gotcha, but still blank
{{expand('domain.climate')| selectattr('attribute.preset_mode', 'eq', 'none') | list }}, blank?
oh duh
it's not domain.climate
it's states.climate
And no expand needed then
still blank
{{ states.climate | selectattr('attributes.preset_mode', 'defined') | selectattr('attributes.preset_mode', 'eq', 'none') | list }}
shouldn't make a difference
petro's version was still missing the s
UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'attribute'
I'm assuming that it's not actually equal to 'none'
My edited version has it
that gives a whole list of the entities attributes
current_temperature=73, temperature=73, target_temp_high=None, target_temp_low=None, fan_mode=auto, hvac_action=idle, preset_mode=none,
a partial list
yes, this is blank
but the attribute preset_mode clearly says none in dev tools / states
can you show me it in the developer tools -> states page
Auh, I had to map the name π
well yeah, trying to figure out if what you're saying is true π
hardest part about support
the templatse without the map were testing, not the solution
when assisting people who only kinda understand templates π
a short question, i have a external light controller, currently controlled via nodered. but I would like to have them as a light switch in HA. is there a possibility to do this via restful api and/or templates?
That controller isn't in HA at all? You could set up an input_boolean in HA and listen for state changes in Node Red to handle that
its a aquarium led controller and currently not available to HA. this is how I currently handle it
https://www.home-assistant.io/integrations/input_boolean/, this is a toggle that you can use in HA
is there a way to check what set the last value of something? i have input_booleans that override certain automations but i have "scene"'s in the form of scripts (because real scenes are annoyingly limited) which will set the boolean themselves, i want to check if the input_boolean was changed by a script or not so i can avoid setting it in my "normal" scene if it was previously set manually
so basically i want to check if the last time 'input_boolean.override_light' for example was set by a script
You can use context
Hi again, I am still stuck. Maybe someone is willing to take a look? https://community.home-assistant.io/t/json-value-template/129626/5 I try to read values from the second instance as well....
ty
Hi all. Could someone help me please with how to select the lowest of a bunch of temperature sensors? I have created a generic_thermostat to control my heating but it's using one room's temperature. I'd like to template something to always return the lowest of them for the heating control?
I figured it out by using a min/max
another way would be to sort the list by value and surround the whole thing with ()[0] and that will get you the highest/lowest depending on which direction you sort it, i do something similar to get the latest updated motion sensor
There's also a | min and | max filter. Sorting the list and taking the first item is not needed for that
'[[[ return states["sensor.rm4_mini_temperature"].state + "Β°F" ]]]'
How can I change this template to read 76 degrees F instead of 75.96 degrees F?
Hi,
I want to add Watts and Amps entity values of 7 sonoff POW R2 devices and show them as separate entity(sensor). Can someone point me in right direction.
I have managed to do this in template editor,
now i need help to post value from this script/template into my dashboard.
Hello, how do I create a new entity using e.g. template that shall be used as a storage variable. And how do I initialize that once, upon creation.
´´´ - name: sunsp_fro_dc_0_power_to_knx
unique_id: sunsp_fro_dc_0_power_to_knx
state: "{{ 0 | float }}"
device_class: power
state_class: measurement ´´´
if I do that it stays 'state unknown'
How do I initialize that entity?
Well maybe you can tell me how to archive my goal? Can you give me a hint how it can be done?
I do not understand what you mean by "reload template entities from YAML" .
== Developer Tools
Maybe I don't understand the concept behind it? What I try to do. If sensor.A changes then check how much it changed, to then send out a knx packet if it has changed enough. So I thought I need a storage of the last sent value, compare the stored with the new value upon that change, to then update the storage and sent out to knx bus. Maybe there is another idea how something like that can be done in HA? Should I better try to do that using a python script? If so, I am willing to dig into that. But for the time I need to learn a lot...
Okay! This is what I did. There I get the entity, but it is undefined.
(the state is undefined...)
I would expect that template to have the state 0
Okay, I keep trying, in developer tools templates, but fail. How do I copy a state from entity A to state entity B?
I read that 50 times... One example please, that could help me.
But what I would probably do is:
- create an input number
- create an automation which triggers on state changes of sensor A
- compare the old and new state
- add the difference to your input number
- check the state of the input number to see if it is above the threshold
- if that is the case, send the knx command and set the input number to 0
I understand the idea. But again, the maybe simple question, how do I write to an entity (B) or "the input" number in the action part of the automation? I find no "service" that is writing a value to my sensor.B. Maybe I don't see the obvious?
{{ states('sensor.cucumber') }} will give you the state of that sensor
But do note that all states are strings, so you'll have to convert it to a number
I know, but you seem not to understand what I search. Maybe I am unable to phrase it correctly. I try to WRITE the state of sensor.B Something (this is not working!) like that {{ set 'state.sensor.sunsp_fro_dc_0_power_to_knx' = float( 1 ) }}
I keep trying in developers templates, but fail... π
No, a template will provide you with a value, you can not perform actions in it
Use the service call for the particular entity, and use the template for the value
Eg
service: input_number.set_value
target:
entity_id: input_number.apple
data:
value: "{{ states('sensor.cucumber') | int + 6 }}"
That clarifies it for me, finaly. Thank you!!!
´´´
service: input_number.set_value
target:
entity_id: sunspec_dc_1_power_to_knx
data:
value: "{{ states('sensor.sunsp_fro_mppt_module_0_dc_power') | float }}"
Message malformed: not a valid value for dictionary value @ data['action'][0]['target']['entity_id'] ????
But getting closer π
How do I do that?
I did some reading on it. HA turns out to very complicated for that. Maybe someone has a link how to do something that I do using s python script?
You can easily create an input number in the GUI
Settings > Devices and Services > helpers
Thank you for your help!
But then I will write the value to that input_number, not to where I want it, the entity that will be send out to the knx bus. Okay, then I could use send.knx once difference is reached in that input value. But, that is scalar, a fixed or variable amount of change. But not a percentage of the monitored value of sensor.A. I guess that will not solve the problem, right. I can't believe, that there is no way to write a value to the state of an entity. If not, then I think I cannot do what I want. I will have to revert back to the knx visualisation hardware. Almost all time spent no with HA will be wasted. I am disappointed...
Is there a way to use python to Read,calculate and write to an entity?
Could there be a dummy device/integration created, that is "fed" by python script generated output to do the trick?
What is the actual service call you want to use at the end
knx.send
I want to send out data from the inverter integration, but only if the value has changed by x% or if y time no update to the bus. That's all, because the knx bus gets flooded otherwise....
you mean:
service: knx.send
data:
address: 12/0/99
type: power
payload: "{{ states("sensor.sunsp_fro_mppt_module_0_dc_power") | float }}"
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), http://pastie.org/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
You need to fix your quotes
Use different quotes inside and outside the template
What exactly do you mean, which where?
You are using double quotes inside your template, and the template is wrapped in double quotes as well
Replace one of those with single quotes
Okay, what does it do if make that error? Fix like that?
service: knx.send
data:
address: 12/0/99
type: power
payload: "{{ states('sensor.sunsp_fro_mppt_module_0_dc_power') | float }}"
Yes
Before you had "{{ states(" sensor.sunsp_fro_mppt_module_0_dc_power ") | float }}"
And again, please format your code as code
Thanks, I would like to understand what it does? And, I try formatting, but I am rather new to discord. Where can I find how to format it. Your code is in nice boxes. I haven't managed to find how that is done. I am doing a steep learning curve ... π
You are using single quotes when you try to format it, you need backticks
Is there anyway to create a dictionary helper? I'd like to associate motion sensors with lights and the build automations based on that.
I'm trying to write a template which uses the last_changed time to make a decision. However, on reboot this value resets to the current time. What's the best way around this shortcoming of HA?
Is this possible? I can easily write it in pseudo code but have no idea how to make it into a script or automation.
Basically i want to create a script that takes a motion sensor as an argument. Checks that sensor in a dictonary and gets a light back and then turns the light on or off depending on the sensors state.
that's straightforward
Haha β¬οΈ difference between amateur and professional at HA π
Any clues on how to achieve it @inner mesa?
something like this:
test2:
variables:
lights:
binary_sensor.one: light.one
binary_sensor.two: light.two
sequence:
- service: light.turn_{{ states(binary_sensor) }}
data:
entity_id: "{{ lights[binary_sensor] }}"
pass in the sensor via "binary_sensor"
Does States(binary_sensor) return On if its on (motion detected)?
And i would then create an automation based on this?
you asked for a script
so that's a script
if you want an automation, it's easy to convert
it does matter
they're very different things
you don't pass a sensor into an automation, for instance
Sure i get that. I meant for my self
this part:
Basically i want to create a script that takes a motion sensor as an argument.
I don't know what you're looking for with an automation
So i would change out binary_sensor.one: light one to the pair matching? So
binary_sensor.downstairs_bathroom_motion_sensor_rorelselarm: light.hallway_lights
yes
And - service: light.turn_{{ states(binary_sensor) }} should be - service: light.turn_on{{ states(binary_sensor) }}right?
Oh ok. Trying to understand what happenes here
it will resolve to light.turn_on or light.turn_off based on the state of that sensor
Cool!
Getting: Message malformed: Integration '' not found
Full script:
variables:
lights:
binary_sensor.downstairs_bathroom_motion_sensor_rorelselarm: light.hallway_lights
sequence:
- service: light.turn_{{ states(binary_sensor) }}
data:
entity_id: "{{ lights[binary_sensor] }}"
your indentation is wrong
everything from the second line down needs to come back 2 spaces
Would i call the script like this?
data:
variables: {{ binary.binary_sensor.bathroom_motion_sensor_rorelselarm }}
a few things wrong with taht
I mean in an automation action
still, it's broken
service: script.1662915872850
data:
binary_sensor: binary_sensor.bathroom_motion_sensor_rorelselarm
Sorry.
data:
variables: " {{ binary_sensor.bathroom_motion_sensor_rorelselarm }} "
I did.
I gave you the answer
this part is completely wrong: variables: " {{ binary_sensor.bathroom_motion_sensor_rorelselarm }} "
the relevant example there is:
automation:
trigger:
platform: state
entity_id: light.bedroom
from: "off"
to: "on"
action:
service: script.notify_pushover
data:
title: "State change"
message: "The light is on!"
you added "{{ }}" and "variables:"
Ok. I think i understand, not entirely sure why my version didnt work though.
Was looking at this example:
automation:
trigger:
platform: state
entity_id: light.bedroom
from: "off"
to: "on"
action:
service: script.turn_on
target:
entity_id: script.notify_pushover
data:
variables:
title: "State change"
message: "The light is on!"```
Ah i see
as it mentinos:
There are two ways to achieve this. One way is using the generic script.turn_on service.
The other way is calling the script as a service directly.
Yeah i get it now.
still, you were trying to evaluate a template there rather than just passing the value
yes it was two different errors. Still pretty much a novice on templating and writing stuff in yaml rather than in the UI
Hi all, I'm currently running mostly the minimalist frontend. On my front page I have a number of room cards. On the card for the basement I'd like the main entity to be one of two entities, 1. the washing machine time left if it's in the running state. 2. If not, the temperature from a temp sensor in the basement. Am I allowed to put a template directly in the YAML for the page or do I have to define it as a template in one of my config files?
Current entry which isn't working.
@tepid oak posted a code wall, it is moved here --> https://hastebin.com/bovumunihi
- type: "custom:button-card"
template:
- card_room
- grey_no_state
name: Basement
# entity: sensor.basement_temperature
entity_id: >-
{% if is_state('sensor.washing_machine_machine_mode', 'Running') %}
sensor.washing_machine_time_remaining
{% else %}
sensor.basement_temperature
{% endif %}
icon: mdi:home-floor-b
tap_action:...
That card does not use jinja templates
Ah, I guess that would explain it
what's the correct syntax to provide a default timestamp? for example state_attr('binary_sensor.contact_door_front_house', 'last_updated')|timestamp(now()) where timestamp is obviously not valid i've also tried the default filter but that doesnt work if state_attr returns 'None' as that's a valid value to the default filter
{{ none|default(now(), True) }} -> 2022-09-11 12:45:24.116846-07:00
Thanks, so was just missing ", true" in the default param, i take it that tells it to act upon a nonetype
or if the type doesnt match the 1st parameter
I'm trying to get a formatted time delta to tell me how much time is left on a 3D printer. I have octoprint configured which gives me a string with the estimated date/time of completion. i can convert that to a datetime, then subtract that value from now() to get the number i'm after. However, it's returned as a timedelta object which leaves me unsure of how to take that value and then format it correctly.
ex: {{ (states("sensor.octopi01_estimated_finish_time") | as_datetime() - now()) }} returns 9:18:28.877476
I'd like something along the lines of 9h:18m to be generated
I note in the docs that there are a couple functions timedelta and as_timedelta which both return a timedelta object. I think maybe what I'm trying to do is to go the opposite direction, take a timedelta object and format it via strftime or similar. strftime notably does not support timedelta objects.
| timestamp_custom('%hh:%mm', True) i think is what you want
i'll try it!
%H:%M
Is there a good reference for old-style vs modern template sensors, along with when I can use icon_template and when I can't?
sadly, nope. it also is expecting a datetime object, which isn't a timedelta
I am trying to use an icon_template on a modern-style (I think) sensor and am gettin the error Invalid config for [template]: [icon_template] is an invalid option for [template]. Check: template->sensor->0->icon_template.
3:09:41 PM - (ERROR) config. py
{{ (states("sensor.octopi01_estimated_finish_time") | as_datetime() - now()) | timestamp_custom('%hh:%mm', True, "boo") }}
returns a booooooo
{% set secs = ((now() + timedelta(hours=1, minutes=30)) - now()).total_seconds() %}
{{ '%0d' % (secs//3600) ~ "h:" ~ '%0d' % ((secs//60) % 60) ~ "m" }}
if i leave out the default, it directly says that it doesn't think the input is a datetime, which it isn't.
@inner mesa i think i can work with that!
also i appreciate the latte art π
{% set secs = ((states("sensor.octopi01_estimated_finish_time") | as_datetime() - now())).total_seconds() %} BOOM
that was exactly what i needed and i like the approach. the "total_seconds" method was the missing link and i appreciate the help!
i feel like the mod math is just showing off lol π
Watching NFL and thinking about templating π
Anybody here using templating with auto-entities?
I think I do
I donβt remember tho
this would be easier, but I don't know why it doesn't work here: https://pynative.com/python-timedelta/#h-formatting-a-timedelta
I'm definitely not a python expert, but the way I read that it's formatting a datetime.
a datetime with a timedelta added to it, is a datetime again right?
But 20 days is also not a month, so there is more strange going on there π
oh, yeah, you're right
in any case, I'm regularly disappointed with what can be done directly with a timedelta
yeah, it would be nice if you could just format a timedelta
there is an as_timedelta function now, which converts a time to timedelta
would be nice if it could be done the other way
I am trying to create a sensor on the fly (or perform the value adjustment on the fly) whilst using auto-entities.
Right now I am using creating a sensor where state is
state: "{{ now().timestamp - states('sensor.last_restart_time')|as_timestamp(0) }}"
Any idea how I could create these uptime sensors on the fly with auto-entities so I can plot all restart_time sensors in one graph?
Hey everyone! Perhaps is there a way to create a function to prevent me from calling repetitive code? Trying to follow the DRY principle in YAML has been difficult. I'm essentially looking to make a function with two arguments in which just checks to see if two media_player entities are grouped. I have everything working as pleased but it's not very redundant.
lol
that was repetitive
there's no easy way to create a function that returns a value like that, but you can create a script that takes parameters
Hahaha my accidental dual messages or my statement, or both. π No problem, I appreciate the prompt response.
@dense tinsel posted a code wall, it is moved here --> https://hastebin.com/epanolafif
whenever you feel compelled to return "true" or "false", just use the test itself
without fully understanding the rest of it, you can replace the last several lines with:
{{ (master_ensuite_grouped and master_bedroom) or (master_ensuite_grouped and not ensuite) }}
Thank you so much, I forgot to bracket each of my statements which is what had caused me the headache.
Working code below for anyone who may want it.
https://hastebin.com/qutafoxoco
https://i.postimg.cc/63KT5D7F/Untitled.png
https://i.postimg.cc/jdnTmM2f/Untitled.png
I will be posting a write-up on all of it soon. I noticed a lot of people with the Sonos system trying to achieve exactly this with no solutions online.
How can I make this template work for any state saying the word "On"
{{ is_state(''input_select.office_status'', ''on'') }}
eg. "On - Work", "On - Busy", "On - Standby" etc?
its for a condition so if theres a way not to use a template I'm happy to use that
Your q doesnβt really make sense
{{ 'On' in states('input_select.office_status') }}
Oh, I get his q now π€£. Over looked the select
how do I make a template condition that triggers if a sensor state contains a string? my current code doesn't seem to trigger even though it seems like it should
{{ 'Chrome' in sensor.darkstar_activewindow }}
{{ 'Chrome' in states('sensor.darkstar_activewindow') }}
you need to get the state of the sensor, you are now checking for a (probably) non-existent variable
yup that works perfectly, thanks π
Hi, I've got a simple mqtt sensor with it's state being updated by node-red. The only issue is that when the MQTT broker is restarted (or for any other reason) the state_topic no longer exists on the MQTT broker I get an 'unknown' state. Is there a way to default a state for MQTT sensor? Failing that, my plan is to run an automation when MQTT Broker add-on is restarted to manually create the topic with a default. The question then is if there is a way to trigger an automation when MQTT Broker (or any other add-on) has 'started'?
Is there a way to check and see if the state is 'Unknown' and then assign a state if that is true?
You can check for the state of a sensor to be unknown but you can't assign a state to that sensor
You can create a template sensor which shows the state of the source sensor, and something else if the state of that source sensor is unknown
Is there a way to assign a default value through the configure.yaml?
Or through the configuration UI?
I'm not as familiar with MQTT.
Ah yes that's a good idea. Create a sensor on top.. will give that a go
There isn't a default value
Ok.
Can someone help me figure out how I'd make a sensor that reports back the entity name of the latest sensor in a group that changes state?
{{ expand('group.your_group') | sort(attribute='last_changed') | map(attribute='name') | list | last }}
Thanks!
That gives me the friendly name. What do i use for the entity name?
Or where do i find the info on it
Found it (by guessing) it was entity_id
correct π
Can someone help me troubleshoot this?
friendly_name: 'Motion Sensor Latest Changed'
value_template: >
{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='entity_id') | list | last }}
attributes:
last_changed: >
{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_changed') | list | last }}```
what's the trouble?
Getting an error message when checking the yaml
Invalid config for [sensor.template]: [attributes] is an invalid option for [sensor.template]. Check: sensor.template->sensors->motion_sensor_latest_changed->attributes. (See ?, line ?).
you are using the legacy template format, and need to use attribute_templates
How would a non-legacy version look?
Sure but if I'm writing new templates I should probably learn to write the new standard.
I'm guessing legacy doesn't mean deprecated, yet π±
and that the new format falls under the template integration, not under sensor, so you can't use it in sensors.yaml or anything included under sensor
I think all my templates live under the template integration.
no, what you posted above lives under sensor
sensor:
- platform: template
your_code:
You are correct.
So instead of ```yaml
sensor:
- platform: template
your_code:
It should be
```yaml
template:
- platform: sensor
your_code:
@half pendant posted a code wall, it is moved here --> https://hastebin.com/iheyibejut
template:
- sensor:
- name: friendly name (used to generate the entity_id)
unique_id: a unique id used in the backend (allows changes of icon/entity_id/name in the GUI)
state: the template for the state (value_template in the legacy format)
attributes: templates for attributes (attribute_templates in the legacy format)
Thx
can I assign a template sensor to an area?
there's a few discussions in the forums about this, but haven't found anything definite (guessing: only devices, not entities)
you can, but only using the new format
I just posted a link to the docs above, and an example
but the trick is to assign a unique_id: which allows changes in the GUI
including assigning an area
Ok i managed to move it to the new format. But the attribute does not show up under βAttributesβ in developer tools.
- sensor:
- name: 'Motion Sensor Latest Changed'
state: >
{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='entity_id') | list | last }}
attributes:
last_changed: >
{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_changed') | list | last }}```
try this:
attributes:
last_changed: >
{{ (expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_updated') | list | last).isoformat() }}
okay, any other idea why it doesn't work then π
no, I'd wager it is
I must admit I was just guessing here π
(working)
indentation is off though
at least in the posted code, but then it would not show a state as well
ah yeah It should have indentations that's probably his reason
it would create the first sensor then bitch about the remaining config
template:
- sensor:
- name: 'Motion Sensor Latest Changed'
state: >
{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='entity_id') | list | last }}
attributes:
last_changed: >
{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_changed') | list | last }}
@half pendant try it like 
When i save the yaml and check it i get an error in the log:
Invalid config for [template]: extra keys not allowed @ data['attributes']. Got OrderedDict([('last_changed', "{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='last_changed') | list | last }}\n")]) extra keys not allowed @ data['state']. Got "{{ expand('binary_sensor.motion_sensors') | sort(attribute='last_changed') | map(attribute='entity_id') | list | last }}\n" required key not provided @ data['sensor'][0]['state']. Got None. (See /config/configuration.yaml, line 235).
read our last few posts...
Iβm on an ipad and stupid discord ios app doesnβt allow to copy just the code so when i copy it will mess up the indentation
your error says otherwise
your error is the exact error we would expect if your spacing was off
Iβm not saying you are wrong. Iβm saying i cant copy paste from discord. Where is the error, i have to fix it manually
everything under name should have 2 extra spaces
you can copy text in discord
click and hold the fes's last post with the code and copy text is the 3rd option down
That copys all of the text. Not just the code.
I also can not copy text on Discord mobile, I usually copy the post and on Android some small popup shows which I can click and then take out the part I need
he only posted the template
Don't know about iOS
so copying all the code is wha tyou want to do
it will include the backticks when you copy the entire message, but that's not so hard to take out
Anyway, @marble jackal you were right. Itβs working now
Also thx for helping me with how the new way of writing templates is! Gonna start moving stuff over!
Hi, i'm trying to scrape a website (works) but I want the output filtered out because it gives too much info back. So I used a strip command and that is also working. However the strip command I use can have 2 different values 'op' or 'om'. And also that is working with the following code.
'{{ (value.split("op")[1]) }}{{ (value.split("om")[1]) }}'
But the log is showing an error BUT it does work. Is there any better code to strip this when the value can either be 'op' or 'om'.
'{{ value.split("om")[1] if "om" in value else value.split("op")[1] }}'
That easy haha thanks! π Kind of new to this
I found this code snippet online that does exactly what i want, but i want to limit it to only sensors from a specific integration (mqtt). Is there an easy way to make that work?
| selectattr('last_changed', 'lt', now()-timedelta(seconds=3600))
| map(attribute='entity_id') | join(', ') }}```
{{ expand(integration_entities('mqtt'))
| selectattr('domain', 'eq', 'sensor')
| selectattr('last_changed', 'lt', now()-timedelta(hours=1))
| map(attribute='entity_id') | join(', ') }}
@marble jackal Can you point me to where i can read up on what the different arguments does? Trying to figure out what βeqβ, βltβ for instance does in this case.
in the jinja documentation, you can find a link in the pinned posts
but eq is equal to, you can also use equalto or ==
lt is lower than, you can also use <
Ok so the argument selectattr(βdomainβ, βeqβ, βsensorβ) should read as βfilter all items where domain equals sensorβ?
yes, but you should not use these fancy quotes
Yeah sorry iβm on a swedish keyboard layout and thatβs the default
and this selectattr('last_changed', 'lt', now()-timedelta(hours=1)) compares the last time the state of the sensor was changed to the current time minus one hour
so you start with all entities from the mqtt integration, then select which one of those are sensors, and then select which ones changed in the last hour
out of that you take only the entity_id, and not the entire state object, and that you stitch together using a comma
Got it. Another question. Trying to read up on the map() function. Wanted to change it so that it keeps the entity_id and the last changed time but couldnβt make it work with passing multiple arguments to the map function.
that's not possible.
I am trying to do this for a template condition:
{{ expand('group.inside_switch_card_2') | selectattr('state', 'eq', 'on') | rejectattr('entity_id', 'eq', 'light.master_bedroom_light') | map(attribute='state') == 'on' }}
but it always says false
what are you trying to do with that?
are you trying to get a count?
== 'on' at the end doesn't make sense
I have a group that includes all switches and one light
Thx, then i can stop looking π
I want to exclude the light and see if any of the switches are on
replace the == 'on' with | list | count > 0
perfect. thanks
Can i use the selectattr() function to test if a string contains another string?
selectattr('entity_id', 'search', 'something')
Hi all,
I am missing a very simple thing here. I want to subtract two datetime helpers from each other. This works using timestamps. But after that, I want to put the result in a new datetime helper. For some reason, it does not accept the value. I thought you can just put a timestamped value in a datetime helper, but it does not seem to work. I guess I am missing a very simple thing. Does anyone here have an example for this?
I think I got it...
Is there a better way I can write this. More specifically is there a way I can recall the value of another element like this().weeks?
{% set alice_week_age = {
"weeks": ((now() - '2022-03-15' | as_datetime | as_local).days / 7) | round(0, 'floor', 1),
"days": (now() - '2022-03-15' | as_datetime | as_local).days - (((now() - '2022-03-15' | as_datetime | as_local).days / 7) | round(0, 'floor', 1) * 7)
} %}
What I have works, I would just like to clean it up
Set a variable?
My strategy for such things is generally to set a bunch of variables and then use them in the data structure
it needs a specific format for the set_datetime or whatever the service is
I'll try to need to understand jinja a bit better.
Fixed it. I forgot the quotes... duh
Looking at https://jinja.palletsprojects.com/en/latest/templates/#variables doesnt make it clear to me how to set the value of a variable
{% set birthday = '2022-03-15' | as_datetime | as_local %}
{% set weeks = (now() - birthday).days // 7 %}
{% set days = (now() - birthday).days % 7 %}
{% set alice_week_age = { "weeks": weeks, "days": days } %}
so isnt that what I'm doing with set alice_week_age? how can I access alice_week_age.weeks within alice_week_age ?
like that
yah, exactly how you wrote it
Right, you're already doing it
that wasnt working but i'll try again π
This is where I wonder where you may have copied that from, since you're clearly already using a variable
BTW congratulations with Alice being 26 weeks old tomorrow!
{% set alice_week_age = {
"weeks": ((now() - '2022-03-15' | as_datetime | as_local).days / 7) | round(0, 'floor', 1),
"days": (now() - '2022-03-15' | as_datetime | as_local).days - alice_week_age
} %}
UndefinedError: 'alice_week_age' is undefined
you can not use the variable inside itself before you defined it once
but I've already provided the easy formulas for your calulations
Thanks her name isn't actually Alice and thats not actually her birthday but she is still in the weeks/months age range π
{% set offset = now() - '2022-03-15' | as_datetime | as_local %}
{{ {'weeks': offset.days // 7, 'days': offset.days % 7 } }}
Thanks!
Even better π
Thank you!
My next calculation (after I get this one in lovelace) that I want to make is going to be Months old but on the set day of the month, so counting how old she is by months.
So if birthday is 2022-03-15
On 2022-04-15 -> 1 Month
On 2022-09-15 -> 6 Month
yea I feel like that one is going to be a far more of a challenge for me
learning experience π
you can estimate the number of months with {{ {'months: offset.days // 30 ,'weeks': offset.days // 7, 'days': offset.days % 7 } }}
but to get Actual months... no
with a lot of code
But you'll have to take into account the years, and changes of the year, and if they are full months (so compare the days in the month)
π
I have no idea how many months old I am π€· . Many...
haha ikr
I was trying to create the template, but I have to start preparing dinner now
{% set birthday ='1981-10-12' | as_datetime | as_local %}
{% set d = now().day >= birthday.day %}
{% set m = now().month >= birthday.month %}
{% set bday_this_year = birthday.replace(year=now().year) %}
{% set last_bday = bday_this_year if bday_this_year < now() else bday_this_year.replace(year=now().year - 1) %}
{% set years = last_bday.year - birthday.year %}
{% set months = now().month - birthday.month - (0 if d else 1) + (0 if m else 12) %}
You made some pretty good progress so far! π
I am trying to figure out how to turn off only things that are on in a group or lock only things unlocked. Turning the group on/off wonβt work. I was using the expand template but if you try and turn an entity off when all of them are already off you get an error. Any ideas?
Conditions wonβt work because I am working with several different domains.
You can use a template like you had, map the entity id, and use that for the target of your service call
Leap years are an issue, and the days part isn't easy as well now
I did that but it would error if letβs say all the lights were off. Entity_id would be blank
Well, I figure I would only be calculating this for the first 2 years so not sure how much leap year would be a problem
Put it in an if-then and check first if there is any light on
Hello! I've been pointed from the general thread over here to ask about color effects. Are there any good starting points for doing interesting color effects for something like a kids dance party? We have a few color zigbee bulbs that could be randomized or could have other effects applied to them, but I'm not sure what the best starting point would be. Thanks!
So this should not error if all covers are closed:
- service: cover.close_cover
data:
entity_id: >
{% if expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='state') | list | count > 0 %}
{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list |join(', ') | default(none) }}
{% endif %}
that will still error
this is what you should use
- choose:
- conditions:
- condition: template
value_template: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='state') | list | count > 0 }}"
sequence:
- service: cover.close_cover
data:
entity_id: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list |join(', ') }}"
and if you want to optimize it..
- variables:
lights_on: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list }}"
- choose:
- conditions:
- condition: template
value_template: "{{ lights_on | count > 0 }}"
sequence:
- service: cover.close_cover
data:
entity_id: "{{ lights_on | join(', ') }}"
I just realized they were covers, oops
this tactic seems to work:
{{ expand([states.light, 'switch.fr_reading_lamp'])|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}
you can add whatever other entities you want
i cant use a choose because i am doing multiple different things, lights, llocks, covers, switches i guess i am going to have to do multiple automations or just give it an else?
just use that choose for that single action
or put all the remaining actions inside the choose
auh. multiple choose under each service?
no
so the choose is only for that single action
you can put actions after it
or not
or you can put items inside that chooses sequence
auh, you can multiple action blocks?
all you're trying to do is make it not error on that service call, so you use choose to conditionally call that service call
I'm not following your question
If all you want to do is make this service not error...
- service: cover.close_cover
data:
entity_id: >
{% if expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='state') | list | count > 0 %}
{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list |join(', ') | default(none) }}
{% endif %}
you can replace it with this and it will be the same
- variables:
lights_on: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list }}"
- choose:
- conditions:
- condition: template
value_template: "{{ lights_on | count > 0 }}"
sequence:
- service: cover.close_cover
data:
entity_id: "{{ lights_on | join(', ') }}"
if i have a light on, a switch on, a lock unlocked, and a cover open. a choose will get to complicated
I still don't follow
the choose is literally for just that service
no other services
unless you want that
you can do this without any repercussion and it's not really complicated:
- variables:
covers_open: "{{ expand('group.all_covers') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list }}"
- choose:
- conditions:
- condition: template
value_template: "{{ covers_open | count > 0 }}"
sequence:
- service: cover.close_cover
data:
entity_id: "{{ covers_open }}"
- variables:
lights_on: "{{ expand('group.all_lights') | selectattr('state', 'eq', 'open') | map(attribute='entity_id') | list }}"
- choose:
- conditions:
- condition: template
value_template: "{{ lights_on | count > 0 }}"
sequence:
- service: cover.close_cover
data:
entity_id: "{{ lights_on }}"
it'll still rip through the automation
ok, i see what you are doing
You could even get super lazy (like i do) and just make a all in 1 turn off script
i thought about that but i like what you posted above
my alarm_away automation has become a complete mess with stuff i have been trying π
action_based_on_state:
mode: parallel
max: 1000
variables:
target_entities: "{{ expand(group) | selectattr('state','eq', target_state) | map(attribute='entity_id') | list }}"
sequence:
- condition: template
value_template: "{{ target_entities | count > 0 }}"
- service: "{{ service }}"
target:
entity_id: "{{ target_entities }}"
then your automation is just:
- service: script.action_based_on_state
data:
group: group.all_covers
service: cover.close_cover
target_state: open
- service: script.action_based_on_state
data:
group: group.all_lights
service: light.turn_off
target_state: 'on'
the choice is yours, personally I like to make scripts and reuse them so that I don't have to have super complicated automations
I know the script will work. at that point, you're just debugging the automation itself if something doesn't go right. and your compartmentalized script can be tested easily in the service caller
especially if you add fields and descriptions
take a look at my config, it's all scripts and like 10 automations that use all those scripts that are parallel
and if you want them all to turn off / close at the same time....
- parallel:
- sequence:
- service: script.action_based_on_state
data:
group: group.all_covers
service: cover.close_cover
target_state: open
- service: script.action_based_on_state
data:
group: group.all_lights
service: light.turn_off
target_state: 'on'
it's cool to watch
i think i am on my way with the variables example - variables should line up with the - choose for proper yaml corect?
yep, but you can put them in the variables section too
instead of in the action sequence
just @ me if you have other q's
thank you
slowly building it then my alarm has to go to arm away so....may be a while
i really need to understand variables so some reading also
Thanks !!
@fierce hornet posted a code wall, it is moved here --> https://hastebin.com/qukocuwela
Could someone help me? I'm trying to create a system that cleans specific rooms using my vacuum based on some input bools. It seems like whatever I try gives an error. Most of the time it's ... required key not provided @ data['zone']. Got None
The template is moved to the link above
you have several extra "-"
it also needs to output a list
not a yaml list
and you need to programatically add ,
not an easy template
service: xiaomi_miio.vacuum_clean_zone
data:
repeats: 1
zone: >
{% set ns = namespace(items=[]) %}
{% if is_state('input_boolean.stofzuig_kleed', 'on') %}
{% set ns.items = ns.items + [25335, 25936, 27573, 27402] %}
{% endif %}
{% if is_state('input_boolean.stofzuig_keuken', 'on') %}
{% set ns.items = ns.items + [21695, 25664, 24804, 28896] %}
{% endif %}
{% if is_state('input_boolean.stofzuig_woonkamer', 'on') %}
{% set ns.items = ns.items + [24756, 25046, 28189, 28625] %}
{% endif %}
{{ ns.items }}
I was afraid of that yea. What you've got going on looks promising! Also outputs as a list now
Unfortunatly it doesn't work because it actually expects lists within a list. This just makes it one big list
Would you happen to know how to accomplish this? Have no idea how to come up with something like this. I believe the output in the end should be [[24756, 25046, 28189, 28625], [25242, 26014, 27662, 27272], [21695, 25664, 24804, 28896]] if all the booleans are enabled
I found this https://community.home-assistant.io/t/a-list-generated-by-a-template-is-it-possible-help/111239/7 online. But it's from some years ago and will be a mess with the 10 booleans I intend to use it with.
just add another set of square brackets around each list
{% set ns = namespace(items=[]) %}
{% if 1==1 %}
{% set ns.items = ns.items + [[25335, 25936, 27573, 27402]] %}
{% endif %}
{% if 1==1 %}
{% set ns.items = ns.items + [[21695, 25664, 24804, 28896]] %}
{% endif %}
{% if 1==1 %}
{% set ns.items = ns.items + [[24756, 25046, 28189, 28625]] %}
{% endif %}
{{ ns.items }}
That works! Didn't know the last step would be so simpleπ Thanks guys!
thanks @inner mesa
I have a water meter calculated in US gallons which I am converting to m3. When the HA restarts, sometimes the US gallons sensor spikes initially for a second before returning to normal, and unfortunately my m3 sensor adds this spike to itself. Because this spike only happens rarely and immediately after a restart, I'd like to make my m3 sensor wait like 3mins before starting after startup (this should ignore the spike). Question: Is it possible to add a delay to the following template:
water_meter_water_consumed_m3:
friendly_name: 'Water Meter - Water Consumed (m3)'
icon_template: hass:water
unit_of_measurement: cubic meters
value_template: >
{{ (states('sensor.water_meter_water_consumption_us_gallons')|float(0) * 0.0037854118|float(0))|round(4) }}
availability_template: "{{ states('sensor.water_meter_water_consumption_us_gallons') not in ['unknown', 'unavailable', 'none'] }}"
No, that's not possible, but how high is this spike?
You could add it to the availability template, so it's unavailable if the source sensor value is above a certain threshold
it's fairly significant... 107k to 279k, back down to 107k
I wonder if I could add the threshold to be dynamic, like if greater than 50% the previous value then wait....
Here is a screenshot https://imgur.com/a/Ld9wUuQ
You could if you convert it to a trigger based template sensor
Then you can trigger on state changes of the source sensor, and compare the from_state with the to_state
Maybe it is not even needed to use a trigger based template sensor, you could use this.state and compare that to new calculation
But you are using the legacy format, which doesn't provide the this variable
hmm, interesting. Can you provide me with a link to read an example on this?
Im happy to make the change if I know how π
"you could use this.state and compare that to new calculation"
Can you suggest how this code should look?
...now that I have it updated:
template:
- sensor:
- name: 'Water Meter - Water Consumed (m3)'
icon: hass:water
unit_of_measurement: cubic meters
state: >
{{ (states('sensor.water_meter_water_consumption_us_gallons')|float(0) * 0.0037854118|float(0))|round(4) }}
availability: "{{ states('sensor.water_meter_water_consumption_us_gallons') not in ['unknown', 'unavailable', 'none'] }}"
- name: 'Water Meter - Water Consumed (m3)'
{% set new = (states('sensor.water_meter_water_consumption_us_gallons')|float * 0.0037854118) | round(4) %}
{{ new if (not this.state | is_number) or new < this.state | float * 1.5 else this.state }}
Something like this
ok, so that would go under the 'State' variable
you don't need the |float(0) here: 0.0037854118|float(0)
BTW, you can simplify your availability template to
availability: "{{ states('sensor.water_meter_water_consumption_us_gallons') | is_number }}"
Right, didn't look at the existing template, I only used it to create the variable
But indeed, that's not needed
The default for the other float is also not needed, because of the availability template
I forgot one thing, you should take into account what happens if the state of the template sensor is unavailable
Then you also want to use the new state
I've added that
And brackets, because I'm not completely sure to what the not applies
A quick check learns me the brackets are not needed
I think I got my baby birth month counter figures out π
good thing you got it done before your baby is old enough to fix it for you π
lol
Ok, dad. Lemme just do it for you...
I'll share it in a second, pulling up hastebin now
I didn't account for leap year math because for what I'm aiming for I don't see how that makes a difference
That didn't actually work as planned. Is there a way to take a date and subtract a month such that 2022-09-18 becomes 2022-08-19 ?
I was thinking about something like set lastmonth = concat (now().year "-" (now().month -1) "-" now().day) but I can figure out how to do that
Got it!! π {% set last_month = now().year ~ "-" ~ (now().month - 1) ~ "-" ~ now().day %}
Careful of months w/ 30 or less days
There is something like this {{ (now() - timedelta(days=30)).date() }}, you can't provide "months" likely because it's ambiguous
The way you have to manage it is create a datetime at the first of the current month you are in. Then perform your math
This won't work in January
Thanks for this. I think this is what I need for tracking daily HVAC duration, but I'm trying to "beef it up" and clean up the state based on if it's just minutes or minutes and hours (ex. 17 minutes will say "17 minutes" and not "0 hours 17 minutes".) I've pasted the code I use for a few other sensors and removed seconds and adjusted sensor names, but I can't get it to work in the template tab. Thoughts?
https://hastebin.com/ohajanubeg.csharp
No answer in general, maybe it belongs here?
Good morning, Is there a way to modify the time at which a meter helper (reset daily) resets? Why, I use a battery in my solar system and I would like to know how much energy is used since sunset, or a time in the afternoon. Any idea?
there is an attribute cron pattern... ????
Thanks!
ok so why am I getting two decimal places from this template?
- name: "Main Room Temperature"
unit_of_measurement: "Β°C"
device_class: temperature
state: >-
{{ (float(states.sensor.kitchen_temperature.state) + float(states.sensor.lounge_rm_pro_temperature.state) ) / 2 | round(1) }}```
my very basic understanding is that round(1) should give 1 decimal place
Because you are only rounding 2 which is already an integer
You should also use defaults for your float functions or use an availability template
And you should use states('sensor.whatever') instead of states.sensor.whatever.state
Can this only be used in mqtt value_templates or any template sensor?
I think it's implemented in everything under the template integration
Sweet. That makes running totals a bit easier then.
that should be on my clipboard
it mentions all state based and trigger based entities
Thanks all I found was https://www.home-assistant.io/docs/configuration/templating/#using-value-templates-with-mqtt
I assume it will be a string and needs to have a float or int filter applied if doing addition?
this.state will always be a string
Thanks Fes.
Good point
{% set m = 12 if now().month == 1 else now().month - 1 %}
{% set y = now().year - 1 if now().month == 1 else now().year %}
{% set last_month = now().replace(year=y, month=m).date() %}
This will work in January
Hi. How can I generate a hash of a string in templates?
Background is I want to secure a webhook event. My idea was this: (what I assume to be the normal secret key method)
On the device sending the webhook, I hash a string containing the current date and a secret key, then I send both date and hash as event_data with the webhook.
Then in HA templates, I use that date and the secret key to generate a hash and if it matches with the hash sent via the webhook event_data, continue.
there are no functions that hash things, you'd need to make it yourself.
okay, could you please point me in the right direction as to how I can make it myself?
you'd have to come up with some algorithm. It may not be possible.
Jinja is limited
TBH, it'll be a waste of time
Do you happen to have another idea on how to secure a webhook like I mentioned above?
(apart from just keeping the webhook url a secret lol)
not really a way to do that
This also works in January:
{{ (now().replace(day=1) - timedelta(days=1)).replace(day=now().day).date() }}
I think I finally got it π
https://hastebin.com/qimugokufe.csharp
does it account for DST?
if not, it'll be off by an hour π€£
the perils of time and coding
It only counts months and days by day of month so 2022-08-22 -> 2022-10-24 is 2 months and 2 days
I think it would break for birthdays later in the month than the 27th but that isnt my case
The doctors office counts baby age by day of month, not sure what they would do with a birthday on the 31st for shorter months. didnt think to ask
what Timezone are you in?
EST
not the end of the world π
what matters is if DST is applied on your birthday, but not applied when you're counting
basically datetimes change the offset when DST is applied
ah
right now I think ESTs offset is 4 hours because we are in DST, but when out it's 5 hours
or vice versa
yes something like that
so, when you create a datetime in the past, it uses your CURRENT dst setting, not the DST setting at that point in time
super dumb
oh interesting
well, it's not dumb, it makes sense why they do it, so that time deltas are correct
but when you're manipulating datetimes like you are, it screws it up
well i think it should be close enough, not doing rocket science with her age counter π it's more of a quick reference / nice to know
it's good to know thank you for letting me know
hahaha true
i often like to do things the long drawnout way π
@sterile nacelle posted a code wall, it is moved here --> https://hastebin.com/iroworuyaf
akvarie ones work fine, but the 3d_printer one throws error :/
The system cannot restart because the configuration is not valid: Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer') for dictionary value @ data['sensors']['3d_printer_power']['value_template']. Got '{{ states.switch.3d_printer.attributes.current_consumption }}' invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printer') for dictionary value @ data['sensors']['3d_printer_voltage']['value_template']. Got '{{ states.switch.3d_printer.attributes.voltage }}'. (See ?, line ?).
I'm in GMT +1 and I just recently realized why there was only one hour offset if you use timestamp_custom on a timedelta in seconds without adding false
there is no DST on 1st of January 1970
as it was winter then
you shoud use {{ state_attr('switch.3d_printer', 'current_consumption') }}
same for the others
or is the problem that it is DST now, and not on 1st of January 1970
the problem was, you're taking a date from now which has the offset flag set to whatever the current dst is
and then making a date when dst may or may not have been active
so your made up time will have a +0400, when it should have had +0500
dst is fucked up
when you run that exact same command during a non dst time, the top becomes null or 0:00:00 and the bottom will be -05:00 for tz info
actually, it looks like this was fixed??!?!?!?!?! in python 3.10??? holy crap
ugh, my dst calcs will be wrong now π
oh, no that's UTC vs Local
there is an offset of 1 hour between the 2
that flag at the end basically says "Is my timestamp local or is my timestamp utc"
yes, but as it is DST here now, I found it strange that the offset was one hour
but there is no DST on 1st of January 1970
it took me some time that the timezone of that actual date would be used
BTW why is %R not on strftime.org
It's probably platform specific
and %F
i.e. windows, linux, or mac
I'm not 100% sure on that
strftime.org might also be out of date
ah no, look
it's only a linux thing
LOL so if you visit strftime.org on a linux machine, you'll see %F... those cheeky fucks
but i'm assuming you're visiting the page on windows, so it shows the windows items
or if you're on your phone it'll be mac
@marble jackal ^
π€·ββοΈ
but I don't have any Linux machines on which I can acutally view a browser
oh my android phone of course
it is, but I don't see them
Maybe it doesnβt announce itself as linux to the browser
They should at least have a drop-down selection
is there a place for feature requests π
hello is there an good tutorial how to make an template?
I got it!
For anyone wondering: I can now generate SHA256 or md5 hashes using the pyscript integration, where I import hashlib and expose a service to HA which generates the hash and outputs it to sensor.generated_hash.
There are three links in the channel topic
Good morning everyone! I have a rest sensor which gets a JSON response looking like this:
{"html":"<h3>Hemer-Becke/Oese</h3><p class="klein"> gewässerkundlicher Pegel </p><p class='klein'>Pegelstände der letzten 3 Tage</p><img src='lib/php/gangl_p.php?stationsname=Hemer-Becke&breite=300&hoehe=210' width=300 height=210 ><table align="center">
<tr><td></td><td></td></tr> <tr><td class="klein"> mittleres Niedrigwasser: </td><td class="klein" align="right">4 cm</td></tr>
<tr><td class="klein"> Mittelwasserstand: </td><td class="klein" align="right">16 cm</td></tr>
<tr><td class="klein"> mittleres Hochwasser: </td><td class="klein" align="right">122 cm</td></tr>
</table>
<div align="center"><p class="klein">Wasserstand am 14.09.2022 09:05 : 14,00 cm</p></div><div align="center"><p class="wichtig">ungeprüfte Rohdaten</p></div><input type="hidden" id="hdnPgnr" value="Hemer-Becke">"}
so when I use value_json.html, I get the HTML code as state. How do I go from here to just get the 14,00 cm from the /div/p tag?
@inland stag posted a code wall, it is moved here --> https://hastebin.com/buyomuhefi
I cleaned those up
Home Assistant does it as well in the state output
right now I cannot get the state from HA as it exceeds 255 characters
(with only using value_json.html)
{{ value_json.split(' : ')[1].split('</p>')[0] }} for that specific example
if you're extracting the value from <p class="klein">Wasserstand am 14.09.2022 09:05 : 14,00 cm</p>
this one might be safer {{ html.split('Wasserstand am')[1].split('</p>')[0].split(': ')[1] }}
using split makes sense, I was investigating if I can use something like XPath
this is working now: {{ value_json.html.split('Wasserstand am')[1].split(' cm</p>')[0].split(': ')[1] | replace(',','.') | float(0) }}
there's probably more ways, this is all i know π
just use regex
{{ value_json.html | regex_findall(">([0-9]+) cm<")[0] }}
also, no need to cast to float
Hm, this leads to a TemplateSyntaxError: expected token 'end of print statement', got '[') for dictionary value @ data['value_template']. Got "{{ value_json.html | regex_findall('>([0-9]+) cm<')[0] }}".
do I need to escape the <>?
nope, did you quote the entire template? If you did, you have to change the interior or exterior quotes.
None of this is related to templates
deleted messages??
Yes, can't remember what it was about, but but about templates
I was not referring to your post
Is there any way to get the last_changed of a device without entities? I have a zigbee device with 3 buttons that sends events and want to template the last_changed of a button
devices don't have states
you can build a trigger-based template binary_sensor and use its last_changed
that was my plan if there was nothing else to do π
thank you Rob
you can also expand a devices entities and get the last changed entity
{{ expand(device_entities('22bcb2d986098a5dc0f95614f727daa3')) | sort(attribute='last_changed') | map(attribute='name') | first | default }}
but if the device truly has no entities and relies on events, that won't help
exactly, that doesn't help me. I want to know when a button last pressed, there is no entity for that, it's passed as an event
sorry, i assumed button was the button entity
I already did a trigger based sensor, but thank you very much for your tip petro
- trigger:
- platform: state
entity_id: light.hallway_front
attribute: color_temp
sensor:
- name: "Hallway Lights - Colour Temp"
device_class: power
state: "{{ state_attr('light.hallway_front', 'color_temp') }}"
How can I make it keep the last state when the light is off? Right now its "None" when the light is off. Can i just have the last number is was set to?
I am happy to remove the trigger template as its probably not needed
Is there a way to convert any negative number to a positive number, and leave positive numbers and 0 alone? I'm wanting this for a temperature comparison automation.
Absolute value?
That sounds right, I'll test now to learn how that works.
{{ (states('sensor.temperature_difference_indoor_to_outdoor') | float) | abs }} seems to work great for my purposes. Thank you for pointing me in the right direction.
Any ideas for how I could return a true template when a value changes from positive to negative?
You'd need to store the previous value somewhere, then use a boolean test to compare the previous and current values. But why do you want to do that?
a trigger-based template binary_sensor with a numeric_state trigger would do it
- trigger:
- platform: state
entity_id: light.hallway_front
attribute: color_temp
sensor:
- name: "Hallway Lights - Colour Temp"
device_class: power
state: >
{% set ct = state_attr('light.hallway_front', 'color_temp') %}
{{ this.state if ct is none else ct }}
You probably want the trigger, as it will allow the state to be restored after template reload or HA restart
oh nice one - that makes sense
How do I create a sensor that defines the possible outcome in the state, so that the automation trigger UI can detect which possible outcomes there is for the sensor? (quite new to HA)
This is what I got:
- sensor:
- name: "Bed status"
unique_id: bed_status
icon: mdi:bed
state: >
{% if states("binary_sensor.sonoff_door_sensor_2_contact") == 'on' %}
open
{% else %}
close
{% endif %}
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), http://pastie.org/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
You don't need a template sensor for this
you just need to assign the right device_class to the binary sensor you already have
if the device has a unique_id, there's a dropdown in the UI that will change the display in the frontend on the device
Okay, so you would rather rename the device/entity, then creating new custom sensors?
no, we are not talking about renaming devices/entities at all
(binary) sensors can have a device_class, which determines how they are treated by the frontend (Dashboard)
In the link I shared there are multiple device classes which use open/close
there is also opening
yep
it will also have effect on the icon, if no icon is set
if settings doesn't exist, then you have to do it in yaml
What if one wanted to use custom wording like made/unmade?
then you need to create a template sensor, or use something like https://github.com/thomasloven/lovelace-template-entity-row
okay, thanks. Appreciate your time
Hi all. Need some help with a notification template. I can never get my head around time-based stuff. I have a travel time sensor that has the commute time in minutes to a my kid's school that has the same pickup time every day. What is the best way to have a notification go off at the travel sensor's value before that fixed time? And maybe plus like a five minute buffer?
{% set pickup_time = '15:00' %}
{% set travel_time = states('sensor.travel_time') | float(30) %}
{% set buffer = 5 %}
{{ now() > today_at(pickup_time) - timedelta(minutes=travel_time + buffer) }}
The float filter on the second line defaults to 30 minutes now, in case the sensor is not available
Super elegant. Thank you.
Haven't heard of the timedelta function. I'll have to look into it more. Appreciate it!
is it possible to create a template color_temperature for a light that maps an rgbw light like this:
warmest temperature: 0,0,0,255 (only white channel on)
coldest temperature: 255,255,255,255 (all channels on)
@rustic raft posted a code wall, it is moved here --> https://hastebin.com/okokidehad
aw that was less than 15 lines
it was 19
less than 15 lines of yaml*
doesn't matter
noted.
and no, what you have there is not valid
you cannot generate a bunch of conditions from within a template
you can, however, do that with just a template
I suppose. I can't really figure out what you're trying to do
thanks, that's helpful. It's a blueprint that mirrors the value of one or more select entities into a single select entity. i'm trying to make something similar to a group with custom logic and helper entities.
if i wanted to create multiple yaml conditions from a templated for loop, would i be able to do that in a script?
no
I'm still not clear on exactly what you want out of those conditions
you want to know if a bunch of input_select entities are the same value?
" if either of these two entities state's === "active", then [do something]"
so that's easy
conditions are "and", BTW, so they won't be "or" unless you explicitly specify that
anyway:
{{ expand(['input_select.x', 'input_select.y'])|selectattr('state', 'eq', 'active')|list|length > 0 }}
or
{{ 'active' in expand(['input_select.x', 'input_select.y'])|map(attribute='state')|list }}
appreciated, i'll slap that in a template condition and it should do what i need it to
you can easily test it in
-> Templates
Petro I have let it run for a few days having added the changes you sugested to all my state_changed based automations but i still get the same kind of warnings: https://hastebin.com/onajeraqul.coffeescript
this is how one ot the automations looks like now, i have added it to pretty much every condition but does not seem to help: https://hastebin.com/ibuhuzojog.http
You are already referring to the object_id before you check if it is not none
new_state.domain == 'binary_sensor' and new_state.object_id.startswith('windowbr') and is_state(enable_window_switch, 'on')
and new_state.status != 'unknown' and new_state.status != 'unavailable' and new_state.status is not none
and new_state.entity_id is not none and new_state.object_id is not none
and is_state(window_auto_on, 'on') and 'tamper' not in new_state.object_id and not new_state.object_id.endswith('batt') ```
you are using new_state.object_id.startswith('windowbr') on the first line, while your check new_state.object_id is not none is on line 3
acutally you are already using it here {%- set room_number = trigger.event.data.new_state.object_id[-3:-1] %}
Mmmm I see
What would be the best aproach to avoid this?
I guess I need to wrap this condition in another one that does those checks first
would this work better?
condition:
condition: and
conditions:
- condition: template to make those check?
- condition: my template```
no, you need to move it to the front of the template
but you also have a lot of redundant code in your templates
I did an attempt to improve it
btw, are you sure you mean new_state.status and not new_state.state ?
oh, and I just realized you create a variable with the old_state, but you never use it
good point
i do use old_state in other automations, just a copy paste thing, you are right can be removed in this particular one
i guess new_state.state would be right not status
but not sure other at this point lol
https://dpaste.org/Rqedd improved version with a typo fix, more consistant usage or quote-type, change of status to state and old_state removed
thanks for the example im readind trought it π
state would be the standard for the entity state, status would be something custom for these specific entities
then its state
I'm also not sure why you are using format to concatenate the strings
{%- set window_auto_on_on = is_state('input_boolean.windowbr' ~ room_number ~ '_auto_on', 'on') %} this would work fine as well
without format()
because it worked and did what i wanted π€·ββοΈ
its been 2.5 years since i wrote it, i have a bunch of automations using this style, chances are i did need it somwhere else and just copied it from that automation, as i say im not a programmer so this is quite out of my comfort zone ..
whoops, I left some code, in, this is the corrected correct version https://dpaste.org/jj1MC
BTW, conditons are AND by default, no need to wrap it in an AND condition
Oh, and one other thing
If you add some checks to your trigger, it would't have to render all these templates on every state change
on all your conditions you check for state changes in the binary_sensor domain, why not add it to the trigger?
That might also remove the results which cause you to check on all those values being non none
but the trigger is state_changed based, can i make it trigger only when a binary sensor changes state?
by adding it to the trigger
platform: event
event_type: state_changed
event_data:
domain: binary_sensor
ok yes cool that makes a lot of sense
You could also add a lot of these variables you create again for each template to automation variables
so you won't have to recreate them in each template
trigger: []
conditions: []
action: []
variables:
old_state: "{{}}"
new_state: "{{}}"
correct me if im wrong but I dont think that could be done back in the day when i wrote this, variables werent introduced yet
might be, but no reason to not add that now
btw, your approach to do the checks in a separate condition would also remove more redundant code
as you now do these checks in every condition
ok, lets see step by step, to much info at once to process.. if i understand correctly you are saying if I just declare all the variables i need once in the begining of the action section I can delete all of them in the rest of the template and it will still work as before right?
like new state, old_state, room_number, windows_switch, etc, basicaly all the ones im constantly repeating in every section of the automation
and also that they will be local variables only persistent inside this automation
along these lines
trigger: []
conditions: []
action: []
variables:
new_state: "{{trigger.event.data.new_state}}"
old_state: "{{trigger.event.data.old_state}}"
room_number: "{{trigger.event.data.new_state.object_id[-3:-1]}}"
sensor_type: "{{trigger.event.data.new_state.object_id}}"
window_switch: "{{"input_boolean.enable_windowbr" ~ '{}'.format(room_number)}}"
window_auto_on: "{{is_state('input_boolean.windowbr' ~ room_number ~ '_auto_on', 'on')}}"
window_auto_off: "{{is_state('input_boolean.windowbr' ~ room_number ~ '_auto_on', 'off')}}"```
and now i can use these variables without declaring them inside every condition, right?
correct, they are available in the entire automation, besides for the trigger
not sure why the bot compains about your yaml
the only thing is that you might need to check for the object_id not being none
im testing it and the config checker also complains so the yaml must be wrong
so:
room_number: "{{ new_state.object_id[-3:-1] if new_state.object_id is non none else none }}"
in "/config/automations/Windows Automation Template.yaml", line 106, column 7
expected <block end>, but found '<scalar>'
in "/config/automations/Windows Automation Template.yaml", line 110, column 26
and you can use the variables you declared, so no need to use trigger.event.data.new_state if you already declared that to be new_state
no way to know what is wrong without the automation code
ok let me dig a little
okay, I'm actually going to work now π
no worries, thanks men, ill try to implement all your sugestions see where it takes me π
its defenitly when i add the variable line that breaks the config checker:
action:
variables:
new_state: "{{ trigger.event.data.new_state }}"```
I assume you are on a recent version of HA?
latest release
and you have at least one action, or [] to define an empty list?
all the same automation as before, but when I add this line after action adding the variable i get the error
it should be after all the actions
so
action:
- some action
variables:
some_variable:
not:
action:
variables:
some_variable:
- some action
at the end of the automation? I need the variables declared to use them in the the action
I know
that doesn't matter, it will load them after the trigger
the order in the dictionary is not relevant
but you can also put it before action
ok that fixed it placing it after the first action
that worked also π
thanks for the help ill keep chiping at it, will be back for sure π
it will be available in the condition as well, so if you want the most logical order, but it right after the triggers
yes that is what i did makes more sense
you can also define variables in the action sequence, but they won't be available in the conditions then:
action:
- variables:
some_variable:
- service: some.service
i need them available in both as i have sequences and conditions that both use the same variables
yes I know, it was just FYI π
I need to correct my self, its actually its not working, i have tried to add the variables in a bunch of places in the automation and cant seem to add them without the config checker complaining, (i made a mistake before as I was editing wrong file as i have multiple windows open) i need to go now, working from home but wife just got back and need to take care of some stuff, will be back later see if we can implement this π
im back, been trying to figure stuff out one by one
- platform: event
event_type: state_changed
event_data:
domain:
- binary_sensor
- input_boolean```
would this also be correct to the state_change ongly triggers on only those 2 domains?
proably a combination
shouldn't have to if he's using 2 triggers
I've seen the rest of the automation π
its all posted here LOL
You could as well, just scroll up a bit
that requires effort
Trying to remove a lot of redundant code from his automation
i do have a specific question for you petro:
@mighty ledge im using your code it was written status, not sure if should be state or status
what code?
here
I just copied what you originally had
if new_state is a state object, status isn't valid
so state is right, just wanted to confirm
cool
TheFes, for adding the the variables I cant get them to pass the config checker no mattter what i have tried π¦
.share the entire automation
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- 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.
anywhere i have tried to add them in the automation it doesnt pass
and the error code
its prett much the same havent changed anything yet lol
just trying to add the variables (havent aplied any of your sugested changes yet) but han on i will share again
I'm guessing you're a process engineer IRL?
my self? i have no formal education background, work as drone developer test pilot
I don't see variables anywhere
I need to know what you are trying to see what is wrong
yes they are not there, this is the working code, what im saying no matter where i add variables in any portion of the code it breaks
can you mention the line where i should add them i will test please?
I was just asking cause you're doing all this prep work without changes π€£
lol
- alias: "Windows Automation"
mode: parallel
max: 30
trigger:
- platform: event
event_type: state_changed
event_data:
domain: binary_sensor
variables:
variable_here: 1
and_another_one:
condition:
your_code:
short story is basicaly i have a working supervised install at a rental house i have a few hundred miles away and im cloning it to a new HAOS install at my home and trying to fix all breaking changes and updates so i can just go over there and swap one for another, i cant afford to break the working install and its running on a raspian that hasnt been updated in 3 years expposed to internet with malware currently on it so i need to fix it
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/automations/Windows Automation Template.yaml", line 15, column 7
expected <block end>, but found '<scalar>'
in "/config/automations/Windows Automation Template.yaml", line 19, column 26
i get the same error no matter where i try to add the variables section in the code
i can share the full code but its the same as the first link
what is the code which generates this error
adding
variables:
new_state: "{{trigger.event.data.new_state}}"
as per your intructions
if i comment it out it works
just to be clear and you can see all the code:
This works: https://dpaste.org/xP6fk
This gives the error: https://dpaste.org/4CCzG
only diference is adding the variables as you told me to do
window_switch: "{{'input_boolean.enable_windowbr' ~ '{}'.format(room_number)}}"
uh, that's also poorly written
window_switch: input_boolean.enable_windowbr{{ room_number }}
TheFes also pointed it out allready thanks π€£ π€£ π€£
yes but that's what your error was coming from
in "/config/automations/Windows Automation Template.yaml", line 15, column 7
points directly to the error
it's hard to tell because you have those 2 commented out lines
which are not counted in the line number
Hi all, newbie here. One of my sensors is not loading on restart.
- sensor: - name: "^DJI Trending Color" statae: > {% if state_attr("sensor.yahoofinance_dji","trending")=='up' %} rgb(38,209,88) {% else %} rgb(255,69,58) {% endif %}
I even did a power set on the RPI3B
statae:
π© damn
yes i undertantand comented lines screw up the line count π¦ but on that note how are the columns interpreted in the errors, i mean when it says for instance line 15, column 7
i dont get the column thing
number of characters
Thank you. very much
this looks suspicious
use single quotes inside the template, that is probably causing the error
7 characters in is the start of your key π
you have 7 spaces
it's saying "that whole line is fucked", paraphrased
and it starts getting fucked at the 7th character
window_switch: "{{ window_switch: input_boolean.enable_windowbr{{ room_number }}"```
no
window_switch: input_boolean.enable_windowbr{{ room_number }}
or
window_switch: "input_boolean.enable_windowbr{{ room_number }}"
both are fine
or
window_switch: "{{ 'input_boolean.enable_windowbr' ~ room_number }}"
so with single quotes inside, and double quotes outside the template
Personally I try to avoid string concatenation if I can
I like this one, the less stuff in the line the better for me π
and yes now it passes config test π
let me restart and see
you can just reload automations
If you want to avoid worrying about quoting, use multiline notation
i have had multiple times i reload no errors and then i restart and i get errors, i rather restart to make sure
yep seems to work now π
so this other set line im using ```yaml
set enable_window_switch = "input_boolean.enable_windowbr" ~ '{}'.format(room_number)
would be writen like this correctly as variable:
enable_window_switch: input_boolean.enable_windowbr{{ room_number }}
ok cool
let me simplify this a little and then i can get back to your sugested code from before try to implement it π
something like this is also valid:
some_variable: switch.{{ other_variable }}_on
just to be clear and dont mess up this is the code you suggested: https://dpaste.org/jj1MC
its to replace this portion of the automation right?: https://dpaste.org/dgahz
well yes, but that was before you started using variables
because I still create the same variables in the template there
yes
if you use variables, it can be shortened a lot
you can format code as jinja instead of yaml if you just post templates
same for dpaste (it's django/jinja there)
and you could the first part in a separate condition
updated the link
as it is the same for the others
- condition: template
value_tempalte: >
{{
new_state.object_id is not none and new_state.entity_id is not none and new_state.state is not none
and new_state.state not in ['unavailable', 'unknown'] and not new_state.object_id.endswith('batt')
and 'tamper' not in new_state.object_id and (new_state.object_id.startswith('windowbr') or new_state.object_id.startswith('doorbr'))
}}
- condition: template
value_tempalte: >
{{ enable_window_switch_on and (window_auto_on_on or window_auto_off_on) }}
not in is the same as !=?
I think this would not work because im using or as the condition, as i have 3 conditions one for bedroom, one for living rooms and one for kitchen
'banana' not in ['banana', 'apple'] would return false
'banana' != ['banana', 'apple'] wourld return true
so it's not the same
you could use the same for the other rooms
the first condition is the same for all 3, if not, move the part which is not the same to the separate conditions
but most of it will be the same
does this look like what you meant?
and now next in the action section i can also remove all the set = X and take advantage of the variables right
for your reference this was the old code: https://hastebin.com/ibuhuzojog.http
No, more like this: https://dpaste.org/rVauX
sometimes i dont know if i hate you or envy you or love you or what I feel, you make it seem so easy π€£ π
yes makes sense a lot simpler
let see if i dont break anything π
how does this look? https://dpaste.org/im9AR
followed all your sugestions, removed all set functions as they are variables now, used your code as trigger condition, formated everything a little better and so far it seems nothing broke, at least HA restared fine π
i guess there is till a lot of redundant code but its a rabbit hole, i just wanted to get rid of the warnings in the logs π€£
Actualy I need to thank you TheFes, im reading the code again now and I can allready see how i can implement all your sugestions further down the code to simplify things further in a similar way π₯°
Hi all, I have a problem to setup the value template for a rest sensor correctly.
I get a list of values like this:
[{"datapoints":[[49.96519,"2022-09-16 13:55:23"],[49.9658,"2022-09-16 13:55:24"],.....
and I want to extract only the 49.96519 as value.
My current template looks like this:
value_template: "{{ (value_json.datapoints[1][0]) | round(2) }}"
but it just gives "undefined".
you still got errors
many many errors
im sure i have
that is why i was ashamed of sharing my code, but hey it worked
Petro im a highschool dropout im not an enginner and a lot less a programmer π€£
but if you would kindly point them out maybe i can learn something
I just have some questions
it might, or might not, not all my binary sensors contain the room number as i have some unrelated to rooms
so how do you know you have a valid room_number?
you have all these conditions in place, yet you don't know if you have a room number
also, is room number... a number
if the sensor is named either doorbr, windowbr, doorlr, windowlr, doorkitchen or windowkitchen it contains the number i need
so for instance doorbr01a
ok
this is how, i name all my sensors like that and i know the placement of the number in the name
ok
the reason i did it this way is i wanted the template to be transparent, no matter if i have 1 sensor or 50
if i add a new sensor it should just work as long as the sensor has the right name
yes I understand this
but you have 909840598304958 if statements that can be extinguished
just give me a moment
sure take your time
that is one massive automation π
π€£ its only one of a few same style π
what's the format of your binary sensors
same crap?
doorbr01 or windowbr01?