#templates-archived
1 messages Β· Page 121 of 1
Hi folks. I'm trying to extract the name of my next timer (timerLabel) from the Alexa Media Player. The sensor.kitchen_next_timer sensor has a sorted_active attribute with the following output:
https://paste.ubuntu.com/p/PPGFZh8WRQ/
Could someone please help me with the template to extract the timerLabel for the first active timer? The example I provided has two timers.
Can you toss that through a json formatter please? Hard to read on mobile
Sorry about that.... Is this better?
https://paste.ubuntu.com/p/PPGFZh8WRQ/
any chance to set a condition and check if numeric_state of a sensor decreses by one?
or a wait template
but i don't know how to get the previous value
@shut silo you can compare the to and from states
can you explain a bit more? i have an automation and want to continue the actions only if a sensor decreased by one
i know "from" and "to" only in triggers
@wet lodge that structure is kinda odd. A mix of those string IDs and dicts
Maybe that was why I was struggling so much.
I would need to do some testing but I'm not at a computer
I can wait.... Appreciate any help I can get, whenever I can get it.
@shut silo template docs should cover the answers there
@wet lodge {{ value_json[0]|select('mapping')|map(attribute='timerLabel')|first }}
something like {{ (trigger.to_state.state|float - trigger.from_state.state|float) > 1 }}
And, forgive me, but that output is from an attribute of a sensor... How do I combine that statement with the template that extracts the attribute?
hey phnx what does set map stand for? Can I use it with other strings where I need to set a color based on the state or state attribute of an entity?
@wet lodge just replace value_json with your states() call
@true otter set creates a variable. map is an arbitrary name I gave the variable
Hmmmm.... I've tried each of the following with no luck:
{{ state_attr('sensor.kitchen_next_timer', 'sorted_active')[0]|select('mapping')|map(attribute='timerLabel')|first }}
{{ states.sensor.kitchen_next_timer.attributes.sorted_active[0]|select('mapping')|map(attribute='timerLabel')|first }}
Any suggestions?
for my awareness: so you use the "random".get to pull the state attribute information , but you close it out with 'red' }}. Why is that?. I am just yrying to understand how templates work.
'red' is a default value if the lookup fails
@wet lodge what is the raw output of the state_attr() call?
I'd like to create a sensor that shows 98 from this:
{{ state_attr('sensor.garage', 'parameters') }} gives me {'type': 'Buffer', 'data': [98]}
It seemed simple, but I am stuck. I've been trying several variants of from_json but I have realised I need push in a better direction or an example to steal from.
state_attr(...).data[0]
That is just brilliant. Thanks.
hi, is there a way to send different key-value in the data attribute when I calling a service in an automation action? like:
service: light.turn_on
data:
{% if trigger.to_state.attributes.bulb_mode == 'color' %}
brightness: {{ trigger.to_state.state|int }}
{% else %}
white_value: {{ trigger.to_state.state|int }}
{% elif %}
or I need to create separate automation for these two cases?
{{ state_attr('sensor.kitchen_next_timer', 'sorted_active') }}
gives me the following:
Unformatted: https://paste.ubuntu.com/p/W3h9Ky2Www/
Formatted: https://paste.ubuntu.com/p/XV5gpyMFPz/
what's the problem with the {{ state_attr('sensor.kitchen_next_timer', 'sorted_active')[0]|select('mapping')|map(attribute='timerLabel')|first }} ?
It doesn't return anything.
Ugg that structure is so weird
Need to add [0] before the |select
You dropped that from my example
For me it works, see the image, that I've sent in private
he's state_attr('sensor.kitchen_next_timer', 'sorted_active') stores a string value instead of an object
@dreamy sinew is there a way to convert it to an object/array?
? {{ state_attr('sensor.kitchen_next_timer', 'sorted_active') is string }} returns true for him
hey phnx I just tried to replicate what you shared , but my icon is going to the default only color. Which by the way was an awesome idea. {%- set motion = {'off': 'green', 'on': 'red', 'true': 'green', 'false': 'red'} -%} {{ motion.get(state_attr ('binary_sensor.motion_sensor_119', 'device_tripped'), 'orange') }} Could I use this same template if I want only to consider the state of the device. Would it maybe look like this ```{{ motion.get(state ('binary_sensor.motion_sensor_119', 'device_tripped'), 'orange') }}?
Can someone tell me what is wrong with the following? I get "input_number" undefined.. ``` action:
- service: input_number.set_value
data_template:
entity_id: input_number.running_cost_varmekabler_bad_1etg
value: "{{ (state_attr('sensor.cost_varmekabler_bad_1etg', 'this_day')) | float + states(input_number.running_cost_varmekabler_bad_1etg) | float }}"
@true otter as long as the states you pull match the keys in your dict you can do it
hey there, How can I access the get result from the rest command service in the second service? Thanks
sequence:
- service: rest_command.test_get
- service: input_select.set_options
target:
entity_id: input_select.test
data:
options: >
{% ..do some calculations on rest_command.test.get value %}
{{ list }}```
```rest_command:
test_device:
url: "http://xxx.xxx.xxx.xxx/test.json"```
When I removed the attribute part behind state I got an error message
state_attr() requires an attribute
I dont really want to have a restful sensor as a go between. Is there a way to make a get request in the sequence without using the rest command service, and then also be able to access the get result?
How can I edit this to count the day as 9am to 9am instead of midnight to midnight??
start: '{{ as_timestamp( now().replace(hour=0).replace(minute=0).replace(second=0) ) + (1 - now().weekday()) * 86400 }}'
duration: '24:00'
this works:
start: '{{ as_timestamp( now().replace(hour=9).replace(minute=0).replace(second=0) ) + (1 - now().weekday()) * 86400 }}'
duration: '24:00'
you can check in
-> template with:
{{ (as_timestamp( now().replace(hour=9).replace(minute=0).replace(second=0) ) + (1 - now().weekday()) * 86400) |timestamp_local}}
Hi, I'm trying to write a template which includes "e raised to the power of", or EXP(x) in Excel. I've tried exp(x) and math.exp(x) in my template, but am getting the result "Unavailable". Returning (x) by itself works in my code. Is there an equivalent?
Yes. Because maths. **0.5
just use e
e raised to the power of is simply
e**(value)
@mighty ledge Thanks, shows how much of a newbie programmer I am (didn't know ** meant raise to the power of).
Here's my little bit of code - It takes current indoor temperature and humidity and provides a "Feels Like" temperature - based on the Australian Bureau of Meteorology method ```sensor:
- platform: template
sensors:
citypad_feels_like:
value_template: >-
{% set t = states('sensor.citylink_temperature') | float %}
{% set rh = states('sensor.citylink_humidity') | float %}
{{(t+rh/100e**(17.27t/(237.7+t)))}}```
real feel is very triky to find out
BOM has a good writeup here: http://www.bom.gov.au/info/thermal_stress/?cid=003bl08&fbclid=IwAR2ycHTHeuK5eD2uFqoBMjHmbNX9GEwpDa3Owjhxy9arcOOmB4L5KjwdfQM
@proud rain i have this but not accurate on minus temp https://pastebin.ubuntu.com/p/5kKtkVPnVS/
Hi all, can someone please explain me how set_white_value works ? looking at docs I read this : Integer between 0 and 255 for how bright a dedicated white LED should be. but then i logs i see an error message looking for hue values.
@loud otter that's not a template question. Try #integrations-archived
can someone help me with my template
- platform: template
sensors:
front_door:
friendly_name: "Front Door State"
value_template: >-
{% if is_state('light.front_door', 'Unavailable' ) %}
Off
{% elif state_attr('slight.front_door', 'Off') %}
Off
{% else %}
on
{% endif %}
what is slight.front_door ?
Oh man
Typo
I am guessing thats the problem. I want to have it so if my front door light is off or manuelly turned off by the light switch, i want it to say off and not unavaliable
it work
which channel to ask for help with a binary sensor / mqtt reading a topic?
Thanks π
Anyone have some premade templates for displaying history stats from last week / month etc. ones with a drop down or date selector would be super nice π
Newbie programming question: {{t+rh/100*e**(17.27*t/(237.7+t)) | round(2)}} The first part of this is producing a float, I was hoping to round that to 2 decimal places with the second command. But I am still getting lots of decimal places. What am I doing wrong?
Thanks rawframe. In the end this worked: {% set t = states('sensor.citylink_temperature') | float %} {% set rh = states('sensor.citylink_humidity') | float %} {% set rf = t+rh/100*e**(17.27*t/(237.7+t)) %} {{rf | round(2)}}
Howdy folks. Running into some issues with templates. I copied this verbatim from the input_datetime integration page but am getting an error that I can't seem to figure out. Beta channel btw.
service: input_datetime.set_datetime
target:
entity_id: input_datetime.XXX
data:
timestamp: "{{ now().timestamp() }}"
Error:
Failed to call service input_datetime/set_datetime. expected float for dictionary value @ data['timestamp']
I'm just trying to set this input helper to "ten minutes from now"
service: input_datetime.set_datetime
entity_id: input_datetime.XXX
data:
timestamp: "{{ now().timestamp() }}"
Thanks for the help!
Turns out it's not working in Developer Tools > Services but does work in a script π€·
I'm trying to set up a toggle button that looks at the colour state of the bulb and and if its red, change to blue, if blue to red. I came across someone else talking about it,
entity_id: light.the_study_lamp
color_name: >
{% if is_state_attr('light.the_study_lamp','rgb_color',(255,0,0)) %} blue
Im a bit confused
You can't template in Developer Tools > Services
what's confusing
I'm using a template variables in an automation and it's not working for me, is this the right place for this?
I'm using variables in an automation but when I reload the automation I get not a valid value for dictionary value @ data['action'][1]['target']['entity_id']. Got None.
what are you using there?
it's based on this (and extremely ismilar) https://www.home-assistant.io/integrations/tag/#building-an-rfid-jukebox
share what you actually have
- id: handle_tag_scan
alias: "Handle Tag Scan"
mode: single
# Hide warnings when triggered while in delay.
max_exceeded: silent
variables:
# Map scanner device ID to media player entity ID
media_players:
3ac9a05c3c08687bf11ee545ba78aabb: media_player.a_room
# Map tag ID to content
tags:
F9-FB-3C-B2:
media_content_id: "https://www.youtube.com/watch?v=rLdpprJ3jeE"
media_content_type: music
trigger:
platform: event
event_type: tag_scanned
condition:
# Test that we support this device and tag
- "{{ trigger.event.data.tag_id in tags }}"
- "{{ trigger.event.data.device_id in media_players }}"
action:
- variables:
media_player_entity_id: "{{ media_players[trigger.event.data.device_id] }}"
media_content_id: "{{ tags[trigger.event.data.tag_id].media_content_id }}"
media_content_type: "{{ tags[trigger.event.data.tag_id].media_content_type }}"
- service: media_extractor.play_media
target:
entity_id: "{{ media_player_entity_id }}"
data:
media_content_id: "{{ media_content_id }}"
media_content_type: "{{ media_content_type }}"
- delay: 2 # timeout before we allow processing next scan
if there's a better place to share lmk
if I hard code the target line with entity_id: media_player.a_room everything works
this error occurs at automation reload time, not event fire time, so there isn't actually a trigger.event.data at that time (I think?)
i have never used that so i don't know
so this has two layers of variables it would seem the even data provides trigger.event.data.device_id but I need to use that value to then look up the media_player.a_room
but that data isn't available until "event time", but the action.target.entity_id is parsed and required at automation load time
I've tried to put maaaany things in the place of action[1].target.entity_id and it always says it evaluates to None
even things that hass guarantees to give me, e.g. "{{ trigger.event.event_type }}" or "{{ trigger.platform }}"
why won't it accept any variable there?
I've stripped this down to be a lot simpler now it's
- id: handle_tag_scan
variables:
# Map scanner device ID to media player entity ID
media_players:
3ac9a05c3c08687bf11ee545ba78aacc: media_player.a_room
avar: media_player.a_room
trigger:
platform: event
event_type: tag_scanned
action:
- service: media_extractor.play_media
target:
entity_id: "{{ avar }}"
data:
media_content_id: "https://www.youtube.com/watch?v=rLdpprJ3jeE"
media_content_type: music
looks like variables are not a part of automation directly? seems like they're a script thing so they'd only be valid in the action block
nope, that's wrong
i don't know how those work though
I'm pretty sure the target is not templatable until the release
Just put the entity_id inside data and you should be good to go
remove target
if you're in release of HA, target cannot be templated. If you're in the beta, you need to have the beta release that has the PR for templating in target.
where to ask question / help with a custom binary sensor / mqtt
trying to make custom sensor on which person is at home
Mqtt topic is
Message 2 received on ai/Living_hd/motion at 8:47 PM:
Person [MyName] (56%)
Message 3 received on ai/Living_hd/motion at 8:55 PM:
Person [MyGirlfriendsName] (88%)
How do i read the name only?
@mighty ledge thanks, yes I also learned that it's not yet supported but in the next release it will be and that is excellent!
@mighty ledge and @dreamy sinew ty both!
Hello! I have a question: How can I assign a latitude and longitude value to a non-tracking sensor so it shows on my map in the dashboard?
@autumn pasture based on what?
i have a sensor and i want it to show on map
it is a sensor that gets its value from mqtt
make a zone for it
oh!
nice
ok let me show you something
sensor tempcamp:
platform: mqtt
state_topic: '/devices/192.168.1.125/ai/1'
name: 'Temperature Camp'
#device_class: "temperature"
#qos: 0
#latitude: 47.6438
longitude: 67.3432
unit_of_measurement: 'Β°C'
value_template: '{{ (((value_json * 120)/10000) - 40) | round(2) }}'
you see where a entered the latitude and longitude ...
i doest not work liket that . where do i had the zone for that
i have created the zone ! yes i works ! i have it on the map now
how to connect my sensor to that zone now?
define template as {{ state_attr('zone.xxx','latitude') }}
i have to go... check this example and take only what u are interested https://pastebin.ubuntu.com/p/HpYmxb9RTJ/
Thanks man!
Im trying to get one of my templates to work where I use a utility_meter to calculate daily and monthly energy usage. I have several MQTT kwh meters. I have one for the total usage and that works. I have other that are connected to spa bath and heating. I wish to use the total β spa - heating to calculate the home household energy usage. I just cant get it to work, its always the same as the total house even tough that I tried different ways to calculate it:
huhallsel_total_kwh:
unit_of_measurement: 'KWh'
value_template: >-
{% set vattenfallkwh = states('sensor.vattenfall_total_kwh') | float %}
{% set ivtkwh = states('sensor.ivt_total_kwh') | float %}
{% set daikinkwh = states('sensor.daikin_total_Kwh') | float %}
{% set qlimakwh = states('sensor.qlima_vp_Total_Kwh') | float %}
{% set spakwh = states('sensor.spabad_total_kwh') | float %}
{% set value = ( vattenfallkwh - ivtkwh - daikinkwh - qlimakwh - spakwh ) | round(1) %}
{{ '{:.1f}'.format(value) }}
Each sensor has a correct value but the total is always the same as vattenfallkwh for the utility_meter
@echo siren What is the output of {{ value }}? (You can use the Template under Developer Tools to test your templates.)
Hi! the value is 8020.1, im thinking that there is some issue with the updates of each sensor, since its not additive the sensor will go up and down in total kwh, could this be an issues for utility_meter? The current value is correct but the utility_meter is the same as for the utility_meter for vattenfall_total_kwh
@echo siren What is the output of the following template:
vattenfallkwh: {{ states('sensor.vattenfall_total_kwh')|float }}
ivtkwh: {{ states('sensor.ivt_total_kwh')|float }}
daikinkwh: {{ states('sensor.daikin_total_kwh')|float }}
qlimakwh: {{ states('sensor.qlima_vp_total_kwh')|float }}
spakwh: {{ states('sensor.spabad_total_kwh')|float }}
vattenfallkwh: 12748.9
ivtkwh: 0.0
daikinkwh: 1678.8
qlimakwh: 690.8
spakwh: 2358.7
Try taking out ivtkwh and see what value returns.
value is the same, 8020.9
Im starting to think that the sensor huhallsel_total_kwh is working fine, but its the utility_meter funktion that does not work when a sensor has minus in it
8020.6 is what I calculate based on the values you gave above.
What is vattenfall_total_kwh compare to huhallsel_total_kwh?
Based on the values you gave me, the template seems to be calculating just fine.
I did a history graph and the total spent today is 27.1 and the house hold is 19.9. But the utility_meter is still present as 27.1 for the house hold. So the template is working, but the utility_meter is not working. Big thanks dale3h π
how do i make this update every minute instead of seconds and give a result in minutes instead of secons
{{ (as_timestamp(strptime(states('sensor.cert_expiry_timestamp_domain_name'), "")) - as_timestamp(now()))|round(0) }}
or hours
even better
anyone got any secret way to convert color_xy into color_hsl for a template?
Dear all, I am seriously struggling with getting my cover (i.e. garage door). I've gone over documentation, examples, threads and the darn garage door won't budge.
My current cover config above - the doors are operating a Satel alarm integration to initiate movement of the gate.
There is a single binary sensor detecting the state. No position detection
Hey .. we have added ' attribute template' ... and it worked for sensor that are declared under platform template but it doesnt work for sensor under platform_mqtt... here is the code we created for platform template sensor: sensor:
- platform: template
sensors:
analog_input_5:
friendly_name: "Analog Input 5"
value_template: '{{ states.sensor.hidden_current_state.attributes["CurrentState"]["AnalogInput"][4]["Measure"].split(" ")[0] }}'
unit_of_measurement: "Β°C"
attribute_templates:
latitude: '47.649328'
longitude: '-67.412194'
The doors are operating just fine from the alarm level and when operated from external buttons and/or apps, the position detection in HA is updated correctly
The Satel integration also properly detects motion in the house, as well as all the binary door sensors, so I am fairly confident it's working correctly.
but for sensor under platform_mqtt i can find the formulation to add the longitude and latitude attribute : sensor temptrailer:
platform: mqtt
state_topic: '/devices/192.168.1.120/ai/0'
name: 'Temperature Trailer'
attribute_templates:
longitude: '47.613777'
latitude: '-67.417687'
unit_of_measurement: 'Β°C'
value_template: '{{ ((value_json * 50)/10000) | round(2) }}'
@vestal idol use #frontend-archived, that's not a templating question. Also please don't post codewalls.
I've deleted the message sorry for posting in the wrong group π
Any help would be greatly appreciated! π
what is it not doing that you want it to do?
Pressing either if the buttons for this cover results in no action from the garage doors
Can you confirm my syntax is correct?
so your switch.garage_door actuates your garage door? is it momentary, or does it turn on when open and off when closed?
It's supposed to be momentary, but it's a class switch
I currently have it as
entities:
- entity: cover.garage_door
show_header_toggle: false
type: entities
title: Garage
state_color: true
In Lovelace and the icon properly follows the state of the door but the card doesn't actuate it.
you'd have to do some sort of tap_action for the card, as the cover entity wouldn't function that way. might look into something like https://github.com/thomasloven/lovelace-slider-entity-row
although I suppose you could change to type: button if you want it to pop up the cover dialog
then when you click on it, the cover details should pop up, and you can open/close/stop
I'll try playing with action types and button, but not sure if it will work.
Thank for the help so far!
Hey guys! Is the command for a command line switch templateable? I'd like to make a timelapse from camera snapshots using this template but I'm getting an error.
create_timelapse_from_jpgs:
command_on: >-
ssh -i /config/.ssh/id_rsa -o StrictHostKeyChecking=no -q
root@192.168.1.252
find /usr/share/hassio/homeassistant/www/snapshots/{{ (as_timestamp(now()) - (24*3600)) | timestamp_custom('%Y-%m-%d', True) }} -empty -type f -delete &&
ffmpeg -framerate 60 -pattern_type glob -i "/usr/share/hassio/homeassistant/snapshots/{{ (as_timestamp(now()) - (24*3600)) | timestamp_custom('%Y-%m-%d', True) }}*.jpg" -c:v libx264 -crf 24 -pix_fmt yuv420p /usr/share/hassio/media/timelapse_{{ (as_timestamp(now()) - (24*3600)) | timestamp_custom('%Y-%m-%d', True) }}.mp4
Basically I want to run ffmpeg on all the snapshots created yesterday. These are located in /snapshots/2021-03-01. But that changes every day of course.
@strange agate I've made great progress, since both the garage door and main gate open - the issue was a combination of inconsistent documentation for the integration and setting up switches appropriately.
One last thing that doesn't work is the cover implementation in Lovelace
The up botton works just fine
So does the middle one, for both stopping, opening and closing
But then the gate is open the down button doesn't work
if your switch is a momentary, you may need to change the entity to switch.turn_on for the close_cover
assuming it just turns the switch on every time the garage is actuated
Correct, it's just a 2 second momentary MONO on the alarm side.
right, so it would be a "on" then instead of an "off" like in your code you posted
Right, I didn't spot that
Absolutely makes sense!!
Thank you so very much for the input.
I am so loving HA and the community. Learning so much every day.
It's 2 am and I am still excited playing around with the code #crazy!
yup, same π it's a blast haha
Last thing - is there an option to set up a 'universal' button icon, since all my 3 are actually the same thing
I could forgo the stop for sure, by deleting it from the config
I wonder about switching to just stop or if another one exists for a universal 'click' in the cover template
potentially something like https://github.com/benct/lovelace-multiple-entity-row
I haven't used it, but might be what you're looking for
has anyone written a sensor or template to display whether there are updates (to the images) of the containers used by HA (including HA itself) ?
I'd like to see when there's an update for my containers (HA, nodered, etc.) , and then read to make sure no breaking change and then update
Iβve spent hours reading up on how to do this and I cannot figure it out. Iβve only been using HA for about two weeks. Here is what Iβm wanting:
A switch that flips when any of the sensors on my litter bots read above 95 full. Iβve tried virtual sensors, virtual switches, IF then conditions and I cannot get it to work. I would paste my code in here but I think with my frustration itβs turned into gibberish. Where should I start please? (Also first time HA discord) thanks in advance!
- platform: rest
name: Codium Version Latest
resource: 'https://api.github.com/repos/VSCodium/vscodium/releases/latest'
username: !secret github_username
password: !secret github_secret
value_template: >-
{{ value_json.tag_name }}
scan_interval: 3660
That's how you can get the value of the latest version if the project in question releases versions... Some don't.
For HA itself, there is already a sensor for that: updater.
thank u this is golden! now i need to figure out how to pull the container version (for instance mosquitto or nodered), is a shell command the only way to bubble this back up?
that one's tough. I ended up going with running a script that I wrote on the host system that runs this (/usr/bin/docker logs vscode 2>&1 | awk '/] info code-server [0-9]/{print "{ \"version\": \"" $4 "\" }"; exit}' to store that in a variable that gets published to mqtt. Then I have a sensor in HA that monitors that topic in mqtt (software_versions/vscode is the topic).
The script loops through a bunch of the software I run and publishes the versions of each of the packages to mqtt. So I have "PACKAGE_version" and "PACKAGE_latest_version" and if they're not the same, I get notified.
ah thats a smart solution, verbose but def does the job
so u have the script running on a regular cron job i imagine?
I discovered this- and thought u might find interesting as well!
When using this: wait_template: "{{ is_state('media_player.floor', 'stop') }}"
How could I modify that template to to make sure the state is stop for at least 10 seconds?
(I want the automation to wait until a certain state changes for at least 10 seconds as an example)
probably a separate automation that flips a input bool to true when the media player goes to stop for 10s
Mhm, okay.
would need to have something to reset it though
Hello there! I have some weird error with the developer-tools -> Template function... somehow the preview on the right side is not working anymore. Top right loading animation spins forever. What could be wrong here?
oh no... nevermind... cache problem π¦
Hello, let's say I have defined a template sensor, collecting room temperature once every second.
Then I change the name of the said sensor in my config file. What happens to the data collected with the old name? Does that remain in the database somewhere as a piece of junk, or is the corresponding data deleted with my sensor name change?
OK. Let's say, during the development phase, I want to reset or clear the sensor history. How is this done? Up until now I changed name of it, to be able to view just new data.
Hmm I'm not sure. Is there a default? I don't think I've specified it anywhere...
default is... documentation
Point taken! π Thank you
I have spent hours and hours. I cannot figure this out. I have three sensors: sensor.hallbot_waste_drawer
sensor.bar_bot_waste_drawer
sensor.catroom_bot_waste_drawer
If anyone of them is about 95 in value I want the virtual switch anylitterfullswitch to be turned on. If none of them are above 95 I want it off. Here is what I have. I thought I was so close but I get this error when I check it's status as "unavailable."
Here is my code (PLEASE help me):
switch:
- platform: template
switches:
anylitterfullswitch:
value_template: "{{ (states('sensor.hallbot_waste_drawer')|int > 90),
or (states('sensor.bar_bot_waste_drawer')|int > 90),
or (states('sensor.catroom_bot_waste_drawer')|int > 90)}}"
turn_on:
service: switch.turn_on
target:
entity_id: switch.anylitterfullswitch
turn_off:
service: switch.turn_off
target:
entity_id: switch.anylitterfullswitch
Greetings π
Can I regex_match a variable in templates?
for example: {% if rooms_to_clean|regex_match("^"myvar"$|,") == true %}yes{% endif -%}
maybe?
try it out in the template tester
there are some regex methods exposed which can be found in the docs
trying but can't really find a way around that string and variable concatenation
I am trying to implement a test sensor with the following value template
value_template: '{{ value_json.24hreward }}'
but that doesnt work because there are number in that
This would work but its not what I need
value_template: '{{ value_json.reward }}'
can somebody tell me what syntax I need to use to get numbers to work here?
@wicked ferry do you have a switch.anylitterfullswitch entity? from what I understand, you want to create something along the lines of input_boolean helper and then use your switch to reference it.
(or binary sensor in this case might be more helpful since you won't plan on toggling it manually)
for those how are wondering its
value_template: '{{value_json["24hreward"]}}'
the double quotes are important
eh, type of quotes isn't important
"{{ value_json['24hreward'] }}" is equivalent
value_json.get('24hreward') would also work with the added benefit of not throwing a value-error on miss
{{ states['media_player.spotify_jon_graft'].state }} returns playing. How do I return the track name & artist that is actively playing?
Answer to my own question: {{ state_attr('media_player.spotify_jon_graft', 'media_title') }} - {{ state_attr('media_player.spotify_jon_graft', 'media_artist') }}
i would like to make a binary sensor to see who is at home
Therefore I've configured my camera's with face detection which sends mqtt messages
The topic contains ai/Default/motion Person [Eric] (91%),Person [Nick] (84%),Person [Finn] (78%),Person [Luke] (87%),Potted plant (79%) "
What is my best way to strip these names? I don't need to know if the potted plant is at home π
Dont know really where to look since all tutorials i find about mqtt is how to send messages
@strange agate thanks so much for help! Iβve tried adding a virtual switch and also tried adding a helper. Still cannot get it to give me anything beyond unavailable.l for switch state. Any other ideas? Thank again!
So I'm going a bit crazy with the template engine. I'm not entirely sure what it is, it seems specific to the MQTT climate module - that appears to, as best I can tell from the source, use the "async_render_with_possible_json_value" method to render the template for the temperature command, which strikes me as weird as that seems more designed to process input, not render a command. More importantly, it's kind of broken - after I'd finally figured out they used this and the target temperature was therefore "value_json" and not a more helpful name, I tried to make it work to render a very simple JSON to push out to MQTT - namely, "{"action":"set","value": {{value_json|float}} }". When I leave it without that template section it correctly sends out the JSON, obviously without anything filled in, but as soon as I add the value_json|float it only throws the number to MQTT, dropping the entire rest of the template. I'm kind of running out of ideas and sanity here, am I doing something stupidly wrong?
I've gone so far as even trying to have the {{}} at the top level and use Jinja string concatenations but somehow even that works exactly until I cast value_json to a float - if I leave that out or don't convert it (resulting in a null as far as I can tell) the entire thing renders fine but as soon as the number comes in everything else disappears.
Okay, so now I have even more questions. I dug further into the code that Home Assistant actually uses to parse these templates, and apparently it also exposes a "value", in addition to "value_json". And guess what, when you use value instead of value_json|float it suddenly renders properly! I have no idea why that even makes a difference, and I really don't know why the climate module uses this version of the template renderer in the first place instead of one with named variables, but honestly I'm mostly hoping somebody can add this to the documentation page for the Climate/MQTT module so other people know to use "value" and not lose an hour of their life thinking they're going crazy like me.
@devout badge All templates render objects as real values after the template is complete. Most likely your resulting type was wrong or malformed
Use the template editor next time and make a value_json variable that represents the json that would have been passed and you can see how the template will be rendered
Also, all value_template fields in configurations have 2 variables: value and value_json. This has been this way for a very long time.
Usually the examples cover this. Otherwise youβre welcome to make changes to the documentation yourself
I used the template editor, or I tried. It didn't hit the same issue as far as I could tell, though it did tell me my output was a dict.
Yes you canβt return a dict
I know that now, after digging through the code. It just took me a while to get there.
No but keeping it value keeps the object in tact
The only thing I changed was now I use value instead of value_json|float
Oh.
Okay, so that still leaves two things that confuse me: a) it seems most other modules use named variables in their command templates, not the generic "value", and b) the fact that the Climate module seems to have so little documentation confirmed to everything else. There is literally not a single command template example other than a single one for reading mode_state that is literally just "{{ value_json }}".
How would one go about writing more examples? How is this doc generated/edited?
Also now that I think about it, why/how does that dict turn into a single number? That seems like a very weird failure mode.
Yes named variables are everywhere
So why does this module specifically not use them? Is that just a holdover from times past that nobody has bothered to change or is there a reason?
Which template field are you talking about
temperature_command_template
Probably an oversite
Anyway, the lack of documentation and examples around that made it kind of hard to even figure out what variable to use, and when I thought I'd figured that out obviously I ran into that issue with it becoming a dict.
Youβre welcome to make edits to the page
^
Thereβs a βeditβ at the bottom of the docs page
Nevermind I just realised
I didn't see that because I wasn't scrolled all the way down
You can also just provide feedback
Guess I'll suggest better examples now, specifically around these templates, and maybe I'll come back later and write some myself if I have the time
It looks like you're trying to create a switch that references itself. Have you checked your value_template in Dev Tools? Assuming it works, I'd consider using a binary sensor. It'll get rid of the need for an additional helper entity. https://www.home-assistant.io/integrations/binary_sensor.template/
hi
Hi. I know this is probably pretty basic so please forgive me (I'm new to HASS and still getting my head around the nomenclature).
I have 20-odd CCTV cameras which publish to an MQTT topic when they detect motion. cctv/+/motion (where the wildcard is the name of the camera). Payload is a JSON string containing some info about the detection.
Is there a way I can have HASS auto-generate entities & sensors for all these cameras automatically when they publish vs setting up entities & sensors manually for each?
Not a big deal if it can't but figured it'd be something that would be possible.
....Is templating how I'd accomplish this or am I completely barking up the wrong tree.
NB. I'm aware of MQTT Discovery, but not sure whether that would be useful in this context.
Hello, why Im getting an error 'UndefinedError: 'device_tracker' is undefined' when I add this to my template sketch: {{ states.device_tracker.stefans_iphone.last_chaged }}
even if I add only {{ device_tracker.stefans_iphone }} it has the same error
Yes you can, thatβs what discovery is for.
You misspelled last_changed
That second template is wrong format
oh I see..thanks!
and how to set two random entities for covers
here is random entitiy for one
data:
position: >
{{ range(20,100)|random }}
entity_id: >
cover.{{ ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] | random }}
so if I wrote something like this ```
- service: cover.set_cover_position
data:
position: >
{{ range(20,100)|random }}
entity_id: >
- cover.{{ ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] | random }}
- cover.{{ ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] | random }}
How to be sure that HA wont pick two same entities?
Iβm not at a computer so maybe someone else can type it out
But you need to return a list.
First make the list, then select a random one, then filter the selected one out of the list and select a second random one
set first = Mylist | random
set second = Mylist | reject(first) | random
{{ [ first, second ] }}
I want to measure the time since status change on a door contact sensor. I have it working but everytime I reboot HA server it sets it back to zero. What's the best way to have the time since sensor change hold through a restart of HA server? Thanks in advance!
Save the information in an input_datetime with an automation or use an external db to store the info like mqtt
Hey all. During the release party live stream I noticed this on the release notes: Templates can now be used to create weather entities. So far I haven't been able to find any docs on what the weather entity should look like, and how to template it. Does anyone have any idea?
Just add a type filter to state_attr() call
thanks petro, I will try
{% set covers = ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] %}
{% set first = covers | random %}
{% set second = covers | reject(first) | random %}```
Im getting an error TypeError: object of type 'generator' has no len()
If i remove last row, and just print {{first}} it gives me ok result, so I guess there is some error in the last row?
I think I found solution {% set covers = ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] %} {% set first = covers | random %} {% set second = covers | reject('==',first) | list | random%} π
Hi guys, is it possible to use the jinja abs() to get the absolute value from a number? Template editor threw an error to this:
{{ abs((states('sensor.daily_covid_cases') | int) - (states('sensor.daily_covid_cases_yesterday') | int)) }}
Update: Figured it out
{{ ((states('sensor.daily_covid_cases') | int) - (states('sensor.daily_covid_cases_yesterday') | int))|abs }}
hey there! Am I the only one who gets messed up Automations and Script because of the GUI introduced on 2021.3.0? It seems that it wipes out the templates that doesn't recognise and if you want to change something in the Automation or Script and then save, you got a messed up one...
Hi Im on 2021.3.2 and cant do backups either manually or automated. Always say system is in freeze state
Hey, is there a way I can get the length of time an entity has been in its latest state from a template? I suppose other than having an sql sensor to get the time between the last 2 entries of said entity in the states table
One way would be to have an automation trigger on the state change and save the current time, so later you can do some math to get the duration. (I have not tried this. but I thing it should work)
Thereβs a last_changed attribute
Also, on a standard entities card, you can display secondary info, and one of the pieces of info is the last time the state changed
And you can expose last_changed in a template sensor with device class timestamp and the front end will properly calculate the relative time on most cards
This channel is for template questions, you should ask that in #general-archived
Oh fantastic idea
Itβs a property, not an attribute btw
Itβs on the state object itself
Ah, ok. So how would I pull that out? states('entity').last_changed? or would it have to be states.domain.entity.last_changed?
states.domain.object_id.last_changed
notify:
- name: gmail
platform: smtp
server: smtp.gmail.com
port: 587
timeout: 15
sender: email@gmail.com
encryption: starttls
username: email@gmail.com
password: password
recipient:
- email@gmail.com
sender_name: My Home Assistant
Setting up email notifications and I'm getting the error "component not found: notify." anyone know how to fix this?
Ask in #integrations-archived
Hi! How do you guys debug your templates? I have a template which looks fine in Developer Tools/Template, but can not be used as-is within the weather template I'm trying to build - I think due to escape issues which I think I have fixed, but how can I e.g. see the result of instantiating my template? I could post more info on my particular problem, but I am more interested in how problems like this are to be debugged in general...
How could I get the sun's next_rising and the next_setting in relative time?
I've tried The sun will set in about {{ relative_time(state_attr("sun.sun", "next_rising")) }} π
But that shows 2021-03-08T06:11:24+00:00
So, I think after hours I got my mqtt up and running. I'm trying to show on a card the time since last sensor change. I got it to work but its returning a value that's not user friendly. How do I convert this:
2021-03-07 18:55:59.269596-06:00
Into something useful?
Since you don't say the exact desired format, start with this: {{ as_timestamp(mytime) | timestamp_custom('%D %-I:%M %P') }}
Added with this https://strftime.org/ and you should be able to craft all the worlds timeformats
Thanks so much. How might I change it to time days hours minutes since that time stamp above? That's actually what I really need.
Do I put that in the configuration file under this?
sensor:
- platform: mqtt
state_topic: "events/clarkmeowspace/on"
name: "MQTT ClarkMeowSpace"
you create a template sensor
Is that wrong? Sorry. I'm new to this and I spent hours to get this to work.
I'm trying to preserve time since sensor change and make it last a HA reboot.
Put it into sensors value_template field
That's something new fo rm.e
your mqtt sensor is fine. if you want to use a template to further manipulate that value to represent something else, you would just a template sensor
Thank you!
this seems to work in the developer tools template but cannot get it to work in the config. Any help?
clark_meowspace_last_changed:
value_template: "{{relative_time(states.sensor.mqtt_clarkmeowspace.last_changed)}}"
Tools Template Result:
clark_meowspace_last_changed:
friendly_name: 'Clark Last In MeowSpace'
icon_template: mdi:clock-outline
value_template: "18 minutes"
When I check the config file I get this error:
Error loading /config/configuration.yaml: while scanning for the next token
found character '\t' that cannot start any token
in "/config/configuration.yaml", line 63, column 1
Hi everyone, I have a template sensor that infers value based on relative last_updated attributes of two other sensors. Is there a way to preserve its value between restart of HA?
Howdy π I'd like to build a template sensor that shows some data about the access point a mobile device is connected to. To achieve this, I need to hardcode a hash map of some sort with data like: aa:bb:cc:dd:ee:ff: Living Room 5GHz AP (mac_address: ap_info).
What's the best way to store config data like this? Input_text is not an option as that's limited to 255 chars and I've got ~300. So I was thinking building a template sensor, using the mac addresses as attributes, and "attribute values for "ap_info" - but that seems to be returning "None".
likely the simplest thing to do would be to build a template sensor with a state that's JSON, serialize it and use as is - but before I jump into that rabbit hole: is there a better way of doing this I wonder?
yep,
i use https://paste.ubuntu.com/p/xcw2rybCwH/ for 5ghz
and another one for 2.4ghz
json looks like this
https://paste.ubuntu.com/p/2gMHWsStp7/
@unreal merlin
great, thanks
I've been working on something similar. The only way I found was to use mqtt. Love to know if you find another way. I'm still working on getting mine right. It's been a steep learning curve for me.
I have a sensor that is giving me the time that an event happened:
2021-03-08 05:57:30.267209-06:00
How do I turn this into hours minutes from current time? If the time stamp was for 10 minutes ago, I want the output to say 10 minutes ago or something similar. I'm flexible I just need this time since that timestamp and have it update when I use on a card. I've spend so much time figuring this out using mqtt. I just cannot take it home. Thanks in advance!
pulling what's left of my hair out trying to catch a trigger event from mqtt which has a json-formatted payload but for reasons i don't want to parse it out as JSON
in my automation, for debug purposes i have the following:
trigger.payload: {{trigger.payload}} - buttonjsonpayload: {{buttonjsonpayload}} - trigger.payload == buttonjsonpayload: {{trigger.payload == buttonjsonpayload}}
spitting that out to MQTT i see the following:
trigger.payload: {"event_type":"button_short_release","event":"p[1].b[5]","value":"OFF"} - buttonjsonpayload: {"event_type":"button_short_release","event":"p[1].b[5]","value":"OFF"} - trigger.payload == buttonjsonpayload: False
so, i have two values trigger.payload and buttonjsonpayload. this is in the context of a blueprint, buttonjsonpayload is created in the variables: section. When sent to MQTT, both value render to matching strings. when compared, they don't.
casting both to string (like {{trigger.payload|string == buttonjsonpayload|string}}) doesn't change the outcome
Hello all, is there a rule somewhere that states an entity ID cant start with a number? or am I doing something wrong?
{{ states.sensor.5in1_temperature.state }} and inside set temp is {{ states.input_number.climate_set_temp.state }}
returns TemplateSyntaxError: expected token 'end of print statement', got 'in1_temperature'
dot walking doesn't work with vars that start with a number
states.sensor['5in1_temperature'].state would work
or states('sensor.5in1_temperature')
How can I combine this into one?
- platform: template
sensors:
smoke_detected:
friendly_name: Smoke Detected
value_template: >-
{{ is_state('sensor.smoke_detector_main_alarmlevel','1')
or is_state('sensor.smoke_detector_main_alarmlevel','2') }}
{{ states('sensor.smoke_detector_main_alarmlevel') in ['1', '2'] }}
i figured it was simple, thanks
Hi! Is it possible to get the current icon of an entity? I cannot find it as an attribute.
i have problems with json api tat returns numbers as string eg. "1.17" its a list i want to use the list | sum for mothly statistics
[{ "id": 301, "day": "2021-01-02", "electricity1_cost": "1.17" }, { "id": 302, "day": "2021-01-03", "electricity1_cost": "0.90" }]
what would be the easy way to convert the numbers to float ?
|map(attribute='electricity1_cost')|map('float')|sum
could try dropping the float map and see what happens though
Hey all, trying to work in a value template into a numeric condition for above but it doesn't seem to take it. Anyone have any ideas? https://hatebin.com/agukapwrap
you have a typo in your URL, and fixing it leads to a blank page
is there a simple way to add or subtract x months from {{ now() - 6months }} {{ now() + 3months }}
Is it possible use templating to catch all sensor states of a certain measurement unit? Say i want to sum all consumption values where the unit is kWH?
The link actually works for me btw
use {{ state_attr('weather.kklo_daynight', 'temperature')|int }} not {% something something %}
Is there a way to set a state for a binary_sensor if conditions are met, say for 60 seconds or more? This for my illuminance sensor telling if it is dark outside (to turn on lights)
binary_sensor:
- platform: template
sensors:
dark_inside:
friendly_name: MΓΈrkt innendΓΈrs
value_template: "{{ states('sensor.pir_ute_paviljong_illuminance')|float < 700 }}"
sun elevation could be better
not really.
Sun elevation do not take into account how much light is emittet all through the year.
Especially will this come to play at 60 degrees north where I live. Where the sun sets at 22:00 and rises at 03:30 in the summer, and in winter.... π
So after testing over some years I find illuminance to be the most accurate method
so take straight measurement from sensor
I do, but when there is a glitch form the sensor, eg. reporting wrong value the light automation will fire. So I will have to work around this, and was hoping the sensor state could be set somehow after the state was below the trheshold for some time.
in automation u can put a time condition if luminance drops under your threshold
Can a template sensor generate new sensors? Say from a list?
Hi All. Could some template guru please help me change the state text in an entities card. I have been puzzling over this for hours. I'm afraid the entry bar is still too steep for me at the moment... https://paste.ubuntu.com/p/VH7kngM3Pt/ 
So, if I have 25 sensors I want to do calculations on, there is no way around templating every single one of them?
Correct
#feature-idea π€£
You can use the template editor to write the code for you
Really?
Yep
Link to learn how?
Thatβs going to change depending on what youβre trying to do
Thereβs no real learning page
Hi all! I am looking for some help with utility meters. I have some floor thermostats that sometimes report crazy kwh usage that messes up my history graphs so I need to "wash" them. Is there a way I can do this with templates? pass the kwh sensor through a template which removes crazy peaks?
Hello all... been reading on the templating page and also the jinja docs, and i'm having trouble figuring out how to do something that I thought would be relatively simple. I've got an incoming MQTT message that is just text (not JSON), and i'd like to extract a portion out of it as a sensor. For example, if the message on the topic is just a string like "The battery voltage for 21231 is 3.02V", i'd like to have a value template that just extracts out the 3.02V from that message. But even with the regex filter I'm not really sure how to do that. Can anyone give me an example on how to parse out a value from a text string?
ok, i think i'm closer... i was able to do "{{ value.split(' ')[-1] }}" and that gets me 3.02V, but it also requires the string i'm looking for to be at the end, so I suppose if the message is sometimes "The battery voltage for 21231 is 3.02V (low)" then it won't get the right string. I guess i just want to search the string for \d.\d*V
It's hard to parse arbitrary data
History Stats - is it possible to use this to report time since a sensor was state "on?" And will it survive a server reboot? I tried using mqtt but gave up after about 20 hours of not being able to get the time to format in a usable manner. Any help would be super apprecaited.
Does anyone know if it's possible to call a script for each item in a JSON list? I'm receiving the JSON object through webhook trigger in an automation. I've been trying to find a way to template a for loop either in the script sequence or the automation action but I fear what I want might not be possible. Any help would be great!
can anyone help me with a rest sensor? I cant get it to populate with info
Hey all! I'm looking for example of template fan. In the latest version I can there was percentage added to control the fan. I have sonoff dual which controls 2 speeds of a fan (0,1,2). I'm looking for working example so I could understand how it works now and I could copy it to my HA. Thanks!
hmm is there a way to stop processing templates, e.g. like a "{% set this=that %} {% return %}"?
like returning from a function for lacking a better term
I saw in the release notes for 2021.3 that "Templates can now be used to create weather entities". Is there an example or instructions on how to do this? I am getting a weather station shortly and would like the temp, humidity, wind, etc. to be pulled from the local weather station, but the forecast information to be pulled from my AccuWeather integration. Any help you can give is greatly appreciated. Thanks.
When in doubt check the docs. https://www.home-assistant.io/integrations/weather.template/#configuration
Thereβs no way to return early.
You can make a nested if statement and as long as your logic is correct, it will return on whatever if/then branch youβre on
functions are a thing in jinja. they're called macro
but if you find yourself looking to one of those you probably need to re-evaluate your logic
in the following example, will cl match now()? I'm asking because cl doesnt seem to include microseconds and now() dose
{% set cl = strptime(states('SOME_SENSOR'), '%Y-%m-%d %H:%M:%S%z') + timedelta(hours=-2) %} {{ cl == utcnow()}}
Just replace microseconds and seconds with zero in both datetimes
guys, do you know any workaround for using 'None' string in templates? (https://github.com/home-assistant/core/issues/43584#issuecomment-732725960)
i want to sync a input_select in HA with MQTT topic. Unfortunately one of the possible states of MQTT topic is "none" and HA doesnt allow templates with "none" in them
I just updated my HA to 2021.3.3 because apparently that has the latest plexapi in it. But due to the change in the services, I am struggling to construct the code to call the service as a test.
Previously I went to "Developer Tools" > "Services". Selected the media_player.play_media service, and then put the following in for the service data:
media_content_type: EPISODE
media_content_id: '{ "library_name": "TV Shows", "show_name": "Spycraft", "shuffle": "1" }'```
Which doesn't appear to work now, so now I'm trying to use the new service. I have went to "YAML Mode" and have been trying the follow, but to no avail. Has anyont got any ideas?:
```service: media_player.play_media
target:
entity_id: media_player.plex_plex_for_samsung_tv_2019
data:
media_content_id: '{ "library_name": "TV Shows", "show_name": "Spycraft" }'
media_content_type: EPISODE```
cc: @marble needle
Can template entities be placed in an Area?
Can you elaborate on how?
Do you mean like this {{ cl == utcnow().strftime('%Y-%m-%d %H:%M:%S+00:00') }}?
With .replace(). Look up datetime objects and their built in methods
oh, duh. Thanks!
why not use any other word?
none as the key is fine, it doesn't like None as the value
noob question:
i have 1 sensor and want to create a template sensor with sensor * 1,5 -> how would be the correct syntax?
value_template: "{{ states('sensor.nice_sensor') |float *'1,5' }}" < like this?
thank you, gonna try it
what to do to cut the result to x.xx ?
"{{ states('sensor.waschmaschine_monat') |float * 0.246 | round(2) }}"
Result is: "0.10500000000000001"
sensor is: 0,07
You are rounding 0.246 to two digits now
Use brackets to make sure the calculated value is rounded instead
yea got it, thank you
"{{ (states('sensor.waschmaschine_monat') |float * 0.246) | round(2) }}" -> works π
Thanks. I am not sure how I missed that.
Hi guys, I cant seem to get my template sensors with data from my car working. I use Bluelinky for Node RED and send an MQTT message to my broker
Unfortunately my value_template doesnΒ΄t work. It will always say "Offen" Even when the raw data I configured in a different sensor says False. Thats the config I created:
- platform: mqtt
name: "Kona Kofferraum"
state_topic: "kona/status"
value_template: "{{ 'Geschlossen' if value_json.status.trunkOpen == 'False' else 'Offen' }}"
unique_id: sensor.kona_kofferraum
Any idea why thats not working?
If itβs json, false is not a string
Yes, itΒ΄s json. So what would I need to change that to?
Just False without the ´´ right?
Ended up using mqtt with retain flag too. Works fine. Thanks!
Yes
Perfect! Thats it. Got it working now. Thank you so much.
Hello I need a little help regarding my script with syncing tvo volume attributes on two entites
I just want to be observable one automation, it has two media_players as triggers
and I dont know how to pass for last row in my automation based on which trigger is called, to set another one?
this works ok https://paste.ubuntu.com/p/zkfdfPWgzX/, but kind a slow
If thatβs slow, itβs slow because of your media devices
Yeah, I assumed that. Although both my media_players are wired..
Is there a way to get the current theme? I want to use different colors in a card, depending on the current theme, so I would like something like this:
{% if is_state('homeassistant-theme', 'dark') %}
'#ffffff
{% elif is_state('homeassistant-theme', 'light') %}
'#000000'
{% else %}
'#000000'
I am trying to use a template to create a dynamic list of entities to add to a group. I saw an example somewhere of how to create a list, but I am just not getting the syntax correct, and I can no longer find the example. This is the code I use: https://paste.ubuntu.com/p/RKB22DSWNz/
The result an empty list. The actual list should be what is printed out, but the result is ['empty'].
sensor.basement_heating
sensor.dining_room_heating
sensor.guest_room_heating
sensor.kitchen_heating
sensor.living_room_heating
sensor.master_bedroom_heating
sensor.office_heating
['empty']
Given:
{% set cl = strptime(states('sensor.jewish_calendar_upcoming_candle_lighting'), '%Y-%m-%d %H:%M:%S%z') %} {{ cl + timedelta(hours=-1, minutes=-34) }} {{ utcnow().replace(second=0, microsecond=0) }} {{ cl == utcnow().replace(second=0, microsecond=0) }}
Which shows in dev tools as
2021-03-12 13:29:00+00:00 2021-03-12 13:29:00+00:00 False
Why is the condition false? Aren't the times equal??
I bet it has to do with timezone. What gives the following ?
{{ as_timestamp(cl + timedelta(hours=-1, minutes=-34)) }}```
you have to create a namespace to do that. Everything you change in a for won't impact the variable defined outside the loop
Or just use this {{ states | selectattr('name', '==', 'Thermostat heating') | map(attribute='entity_id') | list }}
@deft timber fwiw, {{ cl.tzname() == utcnow().tzname() }} is true
Datetimes eq method compares more than whatβs on the surface. Make them timestamps or compare the strings.
Great tip, many thanks @deft timber
I have a question about changing the update frequency on a sensor, which channel should I go? I have a MQTT sensor which updates too fast and fills the database, want to reduce the frequency
Great, thanks π
Hey all, apologies if this has been asked but I can't seem to find it. I'm setting up a chores tracker with NFC tags and input_datetime entities. I'm trying to build sensors off of the input_datetimes that are some amount of time in the future (like 90 days for an air filter) but having trouble templating because everything is different variable types. I'd like to just do something like {{ states('input_datetime.last_air_filter') + timedelta(days=90) }} but obviously states is returning a string and timedelta a datetime object. I can convert everything to timestamps with the filter, but it seems silly to convert both to a timestamp rather than just finding some common type I can pull directly. Any thoughts on how to better accomplish this?
Ah I see my problem. states('etc') returns a string. states.etc.state returns the object. Of course docs recommmend not using states.etc.state, but seems way better for this use case
Well, no, states.etc.state still returns a string. So that doesn't fix it. I'm now trying to use strptime except even when I use that I get a concatenation error
states.domain.object_id returns the state object. states.domain.object_id.state returns a string
Yeah, just seems like there's no easy way to pull the object that's held by state. Confusing way to word it but if the state is a datetime object either states.domain.object_id.state or states('domain.object_id') both return strings instead of a datetime object
States are always strings
There is no datetime object associated with state objects other than last_changed and last_updated
As phnx said, all states are strings
state attrs can be anything but the state itself is always a string
hi, I'm trying to create a 'cooking' sensor. there's a temperature sensor above the stove and one in the living room. I'd like a binary_sensor (cooking) to turn on if the sensor above the stove is 3 degrees higher than the one in the living room. I use a similar sensor in summer to tell me when to open/close the windows that I think I can use as a start but I need help to change the +3 degree difference. here's what I have:
- platform: template
sensors:
cooking:
friendly_name: "Cooking"
value_template: "{{states.sensor.temp_inside_upstairs.state < states.sensor.kitchen_temp.state}}"
anyone able to help me with a switch template? just not sure how I would create one for an aicon unit, require it to use with the generic_thermostat integration. managed to write the sensor template fine, but stuck on switch...
Hey ALl, iam new here and from germany, i have some issues with modbus sma inverter integration can anyone help?
configuration yaml.
sensor: !include sensor.yaml
#sma#
modbus:
type: tcp
host: xxx.xx.x.xxx
port: 502
delay: 3
yes thank you π i used wrong channel my bad first time used Discord with over30 its New Land for me π
cast each state as a float using the float filter. Hint: | float. Then subtract 3 from the kitchen and compare.
Post what you have tried first
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
that should work as is, but it won't be a toggle. Just an on and off lightning bolt
Is that what you want?
ah yes, reading the generic_thermostat docs and it says it must be a toggle device
so what do you want to use to determine that the switch is on?
i don't think it requires it, because the sensor in the thermostat will let the thermostat know whether to toggle the switch, no?
the only way for it to be a toggle is for the switch to know it's state
so your 2 statements conflict. It's either "generic_thermostat docs and it says it must be a toggle device" or "i don't think it requires it". Not both
the first then, says must be a toggle
So back to my original question, what do you want to use to show that the switch is on?
It's ok to say "I don't know"
Hmmm... Say the AC unit is running, then the switch should show as on....
give me 2 i will try write it out
i think i am following now
ok, so if that's the case, what's the AC unit's possible states?
off or cool
So basically, template switches use the state of itself to know which service to call... turn_on or turn_off
ah, because its a toggle, and has to know what to toggle to?
yes
starting to get it
that's done through the value_template field
so your states are 'off' or 'cool'
first, go to the
-> states page
verify that those are infact the spellings of your states. What you see in the UI is translated.
switches:
bedroom_aircon:
value_template: "{{ is_state_attr('climate.master_bedroom_aircon', 'hvac_modes', 'cool') }}"
turn_on:
service: switch.toggle
target:
entity_id: script.bedroom_ac_night
turn_off:
service: climate.turn_off
target:
entity_id: climate.master_bedroom_aircon```
i think this may just do it
wait
turn_off to be replaced
with toggle
I don't use climate devices, it might be a different service
whatever you use to turn it off through services is what you want to use
and your turn on looks incorrectd
your turn on should just call the script
yeah climate.turn_off is the one out of services
turn_on:
service: script.bedroom_ac_night
ahhh
switches:
bedroom_aircon:
value_template: "{{ is_state_attr('climate.master_bedroom_aircon', 'hvac_modes', 'cool') }}"
turn_on:
service: script.bedroom_ac_night
turn_off:
service: climate.toggle
target:
entity_id: climate.master_bedroom_aircon```
personally, I wouldn't use climate.toggle
you want the turn off to turn off, not potentially turn on
oh yeah, its turn off
sorry
from services. there was no toggle.
cheering, hopefully this works
It should work for you
if you go to the services tab and execute template.reload you shouldn't need to restart
perfect, cheers
Can confirm everythingβs working as it should now π»
Thanks for helping me wrap my head around what is so foreign to me
Hi!
I have a value i get from SNMP. The value i get is "MemFree: 302579712"
I want to strip "MemFree: " and then divide it by a number.
This works for stripping the text in the devtools template. But how should i write it as a value_template?
{{ mydata | regex_replace(",\d+|[ MemFree:]", "") }}```
Isn't ```value_template: '{{ regex_replace(",\d+|[ MemFree:]", "") }}'``` enough, i get
unknown as value with that?
hi,need some help...
trying to make a sensor that triggers (xx) minutes before wake up time to start the bathroom heating.
using an input_datetime storing the wake up time and a input_number holding the minutes before wake up.
i am able to create a new time from the now() time, but that's not what i need...
{{ (now().strftime("%s") | int - ( states('input_number.badkamer_tijd_voor') | int * 60)) | timestamp_custom("%H:%M", false) }}
i need a new time from input_datetime - input_number
{{ states('input_datetime.klok_1') | int - states('input_number.badkamer_tijd_voor') | int }}
thanks.
I managed to get it to work with a template sensor.
value_template: '{{ ((states.sensor.snmpunraidmemfree.state)|regex_replace(",\d+|[MemAvailable:]","") | float / 1048576) | round(0) }}'
But i want it in the sensor that gets the data instead.
So states.sensor.snmpunraidmemfree.state should be like... "current value" or something. What am i missing?
Solved π
value_template: '{{ ((value.split(" ")[1]) | float / 1048576) | round(0) }}'
I have a question on the population of values to templates, I have a sensor that spikes sometimes to -40, i do not want these spikes in the database or in the graph, I have now displayed both values but the output of the template is populated once every few minutes(not a fixed period) the input is populated every few seconds, anyone have an idea what might happen here ?
{% if states('sensor.wp_buitentemp') | float > -30 %}
{{ ((states('sensor.new_wp_buitentemp')|float (states('sensor.wp_buitentemp')|float))) }}
{% endif %}
Is it possible to perform an action whenever an entity is clicked using automations? Ive had my eye on trigger event_type: click, but no luck getting it to work - anyone know what its for
This straddles #frontend-archived and #automations-archived, but is definitely not #templates-archived
When you say βentity is clickedβ, I donβt know whether youβre talking about something in a Lovelace card (in which case you should look at the card docs and tap_action) or some physical device
How do I add all of these together? I've tried a couple of combinations and haven't had any success yet.
{{ states.sensor.coinbase_btc_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_comp_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_cgld_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_grt_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_nu_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_ltc_wallet.attributes["Balance in native currency"] }}
These return values such as:
1234.56 USD
you can convert each to a float with this: "1234.56 USD"[0:-4]|float
basically, chop off the last 4 characters and convert to float. then just add
{{ states.sensor.coinbase_btc_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_ltc_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_comp_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_cgld_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_grt_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_nu_wallet.attributes["Balance in native currency"] [0:-4] | float }}
Awesome, thank you @inner mesa !
Iβm sure thereβs a more clever way to approach that by iterating through a filtered list of states (they all contain βcoinbaseβ and require the same massaging), but if ha e to play with it in the dev tools
if i make change to my config.yaml i can't reload it without restarting HA right? if i want to do that i have to make a separate yaml and !include it
then i can apply those changes without reloading the whole thing
but not my main config.yaml itself?
It has nothing to do with separate files - everything starts with a reference in configuration.yaml. Look at
-> Server Controls to see what can be dynamically reloaded
It could be sitting right in configuration.yaml or in some included file
Folks I think I'm being dumb again. I have an ESPHome sonoff ifan03 which has state of on/off and then speed of low/medium/high. I created a binary sensor which correctly shows just off/low/medium/high as well as the corresponding icon fan-off/fan-speed-1/fan-speed-2/fan-speed-3 but I can't get it to show the "on" state colour (grey = off, yellow = on) - it just stays at grey even when the fan is on. Can anyone point me in the right direction?
A binary_sensor can only be on or off, so Iβm not sure what you created
Good point. I started off with a sensor to show the state, then when I hit the problem of it not showing a button or entity as "on", I moved to binary_sensor with a value_template: of {{ state('fan.ifan03_fan', 'on') }}
Functionality is exactly what I want, my GUI updates as does the fan setting, just the icon doesn't change to it's yellow "on" state
That may just be for switches/lights
I use the custom button card to have more control over icon colors
Hmmm just feels incomplete without it. Think I can hack the style somehow based on the state?
I did look at that but it seemed a learning curve
You can use card-mod
Not really. It can be pretty simple
Itβs trivial to set the color based on state
I'll have another read, tbh I was reading it while trying to work so it wasn't getting my full attention
That card does nearly everything, so it can be overwhelming. But itβs not that bad if you just focus on what you want to do
Yeah the doc page did look a little large lol
This is a #frontend-archived question, btw
Oh sorry. Every time I get the wrong room
Ah okay, that looks straightforward enough thx
Just FYI {{ state('fan.ifan03_fan', 'on') }} is not a valid template. Should be {{ is_state('fan.ifan03_fan', 'on') }}. Seems like you're having other issues but noticed that so figured I'd see if I could cross one thing off your list.
that, too π
Oh bother π
That fixed it ty - so a binary_sensor (correctly configured!) does indeed show the yellow "on" state as a regular entity. Perfect
sorry about that, was scanning on my phone and missed that. I do heartily endorse the custom button card, though. Tons more control
Looking exactly as I'd imagined it. Yeah I'll certainly have a good read of the custom button card docs, does look like I can really customise stuff
Hi Guys, Is what I am looking for a template? - I want a glance card where I put some motion sensors up that show the ''last seen'' status so basically the last time there was a ''detected'' presence so just the time of last one
a template sensor would be the straightforward way to do it in a standard glance card
I haven't got this coming up in my sensors, can anyone take a look and tell me if I have written this wrong?
value_template: >-
{{ is_state('device_tracker.damien_owntracks_2', 'home')
or is_state('device_tracker.damien_ios', 'home')
or is_state('device_tracker.damien_phone', 'home')
or is_state('device_tracker.olia_owntracks', 'home')
or is_state('device_tracker.olia_ios', 'home')
or is_state('device_tracker.olias_iphone_2', 'home')
or is_state('sensor.family_status', 'Home') }}```
config validation says its ok
what's wrong?
is that a binary_sensor?
did you reload template entities or restart HA?
Did you try putting that in
-> Templates?
just a sensor template
yeah, it says that it would work, says its listening for the entities
and came back as - platform: template sensors: family_home: value_template: >- False
because no one is home...
oh so strange, now it is appearing in
> states
disregard!
also if I used the template
friendly_name: "Door Open/Closed"
value_template: >-
{% if is_state('binary_sensor.front_door_sensor_contact', 'open') %}
Door Open
{% else %}
Door Closed
{% endif %}
icon_template: >-
{% if is_state('binary_sensor.front_door_sensor_contact', 'open') %}
mdi:door-open
{% else %}
mdi:door-closed
{% endif %}```
would it change the icon on my entity panel from open to closed depending on the door's state?
beauty
Hmm with the following, would the state of the sensor be home if any of those states are true? and what would the state be if false?
sensors:
family_home:
value_template: >-
{{ is_state('device_tracker.damien_owntracks_2', 'home')
or is_state('device_tracker.damien_ios', 'home')
or is_state('device_tracker.damien_phone', 'home')
or is_state('device_tracker.olia_owntracks', 'home')
or is_state('device_tracker.olia_ios', 'home')
or is_state('device_tracker.olias_iphone_2', 'home')
or is_state('sensor.family_status', 'home') }}```
no, it would return a boolean
you can add if/else logic to have it return something else
you can test this
ok, i get the if/else logic, but if it returns a boolean, where does that go?
it will be the state of the sensor
you can try this
just change the state of one of the entities to whatever you want
now I am really lost... this is what I get for trying to copy someone elses config for presence detection....
lost how?
Ok so my logic is this....
Automation to detect group.family or person.x/y at home. This automation turns on an input boolean. input_boolean.family_is_home
Another automation that detects input_boolean.family_is_home turning on, runs script.welcome_home only if the boolean is off and no one is home already (thinking I need to put a guest mode in around here somewhere)
maybe I just need to drop the sensor.family_home above
am I over complicating it?
it seems like you only need the "family is home" sensor
a template binary sensor would be enough
or just put them all in a group
{{ states.device_tracker|selectattr('state', 'eq', 'home')|list|length > 0 or is_state('sensor.family_status', 'home') }}
any device tracker entity has a state of home or that sensor
even that seems more complicated than necessary for those requirements
the requirement I see is to run some "welcome home" automation when a sensor goes from "not home" to "home", indicating that somebody arrived home
so a group of device trackers would do that
i have a binary sensor group.family created
a binary_sensor and group are two different things
right
and a bayesian binary sensor for each person with their device trackers
I have double tapped it haven't I haha
Am thinking I could do away with the bayesian sensor altogether
i think the person entity does that for you
yep, I have added the same device trackers to the person identities (sorry been stuffing around on the weekend with all this)
@formal ember Discord isn't like IRC, you don't have to tag people on every response. Keep in mind that every time you tag somebody, they get a notification ping. That can very quickly become annoying and people may block you.
When using Discord's new Reply feature it defaults to pinging the person you reply to, click @ ON to @ OFF to stop this - on the right side of the compose bar.
for the quote reply π
π
no need for ping on active conversations
sorry mate
lol
Ok so back to my setup:
Automation to detect group.family or person.x/y at home. This automation toggles, sensor.family_status to on or home.
Second automation to detect sensor.family_status as being on or home. This then runs script.welcome_home
Leaving home would be an automation that detects group.family or person.x/y away. This automation toggles sensor.family_status to off or away.
Another automation to detect sensor.family_status is off or away. This runs script.leaving_home
If I keep it simple, am I going to miss out on anything?
again, seems too complicated
just use the sensor and have a single automation that runs an "away" or "home" automation
you don't need an automation for a toggle when you can just create the sensor using the same template
1 entity instead of 2
ok then...
sensors:
family_home:
value_template: >-
{{ if is_state('device_tracker.damien_owntracks_2', 'home')
or is_state('device_tracker.damien_ios', 'home')
or is_state('device_tracker.damien_phone', 'home')
or is_state('device_tracker.olia_owntracks', 'home')
or is_state('device_tracker.olia_ios', 'home')
or is_state('device_tracker.olias_iphone_2', 'home')
or is_state('sensor.family_status', 'home') }
home
{% else %}
away
{% endif %}```
comes back with TemplateSyntaxError: expected token 'end of print statement', got 'is_state'
cannot find something so complicated in the documentation
right, that's wrong π
{% if is_state('device_tracker.damien_owntracks_2', 'home')
or is_state('device_tracker.damien_ios', 'home')
or is_state('device_tracker.damien_phone', 'home')
or is_state('device_tracker.olia_owntracks', 'home')
or is_state('device_tracker.olia_ios', 'home')
or is_state('device_tracker.olias_iphone_2', 'home')
or is_state('sensor.family_status', 'home') %}
home
{% else %}
away
{% endif %}
it's still too complicated
π
you keep repeating that monster
just group all device_tracker entities and use that one group for everything
or...just continue doing what you're doing, I guess
right, like a group.family_device_tracker
sure
that simplifies things
and...that's it
and you can test it by manually modifying states of individual trackers to make sure you get the right result
I think I have just realised I could use my group ```Family:
- person.damien
- person.olia``` instead of an even larger one as those trackers are already assigned to the person.
thats the new automation
for coming home
I am thinking its even easier if I just go 'if family comes home, run script'.... but now I am in #automations-archived land
Yes, thatβs the point of the group π
Thanks for putting up with my time here
Np, itβs a process. But a rewarding one, IMO
Could anyone help me with this problem? Im trying to multiply my sensor value by the number 1127, but my sensor read out gives me 0
-
platform: scrape
name: vechainvalue
resource: "https://www.coingecko.com/en/coins/vechain/eur"
select: ".no-wrap"
scan_interval: 1- platform: template
sensors:
vechain_waarde:
friendly_name: 'VeChain Waarde'
value_template: "{{ (states('sensor.vechainvalue') | float * 1127) | round(0) }}"
unit_of_measurement: 'β¬'
- platform: template
This is the code I wrote in the configuration file, does anyone see the problem?
Do you get the same if you put the template in
-> Templates?
The sensor may report βunavailableβ or something that cannot be converted to a float
Perhaps during startup
My template read out also says 0, when I change round(0) to round(1) it gives me 0.0
So the code seems fine, but I think it has something to do with the scrape sensor which the value from the scrape cant be converted nor multiplied by the number 1127
- platform: template
sensors:
vechain_waarde:
friendly_name: 'VeChain Waarde'
value_template: "{{ ((states('sensor.vechainvalue') | string) * 2) | round(1) }}"
When i change float to string it gives me:- platform: template
sensors:
vechain_waarde:
friendly_name: 'VeChain Waarde'
value_template: "β¬0.06409742β¬0.06409742"
Now I do be getting some values, but it's just the same value put next to each other twice
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.
Well, thereβs your problem. The first character is messing up the conversion.
- platform: template
sensors:
vechain_waarde:
friendly_name: 'VeChain Waarde'
value_template: "{{ ((states('sensor.vechainvalue')[1:] | float) * 2) | round(1) }}"
in the example above, is it possible to store the value to a different attribute.
I believe the default value is the state attribute
Thanks @inner mesa!
State isnβt an attribute
got it. Let me rephrase
n the example above, is it possible to store the state value to a different attribute.
how would I do that RobC. Is it possible to do that with the sql sensor?
Recommend consulting the docs on that
thanks. I don't that option is available for sql sensors. thank you.
You can just create a template sensor based on the output of your sql sensor
the problem is the sql response is larger than 255 characters. because the state column is limited to 255 chars
I was hoping to store the result in the attributes collumn
You could with your own custom component
Do I need to make a new front end component or a new entity?
An integration
thanks. Sorry to bother you again... Do you have a link to an example
Am trying to convert to a float the following output value:
- platform: scrape
name: Exodus ETH Wallet ETH BAL
resource: "https://etherscan.io/address/0x82fbEd465c16679C6dC8E4d8c2dfEcd097175fb8"
select: ".col-md-8"
scan_interval: 1
The value I get is 0.0159... Ether
How do I get rid of 'Ether'?
how do i make the last boot sensor human readable? (for some reason when i preview a multiple entities card, it will show it as 16 hours but when i try it in the singular entity card it shows the garbled timestamp.)
lots of good stuff here: https://www.home-assistant.io/docs/configuration/templating/#time
entity card doesn't support device class timestamp for some reason. Only way you get get that is using relative_time or put it in the entities card.
what would i put specifically?
mb the entities card
just put it in the entities card like any other entity
entities card != entity card
entites card it works and will display a relative time. entity card will not work and it'll display the timestamp
Hey Guys - I'm trying to fix my fans that broke with the latest update (fixed speeds -> percentage speeds) ... is this the best channel to get help?
I have tried a few options wrt changing the speeds to percentage as opposed to low, med, high etc ... but my fans arent even loading to begin with now.
They were working perfectly until now ... not even the default on the latest setup doc is working - maybe I'm over thinking it π
https://paste.ubuntu.com/p/fjCXmp8CBy/ This is my original config - maybe better to start there and see what needs to change?
yeah i did that already, i just liked the big text. what can i do for the relative_time option?
You can build a template sensor using the link I posted earlier to convert to a format you like better
Can anyone tell me if I have an array, can I get HA to return the # of items in the array
example, have an array of values but need to know how many values there are is there a count function?
attribute of an entity (sonos list of favorites)
And where do you want to use the count?
Itβs as simple as doing β|countβ to count the items
need to assign it to a variable
Jinja Template Designer Documentation
For more examples and samples, visit see this page
Lots of jinja docs out there
probably |length
can you give me an example of the line that would have that in it?
(I have the rest working fine)
state_attr(entity_id, "source_list")
where would |length go
well since state_attr() is a complete expression, outside
so right after it
Or that π
Hi Template Guru's
{% if is_state('binary_sensor.office_door_sensor_contact', 'on') %}
mdi:door-open
{% else %}
mdi:door-closed
{% endif %}```
If I wanted to add a colour change to this one, would it be as simple as adding the line under the else line if I wanted door-closed to be Red?
do I have to create a different template to do colour?
or would I be better off using something like card-mod?
The template isnβt the problem or solution
You could, or use something like custom button card
Down the rabbit hole I go again
is it possible to make a template for a condition that looks for the following: "has value been above 100 in the last hour" then template is true or false for condition?
want to see if the sump pump has ran in the last hour measuring watts basically
i see that option in the UI for triggers but not conditions but i guess ill use it as my trigger
sounds like something better served as a trigger, yes
I have a value example: {{states.climate.downstairs_thermostat.attributes.current_temperature}}
can I add that directly into a lovelace card at the top as a badge?
or do I need to define a sensor with it and put the sensor as a badge?
I found state-label in the badge documentation but wasn't sure how to use it directly as a badge
No, you canβt template in Lovelace
k thanks
separate question, I know i can break out smaller yaml's using the !include
and it seems from the documentation that i can break out multiple if i want, but they need different names
is the non-indented label irrelevant?
sensor: could contain some sensors in the base configuration.yaml
and then sensors2: !include sensors2.yaml could have other sensors whiel sensors3: !include sensors3.yaml could have yet others?
The non-indented label is very relevant
but you can split it up like this:
sensor: ...
sensor foo: ...
sensor bar: ...
you need the space
oh ok
sensor badges: !include sensors-badges.yaml etc
then i can just have a separate yaml for badge templating and such
yep
cool π
just need a space
thank you
np
I new it had to matter and not at the same time
keep in mind, that your errors will not point to the correct location
?
oh
on the checks
yes it is going to imagine its just part of the base file
i read that
like if you have an error in a sensor, it'll point to some random ass location
the error contents will be correct, just not the line pointer
I highly doubt I'm doing this even remotely right, so maybe someone can help me. I have several Inovelli fan/light switches, and the fan is showing up as a "light" that the "brightness" can be adjusted. I'm trying to create a template to turn them into fans and will hide the light entity. This is what I've got in the configuration right now, and the fan comes on, but I'm not able to get the slider adjustment to work right. Since my fans don't really do any speed different than low, medium, and high, I was going to set the slider to 33%, 66% and 100%. Anyone help me out on this?
@hard pagoda posted a code wall, it is moved here --> https://paste.ubuntu.com/p/ZwmqSPQd6s/
Ok, so I'm not figuring out how to do the code wall. lol sorry.
I'm trying to find it in the docs, but is there any way when creating a binary sensor template to do something with a time period component like a condition where you stipulate: for: seconds: 10
so I have this template:
sensor:
- platform: template
sensors:
coinbase_total_balance:
friendly_name: Coinbase Total Balance
unit_of_measurement: USD
value_template: >
{{ (float(state_attr('sensor.coinbase_mana_wallet', 'Balance in native currency').split(' ')[0])
+ float(state_attr('sensor.coinbase_my_wallet', 'Balance in native currency').split(' ')[0])
+ float(state_attr('sensor.coinbase_eth_wallet', 'Balance in native currency').split(' ')[0]))
| round(2) }}
icon_template: mdi:currency-usd
is there a good way I can use this more generically, like a wildcard or maybe selectattr? I don't really get how selectattr works... but basically I'd like to account for the situation where I may have many more wallets, and not have to add that any more lines
oh I think I found it... it's just named differently with delay_on
or for example so I could send/post this to someone who has different wallets than me, and have it still work
I'm tempted to develop a PR to the coinbase integration to add this as a sensor entity, but would like to get something more general working in the meantime
Is there a way to make a safe_alarm_panel use a button for disarming instead of requiring a code input?
Oooh, that worked... just added disarm as a state and set the code in the template .yaml.. is there a way to get rid of the keypad now?
(I guess maybe there's an easier template to use if I don't care about the keypad?)
right now I'm calling a service for each template state... maybe I can conditionally check the {{code}} value and if it's present call one service and if it isn't call another?
Ok, so I've tried this and it's still not adjusting the speed of the fan. Can anyone help me out here? https://paste.ubuntu.com/p/rhkxC9Dqbp/
Using that configuration, I'm able to get it to turn on, but not adjust the speed of the fan.
Hello everyone, wondering if anyone knows a quick fix to pull data from or push data from a temperature sensor more often. The sensor is based off an attribute on my HVAC system, it is a template. Could I run an automation to actively ask the device what the temperature is, instead of waiting for it to broadcast the temp?
If I'm understanding corrctly, you have to trigger a refresh of you HVAC system. It depends on the system, it is more an #integrations-archived topic
Ah yes, I threw it up there too but no response. Iβll try again π
Ok, so I've tried this and it's still not adjusting the speed of the fan. Can anyone help me out here? https://paste.ubuntu.com/p/rhkxC9Dqbp/
Using that configuration, I'm able to get it to turn on, but not adjust the speed of the fan.
Take a look at the template fan docs, set speed no longer works off speeds. This was a change in the latest version of HA
I'm still learning the language for Home Assistant and unfortunately haven't been able to learn it fully yet. Examples is how variables are handled in Home Assistant.
The docs have an example
So for these lines value_template: "{{ states('input_boolean.state') }}"
percentage_template: "{{ states('input_number.percentage') }}"
The input_xxxxxxx would be the entity of the light. that is suppose to be a fan?
The value_templates are what render the current state of your fan for that specific field
so it would be value_template: "{{ states('light.living_room_fan_hallway') }}" ?
note that jinja2 is not a HA specific concept
Is it not possible to use a variable as part of another variable? i.e.:
{% set last_triggered = states.{{ trigger.event.data.entity_id }}.attributes.last_triggered %}
{{ }} does not extract the information
treat it like any other object in your code
{% set last_triggered = states[trigger.event.entity_id].attributes.last_triggered %}
Sorry, here's a better example of what I'm trying:
{% set last_triggered = states.automation.lights_on_[light_source].attributes.last_triggered %}```
{% %} logic statements
{{ }} print statements
states.automation.get('lights_on_{}'.format(light_source)).attributes.last_triggered
That only seems to get me TypeError: 'NoneType' object is not callable
what is the entity id of the automation you're trying to pull?
automation.lights_on_bedroom
nothing in those 2 lines would produce a Nonetype is not callable
the error is later on in your template
is automation nolonger a dict?
no its an object
apparently missing the .get
{{ states.automation.get('lights_on_{}'.format(light_source)).attributes.last_triggered }}```
This is the entire template right now.
huh, they must have changed it from a collection then
states.automation|selectattr('entity_id', 'eq', 'automation.lights_on_{}.format(light_source)')[0].attributes.last_triggered maybe
oh no
well either way, this would work
{{ (expand('automation.lights_on_' ~ light_source) | first).attributes.last_triggered }}
YES!
@dreamy sinew that would work if you used |first instead of the getitem
[0] or whatever it's called
I think
i've had weirdness with that but i think you solved it by wrapping in paren
really should just have a template editor up at our disposal at all times
it would be nice if there was one on homeassistant.io somewhere
meh, i'm cool with using the one on my system
with a bunch of canned crap
i can usually get close to whatever the question is
I'm at work... no access π
I put a dev version of HA in docker on it in wsl2
maybe a FR to get it exposed out on the demo system
but it's not running
Thank you very much for the help, guys
Another question - Would this work?
- event: lights_off_override_enable
event_data_template:
light_source: "{{ (trigger.entity_id.split("switch.light_")[1]) }}"```
(Doesn't seem to)
Ah of course.. Rookie mistake!
@dense monolith posted a code wall, it is moved here --> https://paste.ubuntu.com/p/wvcsZJ34JN/
What variables are supposed to be accessible in the template?
value_template: '{{"WARNING" in state_attr("sensor.pixel_4_last_notification", "android.text"}}'
it doesn't know what android.text is, you could do a trigger attribute, value_template: '{{ "WARNING" in trigger.to_state.attributes.android.text'
if you wanted to expand your trigger to multiple entities
I'm trying to do an if statement in my action, so instead of this:
- event: lights_on_override_enable ```
I do this:
``` action:
- event: >
{% if (is_state("trigger.event.data.new_state", 'on')) -%}
event.lights_off_override_enable
{%- else -%}
event.lights_on_override_enable
{%- endif %}```
Is this possible? What am I missing?
no, that's not possible like that
you can use templates inside of data:, but I don't know if that'll work for firing events
I don't see anything here that says that you can template the event name: https://www.home-assistant.io/docs/scripts/#fire-an-event
Okay, thanks!
I would just use a generic event and add custom data (which can be templated)
I have an MQTT sensor to which an application is sending 8-bit RGB values as a simple string of nine digits. How would I go about separating this sensor into sub-entities for each color value such as sensorname.red?
name: wallpaper-color
state_topic: "wallpaper-color"```
I intend to use this sensor to drive the color of various lights in an automation.
Thus far, I have tried this approach but the resulting channel sensors don't contain any values. Perhaps I have made a mess of something.
- platform: template
sensors:
wallpaper_red:
friendly_name: Wallpaper Red Channel
value_template: "{{ states('sensor.wallpaper-color').split()[1] }}"
wallpaper_green:
friendly_name: Wallpaper Green Channel
value_template: "{{ states('sensor.wallpaper-color').split()[2] }}"
wallpaper_blue:
friendly_name: Wallpaper Blue Channel
value_template: "{{ states('sensor.wallpaper-color').split()[3] }}"
What does return states('sensor.wallpaper-color')?
FYI the index should be 0 -> 2 and not 1 -> 3
and if your sensor.wallpaper-color contains comma separated values you should use {{states('sensor.wallpaper-color').split(',')}}
Will a template binary_sensor be updated, when a entity in the attributes_templates changed ?
define updated
I would like to write this {"humidity": 39} to a .json file. How should the template look like?
i have this - service: notify.tekstbestand data: message: > "{{ {'humidity': states('sensor.mancave_multi_sensor_vochtigheid')} }}"
but this isnt getting the right format in the file
I did eventually figure it out but thank you for the advice. Integrating it as an automation with a data_template as seen below worked perfectly.
alias: New Automation
description: ''
trigger:
- entity_id: sensor.wallpaper_color
platform: state
action:
- service: light.turn_on
data_template:
rgb_color:
- "{{ states('sensor.wallpaper_color').split(';')[0] }}"
- "{{ states('sensor.wallpaper_color').split(';')[1] }}"
- "{{ states('sensor.wallpaper_color').split(';')[2] }}"
entity_id: light.light_1
ugh, after 3 days I get fans working, and now they don't work....
That gives me an error.
Mapping values are not allowed here
notice the stealth edit
There is no longer an error but it doesn't work.
alias: Light Color Follows Wallpaper
description: ''
trigger:
- entity_id: sensor.wallpaper_color
platform: state
action:
- service: light.turn_on
data_template:
rgb_color: "{{ ('sensor.wallpaper_color').split(';') }}"
entity_id: light.light_1
Doesn't it need to be split three times for three values?
that's what the .split() does. it becomes a list of 3 values
The raw sensor data is 000;000;000;.
ah so you get 4
states is missing
rgb_color: "{{ states('sensor.wallpaper_color').split(';') }}"
Ah, so it is.
{{ "000;002;003;".split(';')[:-1]}}
I'll remove the final ; from the sensor side.
that will also work
Still doesn't work, I'm afraid.
alias: Light Color Follows Wallpaper
description: ''
trigger:
- entity_id: sensor.wallpaper_color
platform: state
action:
- service: light.turn_on
data_template:
rgb_color: "{{ states('sensor.wallpaper_color').split(';') }}"
entity_id: light.light_1
ok, so I add a percentage_template to my fans template and vscode tells me percentage_template is not allowed
Raw sensor data is now 000;000;000.
Pasting "{{ states('sensor.wallpaper_color').split(';') }}" into Developer Tools produces "['000', '090', '185']".
Pasting my original "{{ states('sensor.wallpaper_color').split(';')[0] }}" produces a single value for red in quotes without brackets.
doesn't rgb_color expect a list of int instead of a list of string ? You can try {{ states('sensor.wallpaper_color').split(';') | map("int") | list}}
to cast each string in int
This gives me an 'expected block end but found scalar" error.
alias: Light Color Follows Wallpaper
description: ''
trigger:
- entity_id: sensor.wallpaper_color
platform: state
action:
- service: light.turn_on
data_template:
rgb_color: "{{ states('sensor.wallpaper_color').split(';') | map("int") | list}}"
entity_id: light.light_1
Beginning to think that my overkill solution might not have been such overkill. π
you mixed your quotes
"{{ states('sensor.wallpaper_color').split(';') | map('int') | list}}"
Trying this.
It produces "[255, 70, 17]" and no errors but still doesn't work.
In the past when I've had a "switch" (like a tasmota) that is really a lamp, I will make an entry under light: in my config.yaml so that it creates a light.entityname. Right now I added a door sensor that is a binary_sensor. I went into customize.yaml and set it's device_class to be door, and this worked great in lovelace for identity purposes but when I went to write automations, the states are being triggered in their original form (not the converted display of Open/Closed) is there a proper way to modify this so that I can use "Open/Closed" in my automations, maybe modify the template of the entity also? I was alternatively going to define a door (similar to how I define lights mentioned above) but that doesn't seem to work the same way. thanks for any guidance
Hey guys need a bit of help. I want to create a date template that outputs " Thursday, March 18 " I have started a bit with ```{% set months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] %}
{% set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %}
{{ days[now().weekday()] + ' ' + months[now().month-1] + ' ' + now().day }}
but when I place the now().day into the piece I am getting an error. If I remoe it and just place it as {% set months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] %} {% set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %} {{ days[now().weekday()]+ ', ' + months[now().month-1] + ' ' + 'day' }} i get everything but the day of the month.
I have racked my brain to sleep trying to solve this . Anyone willing to point me in the right direction? Please.
hmm best way to decode an image sent over mqtt? data:image/jpeg;base64,/9j/4MOREDATAhere ? Ideally I would like to save it as a file or use it as a camera
use strftime.org and the modifiers with timestamp_custom
{{ as_timestamp(now()) | timestamp_custom('%A, %B %d') }}
You'd have to create a template sensor if you want to use open/close. Everything in home assistant uses the under the hood names for states, not the translated names.
Thanks @mighty ledge .π
Hi all! I'm struggling with a script, trying to build what to send to my Sonos, or my google home mini's. Maybe someone can point me into the right direction.
Kitchen is a Sonos -> needs to recieve the property "source:"
Livingroom, Bedroom and Bathroom need to recieve the property "media_content_id:"
@toxic radish posted a code wall, it is moved here --> https://paste.ubuntu.com/p/ttQQF4QYtt/
When i check this code in Developer Tools > Template it works just fine
but as a "script:" it doesn't work, logging says: Error executing script. Error for call_service at pos 3: Error rendering data template: UndefinedError: 'state' is undefined
Here is the full script: https://paste.ubuntu.com/p/y4BdXNbbDG/
Your indentations in that code dump are wrong, itβs safe to say that they are probably wrong in the script too
And it looks like your template spans across fields, which does not work
Use choose instead
aah i've read about choose, thank you i'll have a look
while parsing a block mapping in "/config/packages/radio.yaml", line 83, column 13 expected <block end>, but found '<scalar>' in "/config/packages/radio.yaml", line 83, column 40
this is line 83: conditions: "{% if states("input_select.radio_speaker") != "Keuken" %}"
I have problems with some Yaml in my configuration, where to ask help for it?
I can't find a good example on how to use "choose:" inside of a data_template, can you point me in the right direction?
YOu don't put choose inside a data template. Choose is a script action. Look at the script documentation
Sorry, that's not a link to it
That one
TemplateError('UndefinedError: 'mappingproxy object' has no attribute 'today_energy_kwh'') while processing template 'Template("{{ states.switch.hs110.attributes["today_energy_kwh"] | float }}")' for attribute '_state' in entity 'sensor.tumble_dryer_switch_today_kwh'
I'm having this error appear and I'm sure it's been working fine.
This is the template in question
friendly_name_template: "{{ states.switch.tumble_dryer.name}} Today's Consumption"
value_template: '{{ states.switch.hs110.attributes["today_energy_kwh"] | float }}'
unit_of_measurement: "kWh"```
Could I get some help on this please? This is for an HS110 TP Link plug
hi. how can i add to logging the person who is home when doorbell rings. i added time for now
you use that second one as template for a sensor and write out the value of the sensor to the message
oh... that's why some guys are purple ...they are smart π
thank you @coarse tiger
Anyone can help me out with my script?
Logging: Radio afspelen: Error executing script. Invalid data for call_service at pos 3: extra keys not allowed @ data['choose']
@toxic radish u saw beardedtinkerer's youtube video ?
you should remove the action: tag. choose: should be at the same level than service:
how can i insert a ; when receiving multiple persons in https://pastebin.ubuntu.com/p/kk2Vtvs8xc/
now i receive xxxyyyy
btw you could significantly simplify your code @toxic radish. I suggest you create a dict variable radios containing the key/value, and then in the source or media_content_id, juste call {{radios[states("input_select.radio_station")] }}
