#templates-archived
1 messages ยท Page 106 of 1
something like this should work:
turn_on:
- service: wake_on_lan.send_magic_packet
data:
mac: "ff:ff:ff:ff:ff:ff"
broadcast_address: 192.168.15.3
- service: media_player.select_source
data:
entity_id: media_player.living_room_tv
source: 'Netflix'
whether you need a template switch or not is another question
right right, im getting a little ahead of myself on the template switch Q
ahh entity_id only needs to be there once. nice
not sure what you mean. you need to provide whatever each service call requires
they're separate calls
a template switch looks like a good fit for what you're doing
okay so if i add what you got up there to my original am i right that it would like this https://paste.ubuntu.com/p/ZsgWRC6pff/
ah my syntax was all f'd up, but i followed ur example and it passed the config check!
my spacing is not right either (remove 2 spaces for everything under turn_on:, but that was a pain in the neck in teh editor
but it should work
yea i ended up doing just that!
Is it possible to have delays in between the separate calls?
thanks again Rob!
@brisk temple Thanks.... it works now
Really like your help guys.. can anybody check the following code? I guess the sun event line is incorrect
what's wrong with it?
It does not represent the correct state
I'm wondering if this line of code is correct:
{% set ts_from = as_timestamp( states.sun.sun.attributes.next_dusk ) %}
it looks like next_dusk is in UTC
I was getting an error and after doing some searching i found a thread that recommended wrapping it in if statement. Just started up and it doesnt look like it's helping. Still getting the 'split' error
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 401, in async_render_to_info
render_info._result = self.async_render(variables, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 334, in async_render
raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: UndefinedError: 'None' has no attribute 'split'
.share your template
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
{% set d, h, m = state_attr("sensor.quarantine_meter_dk", "value").split() %}
{% set d, h, m = d[:-1] | int, h[:-1] | int, m[:-1] | int %}
{% set hours_outside = ((14 - d) * 86400 - h * 3600 - m * 60) / 3600 %}
{{ (hours_outside / 7) | round(1) }}
{% endif %}
")
sensors:
quarantine_meter_hours_outside_per_day_dk:
friendly_name: Quarantine Hours Outside DK
value_template: >
{% if states.sensor.quarantine_meter_dk.state %}
{% set d, h, m = state_attr("sensor.quarantine_meter_dk", "value").split() %}
{% set d, h, m = d[:-1] | int, h[:-1] | int, m[:-1] | int %}
{% set hours_outside = ((14 - d) * 86400 - h * 3600 - m * 60) / 3600 %}
{{ (hours_outside / 7) | round(1) }}
{% endif %}
use states('sensor.quarantine_meter_dk') instead
instead of state_attr?
oh, interesting
that thing has a value as None that's why its getting past your if check
so it's proceeding on none
{% set attr = state_attr("sensor.quarantine_meter_dk", "value") %}
{% set d, h, m = attr.split() if attr else ("", "", "") %}
{% set d, h, m = d[:-1] | int, h[:-1] | int, m[:-1] | int %}
{% set hours_outside = ((14 - d) * 86400 - h * 3600 - m * 60) / 3600 %}
{{ (hours_outside / 7) | round(1) }}
should i the if to that or remove the endif?
remove the endif
@dreamy sinew thanks, that solved it!
Having an issue with a template sensor and wanted to ask here. Trying to pull data from other weather template sensors and do an if statement to determine boat weather. Ultimately trying to make an entity to use for badge on lovelace
icon_template: "mdi:sail-boat"
friendly_name: "Boat Weather Today"
value_template: >-
{% if states('sensor.forecast_wind_today')|float <= 10 and states('sensor.forecast_precip_today') <= 0.05 and states('sensor.forecast_condition_today') in ('clear-night', 'partlycloudy', 'cloudy', 'sunny') %}
Yes
{% else %}
No
{% endif %}```
your issue is?
Sorry, returns as "unavailable"
test each part in
-> Templates
this needs a "|float": states('sensor.forecast_precip_today')
but still, just test each part
I got the following working in template editor. I am trying to get it to work in the 'name:' field of the custom:button-card. What do I have to change to get it to work there?
{% if is_state('automation.basement_lights_dim', "on") -%} Disable {%- else -%} Enable {%- endif %}
friendly_name_template I guess? Not sure tho
Got another Question:
{% if states['light'] | selectattr('state','eq', 'on') | list | count > 1 %}
on
{% else %}
off
{% endif %}
works as intended in dev tools. It just doesn't change the actual value of the entity.
share the entire template definition?
Figured out mine:
- entity: automation.basement_lights_dim
name: '[[[ if (entity.state == "on") return "Disable<br/>Auto Dim"; else return "Enable<br/>Auto Dim" ]]]'
@regal salmon posted a code wall, it is moved here --> https://paste.ubuntu.com/p/FCh8VpgNmZ/
Uh, helpful bot :)
Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
@odd flare state_attr() is returning a string and you're trying to split it on startup. You have to check the attr against None and you can't use the is_state_attr method because it doesn't handle None well.
{% if state_attr('x', 'y) != None %}
... do crap here
{% endif %}
Well apparently my discord wasn't up to date and as soon as I hit enter all this crap filled in. Disregard my message
I hate that
@mighty ledge appreciate the explanation...I was 90% there but this sealed it
yeah through me in for a loop, last message I saw was this
So, what I'm attempting to do is this: https://pastebin.com/WihEBrvK
The value_template works fine in dev tools, but the actual entity does not update. It's purpose should be an "All lights" entity that is used for alexa ("Alexa turn on/off all lights").
It always works for turning lights on but it doesn't turn them off again.
oh
make an all light group
then use this template {{ expand('group.all_my_lights') | selectattr('state','eq','on') | list | count > 1 }}
value_template wants a true/false too, so you don't need an actual if statement
Sorry, it's kinda late. -
If I go through the hoops of creating a group with all my lights manually, I could just create a light.all_my_lights, couldn't I?
yep
if you want something dynamic you could make a sensor that reports the number of lights with an attribute template that has all the entity_id's in a list. Then use said list in your expand function.
This doesn't really sounds worth in timesavings to just create and manually update an light.all_lights entity, I guess?
sensor:
- platform: template
sensors:
light_manager:
value_template: >
{{ states.light | count }}
attribute_templates:
entity_ids: >
{{ states.light | map(attribute='entity_id') | list | join(',') }}
then for your light
light:
- platform: template
lights:
all_lights:
friendly_name: "All"
value_template: >-
{% set entity_ids = state_attr('light_manager', 'entity_ids').split(',') %}
{{ expand(entity_ids) | selectattr('state','eq','on') | list | count > 0 }}
turn_on:
service: light.turn_on
entity_id: all
turn_off:
service: light.turn_off
entity_id: all
the light manager will update once a minute. So you'll have to wait a minute sometimes after adding a light for the first time.
or just restart and it'll work instantly
Okay, 1st: Thanks so much for your effort. 2nd: I really gotta wrap my brain around that.
That wouldn't be no fun, would it? Also I could flex in front of my colleagues
Lol, have at it. Just ping me if you have q's
I will haha
It should be sensor.light_manager in {% set entity_ids = state_attr('light_manager', 'entity_ids').split(',') %}, shouldn't it?
yah yah, typo
Aye x)
So, the entity works as it should, but stupid alexa isn't turning anything off. But that's a problem for both another day and another channel. Thanks so much for your help! :)
Btw, alexa's just stupid. i renamed the "all" entity to "wurst" and alexa will turn "wurst" happily on and off. jesus.
can I use variable/template ( {{ value.split }} ) in 'entity_id' of script's sequence service?
can you use the new variable feature from 115 in template sensors? so i can use the same value in value_template, icon_template etc
I am trying to setup some iLO sensors. I have found an example. The template is value_template: "{{ ilo_data.temperature['01-Inlet Ambient']['currentreading'] }}" and it returns (15, 'Celsius') but i only want the 15 and none of the rest of it, how do i get the 15 out?
Have you tried {{{{ ilo_data.temperature['01-Inlet Ambient']['currentreading'][0] }}?
Hi, I'd like to set a condition in an automation as follows:
- condition: numeric_state
entity_id: climate.thermostat_room1
attribute: temperature
not: >
{% if is_state('input_boolean.vs_room1', 'off') %}
15
{% else %}
26
{% endif %}
I need to check in some cases that it is different than 15 and in other cases that it is different than 26. Since equal and not does not exist, can I change the below and above with a template?
you can do it in a template condition
smth like
- condition: template value_template: > {% if is_state('input_boolean.vs_room1', 'off') %} {{ state_attr('climate.thermostat_room1', 'temperature') != 15 }} {% else %} {{ state_attr('climate.thermostat_room1', 'temperature') != 26 }} {% endif %}
Is there a way to merge an entity's state and an entity's attributes into a single JSON map in a template? Specifically, I want to add the state as a new member of the attributes map and send it out as JSON via MQTT. I tried to do something like:
{% set wx_attrs = states['weather.home'].attributes %} {% set wx_attrs['condition'] = states('weather.home') %} {{ wx_attrs }}
But that doesn't work to assign a new map member. So I tried the direct route:
{% set wx_attrs = { "condition": states('weather.home'), states['weather.home'].attributes } %}
But it didn't like this, either..
Is there a way to do this in the templates, or am I SoL?
i don't think you can change the states in a template
Note that I am not trying to change the states, per se. I am just trying to create a single JSON map that merges a state and the attributes map, so I can send that out via MQTT., sort of like merging two different maps into one map. I.e., if I had {a:b} and {c:d}, I'd like to make {a:b, c:d}.
ok my bad
That's okay, @deft timber ... I know I can do it by explicitly rebuilding the full map, e.g.:
{% set wx_attrs = states['..'].attributes %} {% set result = { "condition": states(...), "temperature": wx_attrs['temperature'], "humidity": wx_attrs['humidity'], "forecast": wx_attrs['forecast'], ... } %}
But that seems so long-winded.
@plush leaf It seems like you can add an element with dict() ```
{% set x = {'a':1, 'b':2} %}
{% set y = dict(x, c=3) %}
{{ y }}
So I guess {% set wx_attrs = dict(wx_attrs, condition=states('weather.home')) %}
However, I don't know about JSON ...
Thanks @frank raven -- That works!!
{% set wx_attrs = states['weather.home'].attributes %} {% set result = dict(wx_attrs, condition = states('weather.home')) %} {{ result }}
This gives me the map I need. Then I can send it. Sweet! Thanks!
Do you see any error here, it's complaining about a missing endif
action:
repeat:
while:
condition: and
conditions:
- condition: template
value_template: '{{ repeat.index <= 25 }}'
- condition: template
value_template: >
{% if is_state('input_boolean.vs_room_1', 'off') %}
{{ state_attr('climate.thermostat_room_1', 'temperature') != 15 }}
{% else %}
{{ state_attr('climate.thermostat_room_1', 'temperature') != 26 }}
(% endif %}
last line, you have a parenthesis instead of a curly bracket
yes, good catch
Thanks
It was my mistake at the first place ๐
Have you tried
{{{{ ilo_data.temperature['01-Inlet Ambient']['currentreading'][0] }}?
@deft timber That doesn't seem to work, config check gives me: Invalid config for [sensor.hp_ilo]: invalid template (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['monitored_variables'][14]['value_template']. Got "{{{{ ilo_data.temperature['01-Inlet Ambient']['currentreading'][0] }}". (See ?, line ?).
removing the extra {{ at the start fixes it
It was my mistake at the first place ๐
@deft timber yes but it's Okay
Thank you very much @deft timber, @brisk temple and all the others. You help me fix some of my zwave issues with this templating.
Hi, I'm having a syntax issue with a script but can't figure it out. May you please give a look? It's here: https://pastebin.com/fWTyJ38n
what's wrong?
for one, you don't put {{ xx }} in a block of {% xxx %}
just use the variable name as-is, since you're already in a tempalte
you've done that throughout
I'm unable to pass variables from an automation to a script. I'm following the recommendations of https://www.home-assistant.io/integrations/script/#passing-variables-to-scripts
Here is my script:
set_temp_until_okay:
sequence:
repeat:
while:
condition: and
conditions:
- condition: template
value_template: '{{ repeat.index <= 5 }}'
sequence:
- service: persistent_notification.create
data_template:
title: 'Thermostat {{valve}} tentative {{repeat.index}} ร {{now().timestamp()|timestamp_local}} '
message: 'Looper has triggered.'
- delay: "{{ delay }}"
And I'm calling it this way from dev console with this data and calling the service directly through script.set_temp_until_okay:
data:
valve: climate.thermostat_entresol
virtual_switch: input_boolean.vs_entresol
delay: '00:00:05'
The delay I pass in data is not considered as well as {{valve}}
should work
you have too much indentation
It goes 5 times into the loop immediately and the title of notification is Thermostat tentative 5 ร 2020-10-16 23:20:32
you have too much indentation
@inner mesa You think that may be the issue?
probably not, just inadvisable
I'll look to that tomorrow. Thanks again to all for the help.
@acoustic wedge This works fine for me: https://hastebin.com/ajegorubic.less
calling script.test2 generates a persistent_message every 10s
Hi Friends. I'm using Dark Sky API & trying to get it to show the forecast data with the time its predicted to happen. For example for "sensor.dark_sky_temperature_6h" have it show "45ยฐF (Sat 1:50A)". I don't have much experience with templates and can't figure out the correct way to add time
I have a custom component sensor with the 5 latest bank transactions. It's being updated every 20 minutes. Any ideas how I can make an automation that notifies me for every new transaction? I only want to be notified once of every new transaction. Here is the info I have in the sensor: https://pastebin.com/Fw4eb27K
Hi all
Do any of you recall a method to manage hvac in a coupled manner?
I've tado for heating and samsung clima for cooling (and heat pump if needed). But in this way I've two thermostats in my house.
I was thinking in using a template to emulate the switch between cold and hot.
In an automation is there a template variable or object that holds the name of the automation that exectued?
Similar to trigger.entity_id but for the automation name
not that I can find. The state of the automation changes because the current attribute is updated, but I don't think there's any way to know which automation you're in. Is this for passing to a common script or something? If so, you could just pass a variable to a script identifying the origin
Yeah. Im thinking about a mobile notification action that disables (effectively muting) an automation for say 1t minutes. I didn't want to have to make an automation for each notification type.
Hi. I need help.
From device tool, we can play youtube url with media extractor. Is there a way or template that we just paste url in lovelace and play on device?
calling
script.test2generates a persistent_message every 10s
@inner mesa Thanks. It was exactly what I was doing but now it works ๐
If I trigger the script from another script, it works perfectly. But if I trigger it from an automation, then, when the loop is over, it starts again.
Here is the automation:
- alias: looper
initial_state: false
trigger:
platform: state
entity_id: automation.looper
action:
- service: script.test
data:
delay: '00:00:03'
And here is the script:
test:
sequence:
repeat:
while:
condition: and
conditions:
- condition: template
value_template: '{{ repeat.index <= 3 }}'
sequence:
- service: persistent_notification.create
data:
message: 'test {{repeat.index}}'
- delay: "{{ delay }}"
i want to create a template switch where the value_template uses the numeric value of another sensor to determine 'on' or 'off' ...
on
{% else %}
off
{% endif %}```
is that the most elegant way of doing that?
you can write single line statement as well {{ "ON" if states('sensor.bedroom_tv_wattage')|float > 20 else "OFF" }}
Oh Nice!
Thanks
Is there a way using templates where I can put in a condition. โIf the value has been over 20 for x minutesโ so to speak?
I guess not unless I put in a helper of sorts?
You can use the time pattern trigger for that
In a template switch?
Yeah thatโs what I figured. Im trying to get a template switch set up. Will spend some more time reading up. Thanks for your comments!
yeah but don't go overboard with automations making them super complex. Keep them simple with proper naming so that tomorrow if there are issues, it is easier to debug. I have seen people (including myself) making it super nested complex and when 1 thing breaks, very difficult to debug
I set a 'house state' (day, evening, sleep) and trigger individual automations based on that only. So every automation triggers on the house state, and does just one thing.
Hhi. I need help. Using media extractor, we can play url in automations, is there a way to paste url from lovelace ???
Like in mini media player, there is txt box for input text to anounce on player.
Same like that if txt box for paste url then play on speaker or chrome cast device
whoops was scrolled up
hello, Im trying to put field from my script to some condition
but Im getting an error, when I try to call this script, it says that script has failed
extra keys doesnt allowed @plucky token[speaker_name]
is it even possible to put into templating field from a script?
@rare panther @trail ginkgo you can just use a template binary sensor for that.
"{{ states('sensor.bedroom_tv_wattage') | float > 20 }}"
@buoyant pine the true/false becomes on/off? Also, can I do that with is_State too?
Yes and yes, you can use any template you want
Cool. I shall try tomorrow. Done for the day ๐ Thanks!
Is this a proper way to setup random rgb colors
rgb_color: ['{{ (range(0, 255)|random) }}','{{ (range(0, 255)|random) }}','{{ (range(0, 255)|random) }}']
Is there a way using templates where I can put in a condition. โIf the value has been over 20 for x minutesโ so to speak?
@trail ginkgo โdelay_on:โ and โdelay_off:โ in the template binary sensor may help with that
I have a custom component sensor with the 5 latest bank transactions. It's being updated every 20 minutes. Any ideas how I can make an automation that notifies me for every new transaction? I only want to be notified once of every new transaction. Here is the info I have in the sensor: https://pastebin.com/Fw4eb27K
hi, I'm playing around with rest_command and templates
using
payload: '{ "iot2tangle": [ { "sensor": "Homeassistant1", "data": [ { "value": "{{val1}}" } ] }, { "sensor": "Homeassistant2", "data": [ { "mp": "1" } ] } ], "device": "DEVICE_ID_1", "timestamp": 1558511112 }'
works, but if I want to use a sensor value I get into troubles with the quotes I guess
payload: >
{ "iot2tangle": [ { "sensor": "Homeassistant", "data": [ { "value": " {{(states(sensor.bb_aussen_temperatur) |float)}}" } ] }, { "sensor": "Homeassistant2", "data": [ { "mp": "1" } ] } ], "device": "DEVICE_ID_1", "timestamp": 1558511112 }
Any hints ...
quotes are missing around sensor.bb_aussen_temperatur
๐คฏ thanks - I could now forward the first sensor value from homeassistant to the IOTA Tangle - https://explorer.iot2tangle.io/channel/f02d8c183e418407d6e5252a9184537058df5e99f166751cb56d1afbcb900be10000000000000000:068c4ffe9dbc042c50139e1a
I think that has potential to become a new component ๐
data:
entity_id: media_player.bedroom_tv
source: "{{ tv_source }}"```
is this legit? I can use it variable as tv_source declared above, in my script?
should work - you can check as example https://www.home-assistant.io/integrations/tag/ - where variable are heavyly used
entity_id: script.bedroom_tv
data:
tvsource: "Netflix"```
from log: Bedroom TV toggle via encoder: Error executing script. Invalid data for call_service at pos 1: extra keys not allowed @ data['tvsource']
and tvsource is my field (variable in script bedroom_tv.yaml) => fields: tvsource: description: Particular application (eon, yt, netflix..) example: Netflix
If you are calling the script with the script turn on service (instead of directly) you need to use the variables: block. See the first example here https://www.home-assistant.io/integrations/script/#passing-variables-to-scripts
thanks, it working now, I missed that variables: part ๐
and does somebody have an example for rotary encoders and dimming lights?
something like this
nothing really happens though
logs: Error rendering data template: UndefinedError: 'sensor' is undefined
you have to use states.sensor.bedroom_entrance_led_ceiling_dimmer
or {{states('sensor.bedroom_entrance_led_ceiling_dimmer') | int }}
thanks @deft timber it works now ๐
and another question - I want to control my 6-zone amplifier volume control
entity_id: media_player.zone_13
data:
volume_level: >
{{states('sensor.bedroom_entrance_actuator_1') / 100 | float}}```
I can see clearly that volume in HA is setup like 0.somethng
0,26 so I decided to my encoder values from 0 - 100 divide by 100
again I have a trouble with this one also
my volume_level doesnt respond it seems
The | has the priority over the /, you should do {{ (states('sensor.bedroom_entrance_actuator_1') / 100) | float}}
otherwise you are just converting the 100 in float
Actually it should be {{ states('sensor.bedroom_entrance_actuator_1')|float/100 }}
the solution it seems doesnt work @deft timber , I will try @fossil venture solution also
Im getting unkown error when Im testing in templates section
Hmm, I don't really understand, but okay...
States are always strings. You need to convert the to numbers ("float") before attempting division.
thanks guys, it works ๐
just a short question - https://hastebin.com/oledinipan.yaml
I have left and right encoder near my bed, how to setup volume form one or another
maybe in action to set trigger.state or something similar?
and ofc, I need to set other encoder value, when second one is toggled
you could simply use 2 automations
i don't thing you have access to the trigger info ({{trigger.*}}) when using the state trigger, only when using an event trigger
fyi you can also simulate an 'or' by using the choose statement
@sonic nimbus your hastebin is blank
i don't thing you have access to the trigger info ({{trigger.*}}) when using the state trigger, only when using an event trigger
@deft timber not true: https://www.home-assistant.io/docs/automation/templating/#trigger-state-object
oh ok, good to know, thanks ๐
i want to send a json msg to wled (https://www.google.com/search?q=wled+json+api&rlz=1C1CHBF_enDE840DE840&oq=&sourceid=chrome&ie=UTF-8). how to i do that?
.rest_command perhaps?
.rest_command perhaps?
@buoyant pine thanks
wled_lor0:
url: http://ip-address/json/state
method: POST
payload: '{"lor":0}'
content_type: 'application/json; charset=utf-8'
this is working fine
now i want to make a switch depending on the value of lor (0/1/2)
- platform: rest
name: Wled Lor
resource: http://192.168.1.39/json/state
# is_on_template: >
# {% if value_json.lor == 1 %}
# True
# {% elseif %}
# {% value_json.lor == 0 %}
# False
# {% endif %}
headers:
Content-Type: application/json
body_on: '{"lor": "1" }'
body_off: '{"lor": "0" }'
first i get error for the commented part, then with the code switch is not working...if i turn on the switch, nothing happens in the light and state of the switch gets back to off
is_on_template: "{{ value_json.lor == 1 }}"
oh actually, you don't even need that since you defined body_on: @median mason
two things:
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:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
Please don't say I have an error or describe an error. Share the whole actual error message so we can help you.
i see no msg after i turn on the switch in logs
but the switch turned to off by itself
Hello, I am trying to put entire domain to history exclude , and then individual entity in include. But it's not working. Should I be able to do something like that?
include:
entities:
- device_tracker.i5gulodesktop
exclude:
domains:
- device_tracker
From this, it sounds like that won't work:
Filters are applied as follows:
No includes or excludes - pass all entities
Includes, no excludes - only include specified entities
Excludes, no includes - only exclude specified entities
Both includes and excludes - include specified entities and exclude specified entities from the remaining.
you're in that last category, and I would expect it might include that one entity and then exclude the whole domain
I'd have to think through how to accomplish that, but docs are here: https://www.home-assistant.io/integrations/history/
probably easiest just to exclude the device_tracker entities that you don't want
yeah, I figured, I will just to them by hand, thanks!
Hi all, I want my automation to start 5 minutes before my input_datetime, how should I template that?
something like: trigger: platform: template value_template: '{{ ((now().strftime("%s") | int + 300) | timestamp_custom("%H:%M:%S")) == states.input_datetime.alarm_clock.state }}' ?
Although the upper code is without error (I can save the automation) it is not triggering the automation :/ how come?
Okeee seems like I need a sensor.datetime
@marble jackal so i'm using these two templates:
{{ (as_timestamp(state_attr('sun.sun', 'next_rising')) - ((12*60*60 - (as_timestamp(state_attr('sun.sun', 'next_setting')) - as_timestamp(state_attr('sun.sun', 'next_rising')))) / 2)) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}
{{ (as_timestamp(state_attr('sun.sun', 'next_setting')) + ((12*60*60 - (as_timestamp(state_attr('sun.sun', 'next_setting')) - as_timestamp(state_attr('sun.sun', 'next_rising')))) / 2)) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}
but the two values (currently) are:
2020-10-19 18:47:50
2020-10-20 06:47:50
so "rising" at 6:47pm tonight, and "setting" at 6:47am tomorrow
i'm guessing that's why i need to wait until after sunset?
so that both sunrise AND sunset are for the next day
I hope that lizard knows how much time and effort you're putting into this ๐
or maybe he's just annoyed that the lights are going on and off at weird times
what the fuck is happening with the sun
The sun2 integration might make things easier for you. https://community.home-assistant.io/t/enhanced-sun-component/63553
Sun 2.0โข๏ธ
i did look into sun2, but couldn't get it working right at the time ๐ค
but am i right that's why i need to set them AFTER sunset?
but am i right that's why i need to set them AFTER sunset?
@blazing burrow yes
They are 12 hours apart though, so that part is working ๐
I have a custom component sensor with the 5 latest bank transactions. It's being updated every 20 minutes. Any ideas how I can make an automation that notifies me for every new transaction? I only want to be notified once of every new transaction. Here is the info I have in the sensor: https://pastebin.com/Fw4eb27K
@marble jackal it turned my lights off at the right time last night (after I manually set them), and ran at midnight to update them, so as long as they turn on right (in about an hour), I think we got it ๐๐
@distant plover you have an entity with the name "transactions" that list all that below it as attributes?
The entity is called 'bankaccount' or something and it has the available funds and balance. But then it has an attribute called transactions that contains the last x transactions.
The pastebin only shows 2 transactions
@distant plover ok so if you use "bankaccount" as the entity in a state trigger with the attribute "transactions" and leave the to and from fields blank it will fire that automation any change that takes place with that attribute like a new entry
Hmm... ok. I think the transactions get updated though as they're probably first reserved or something and the finalizes. But maybe tackle that later. So if I listen for any change like you suggest, how would I grab the info from the latest new transaction into a push message?
@distant plover this is an #automations-archived question
the question i answered was an automations question lol
Hehe... Well, I know how to send the push message, but I don't know how to get only the new transaction. And that's what Tinkerer suggested I'd go to templates for.
I made the transactions part of the custom component so I can modify it if that helps.
So I hope this is the right place
I'm using this to scrape an rss feed for the menu at my kids school
@distant plover this might work. is the entity name bankaccount or sensor.bankaccount?
{{ state_attr('bankaccount', 'transactions').accountingDate[0] }}
The problem is that the lunch_2_merged sensor doesn't capture the entire menu but only one of two lines separated with </br>
sensor.bankaccount
and if I use the sensor.lunch_2 only for example, it captures the entire menu but shows everything in a line, including the </br>
sounds like a job for regex imo
@bitter atlas UndefinedError: 'list object' has no attribute 'accountingDate'
@distant plover {{ state_attr('sensor.bankaccount', 'transactions').[0]accountingDate }} so what you should do is create a template sensor with this as the value that way you get a entity that has the result of this as the state and then use that in your state trigger
[0] goes before accountingdate
doh
Then I got a date, yeah
you can use that to create other sensors if need be or use something else as the trigger etc
@distant plover the easiest way to handle this is to make a template sensor that produces the latest transaction
Now I have a template sensor with the accountingDate as state
@muted berry , {{ states('sensor.lunch_2_merged') | regex_replace("^(.*)<br\/>(.*)<br\/>(.*)$", "\\1 \\2 \\3") }} will show the 3 lines in a single line
good lord
regex is always fun to look at
regex: for when you've exhausted all other available options
or {{ states('sensor.lunch_2') | regex_replace("<br\/>", " ") }}, easier ๐
@muted berry ,
{{ states('sensor.lunch_2_merged') | regex_replace("^(.*)<br\/>(.*)<br\/>(.*)$", "\\1 \\2 \\3") }}will show the 3 lines in a single line
@deft timber how would I go about making it so that it does line breaks?
sensor:
- platform: template
sensors:
latest_transaction:
value_template: >
{% set transactions = state_attr('sensor.bankaccount', 'transactions') %}
{% set dates = transactions | map(attribute='accountingDate') | list %}
{{ dates | max }}
attribute_templates:
amount: >
{% set transactions = state_attr('sensor.bankaccount', 'transactions') %}
{% set dates = transactions | map(attribute='accountingDate') | list %}
{% set maxdate = dates | max %}
{% set transaction = transactions | selectattr('accountingDate', 'eq', maxdate) | first %}
{{ transaction.amount }}
its one of those things I always have to go back and refresh myself with everytime i have to use it. like my brain refuses to keep it stored in long term lol
it's because it's trying to tell you something
@distant plover then you just make a new attribute for each item you want using {{ transaction.xxx }} for whatever
{{ states('sensor.lunch_2_merged') | regex_replace("<br\/>", "\n") }}
if your latest transaction is always the zero slot... then this is easier
sensor:
- platform: template
sensors:
latest_transaction:
value_template: >
{{ state_attr('sensor.bankaccount', 'transactions')[0].accountingDate }}
attribute_templates:
amount: >
{{ state_attr('sensor.bankaccount', 'transactions')[0].amount }}
Latest will be the zero, but in an update there might be several new transactions
big spender, eh?
If I draw my card in a shop at 12:00 and then in another at 12:05 and the sensor is updated at 12:20 (every 20 minutes)
@distant plover then you're going to have a hard time
@distant plover are you wanting an automation to notify you or something? would be alittle helpful to know what your end goal was
Yeah, thats the intention SonomaGTS
so you want it to text you the details or simply that a transaction was changed?
your bank might have the ability to send you messages when transactions happen (usually over a certain amount you define)
I need the details ๐
do the transactions hold a history? I.E. are old ones in the list when it updates? When is that list purged
@buoyant pine They don't. But they have this API, hehe.
{{ states('sensor.lunch_2_merged') | regex_replace("<br\/>", "\n") }}
@deft timber this is what's actually in the template though value_template: "{{ states('sensor.lunch_3').split('<')[0] }}"
you can get the details of the latest with what petro posted, otherwise you would have to settle for the entire 5 listings regardless if some were new or not
is it always five transactions?
@mighty ledge Hmm... well, in the custom component I only ask for the latest 5 but the API provide access to entire history I think.
or
{{ states('sensor.lunch_2') | regex_replace("<br\/>", " ") }}, easier ๐
@deft timber The entire part - https://pastebin.com/BVCXB9ve
I've made it a variable for users to set it themselves, numberOfTransactions: 5 https://github.com/sepodele/home-assistant-sbanken
if so, if they're all under the 255 character limit, you could make an automation that writes each transaction to an input_text and notifies you when one of those changes...problem is you'd need logic that checks that one input text didn't just move to another input text (because of new transactions)
You're going to need a way to store the last read transaction's date & another attribute after you send your notification. Then the next time you send a notification, you stop when you get to that transaction date & attr.
and you'll have to do that every time. Probably through an automation and an input_text
no template sensors
thoughts on the message above yours petro?
Yeah, that's a similar approach just slightly different
bit of a PITA but it could possibly work
it's alll the same, you basically need to track the last notification transaction you sent
Headache incoming... I'm starting to think it's not worth the effort, hehe
Would it be easier to modify/add stuff to the python in the custom component?
you should get that checked out
@distant plover yes
1000% easier
but you need to know python
Not sure to follow @muted berry , value_template: "{{ states('sensor.lunch_3') | regex_replace('<br\/>', '\n')}}" doesn't do the trick?
you couldn't get details of every transaction but you could get a count all the transactions made within each 20 minutes to display along with the latest
@mighty ledge I know just enough that I added the transaction part to the original component ๐
Not sure to follow @muted berry ,
value_template: "{{ states('sensor.lunch_3') | regex_replace('<br\/>', '\n')}}"doesn't do the trick?
@deft timber I'm saying that I have more stuff in that template than what you wrote. The split part is missing. Do you mean it should look like this? "value_template: "{{ states('sensor.lunch_1') | regex_replace("<br/>", " ").split('<')[0] }}""
you don't need the split anymore
Oh
I'll try it immediately
Yaay! It works! Would this produce a comma in between the items then? " regex_replace('<br/>', ',\n')}}"
yes, it will
โค๏ธ you're an angel! Much obliged
๐
It doesn't result in a new line but that's fine, I have commas between lines now at least
I guess the state is not multiline
Not sure what that means lol
hello, is there anyone that is good with mqtt value templates in yaml that could help me figure out how to get a json message from mqtt that sends a 1 or a 0 to translate into open or close for a window sensor?
i can pass the 1 or 0, i can pass the 0 for close i just cant get the open to pass when the sensor goes to 1
current yaml
-
platform: mqtt
state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
name: "Kitchen Window 1"
value_template: '{% if value_json.id is equalto 381036 %} {{value_json.reed_open}} {% else %}
{{states.sensor.kitchen_381036.reed_open}} {% endif %}'- platform: mqtt
name: "Kitchen Window 1a"
state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
value_template: >-
{% if is_state('sensor.kitchen_381036.reed_open','1') %}
Open
{% else %}Closed
{%endif %}
- platform: mqtt
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:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
Either way, remove the quotes around '1'
ah
let me give that a try, thank you
also is there a way to combine the 2 value templates so i dont have 2 sensors, or is it better to have them separated out?
I don't really see why you have the two sensors in the first place
id rather not have 2, but this was the only way i could figure out how to get data from these window sensors. im using the honeywell2mqtt pulling the json reed info which is 1 or a 0 which ive done, now id like them to report as open or closed in the ui
still doesnt change states
name: "Kitchen Window 1a"
state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
value_template: >-
{% if is_state('sensor.kitchen_381036.reed_open', 1 ) %}
Open
{% else %}Closed
{%endif %}```
this doesn't look like a valid entity_id: sensor.kitchen_381036.reed_open
Also what is the point of making this an mqtt sensor?
its coming from my mqtt json honeywell2mqtt window sensor
state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
name: "Kitchen Window 1"
value_template: '{% if value_json.id is equalto 381036 %} {{value_json.reed_open}} {% else %}
{{states.sensor.kitchen_381036.reed_open}} {% endif %}'```
i can get the state to change from 1 to 0 i just want to now change the 1 and 0 to open and close
@buoyant pine why would you remove the quotes around the 1?
Integer vs string
right. All states are strings
for now
Oh right, whoops. I was thinking it was coming from mqtt
@maiden jungle Still, sensor.kitchen_381036.reed_open is not a valid entity ID. If you stick that in
-> States, I expect you'll get nothing
is that an attribute?
reed_open
or is it just the state of sensor.kitchen_381036?
@rugged laurel that sounds ominous
it is what it is
its one of the mqtt messages i see in the explorer - reed_open and its the only message that changes when the window opens or closes
Is that actually being worked on or is that just an Eventually โข๏ธ thing?
Ignore the explorer, check the acual state object as instructed
I beleive it'll be in 0.117
It's in dev allready @hollow bramble
hmm. Sounds like it's going to break a lot of stuff
nah, most will probably not notice, but you can clean up some places where you cast to other types
the only sensor that i can see in the states dev tools are the 2 that i made
Kitchen Window 1, Kitchen Window 1a
Well anyone that uses is_state for numeric comparisons is going to get burned
Or booleans? or are those still going to be 'on' and 'off'?
I think is_state still does string compare
if it's intelligent about casting/coercing the state to be compared to the type of the entity, it should be ok, right?
right now, we're manually doing the opposite with filters on the entity state
so ive tried this ( see code), changing the sensor that shows a state in the devs tools, still no joy - platform: mqtt name: "Kitchen Window 1a" state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036" value_template: >- {% if is_state('sensor.kitchen_window_1','0') %} Closed {% else %}Open {%endif %}
I don't really know what you're doing there - your value_template is ignoring the mqtt state
review some of the examples here: https://www.home-assistant.io/integrations/sensor.mqtt/
if your goal is to test the published value, then you need to test that
What exactly are you trying to accomplish?
I have this binary_sensor that doesnt seem to be working. Can anyone help?
platform: template
sensors:
binary_sensor_vacation_mode:
friendly_name: "Vacation Mode"
value_template: >
{% if is_state(" input_select.dm_status_dropdown_nodered", "Extended Away") and is_state("input_select.pk_status_dropdown_nodered","Extended Away") %}
on
{%- else -%}
off
{%- endif %}
Just do {{ is_state("input_select.dm_status_dropdown_nodered", "Extended Away") and is_state("input_select.pk_status_dropdown_nodered","Extended Away") }}
also one of your sensor names had an extra space
nice catch - how do you see that?
With my ๐
in the value_template?
Are you asking where the extra space was?
yeah sorry
in your first is_state
What? No. It was in your sensor entity_id string
im trying to change the 1 and 0 that i can see in the states to open and close
but why are you trying to make a separate sensor @maiden jungle ?
im not sure how to do the formatting , id love not to create a separate sensor. as you can tell im not very well versed yet @hollow bramble
ive tried to to do but just cant figure out the right formatting to pass the info correctly to go from the 1 to open or 0 to close - platform: mqtt state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036" name: "Kitchen Window 1" value_template: '{% if value_json.id is equalto 381036 %} {{value_json.reed_open}} {% else %} {{states.sensor.kitchen_381036.reed_open}} {% endif %}' {% if is_state('sensor.kitchen_window_1','1') %} Open {% else %}Closed {%endif %}
sensor.kitchen_381036.reed_open is not a valid entity, as you've been told several times ๐
yes i know, this was in my notepad as a quick copy paste, its more of the formatting in yaml to combine the to value templates that im struggling with updated
sorry for not replacing that
hello, is there anyone that is good with mqtt value templates in yaml that could help me figure out how to get a json message from mqtt that sends a 1 or a 0 to translate into open or close for a window sensor?
i can pass the 1 or 0, i can pass the 0 for close i just cant get the open to pass when the sensor goes to 1
Refreshing the question...
what you've got there is pretty jumbled up
you'd need to post the actual json value of that topic value, if it's json at all
if it's really just "0" or "1" (unformatted), then something like this should work:
value_template: "{{ 'closed' if value == '0' else 'open' }}"
I don't know what the intent of the rest of that is
the link I posted earlier + this should be helpful in parsing the incoming data: https://www.home-assistant.io/docs/configuration/templating/#processing-incoming-data
like
- platform: mqtt
state_topic: 'homeassistant/sensor/window-door/Honeywell-Security_381036'
name: 'Kitchen Window 1'
value_template: "{{ 'closed' if value == '0' else 'open' }}"
so this is my sample startup log on my sensors with the addon that i use to pull the info, this specific sensor is not a window sensor so its missing the reed open data but it shows you the raw info im working with, ```homeassistant/sensor/window-door/Honeywell-Security_111635
- echo '{"time"' : '"2020-10-20' '15:33:47",' '"model"' : '"Honeywell-Security",' '"id"' : 111635, '"channel"' : 10, '"event"'+ : 132,/usr/bin/mosquitto_pub '"state"' -h : 192.168.1.149 '"open",' -u '"contact_open"' username : -P 1, password '"reed_open"' -i : RTL_433 0, -r '"alarm"' -l : -t 0, homeassistant/sensor/window-door/Honeywell-Security_111635 '"tamper"'
: 0, '"battery_ok"' : 1, '"heartbeat"' : '1}'```
if this was a window sensor the reed_open would have a 0, and my yaml, pulls the reed_open data and gives that 1 or 0, which i can see in the states dev tools - platform: mqtt state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036" name: "Kitchen Window 1" value_template: >- '{% if value_json.id is equalto 381036 %} {{value_json.reed_open}} {% else %} {{states.sensor.kitchen_381036.reed_open}} {% endif %}'
hope this helps clears things up a bit on where i am at on trying to get the 1 and 0 to display open or close
i have tried RobC and boneheadfraggle suggestion with no joy
that's because that template assumes it's just a value and not json
I don't know how to read that raw data. is that coming from MQTT?
yes it is
the reed_open part
i know in this example there is nothing there, this example is not a window sensor
I can't identify the value of it from there. it doesn't look like valid JSON payload
then it'll be hard to help
caught it
you need to get away from this "is equalto" stuff and start using real syntax
+ echo '{"time"' : '"2020-10-20' '15:47:25",' '"model"' : '"Honeywell-Security",' '"id"' : 381036, '"channel"' : 10, '"event"' : 132, '"state"' : '"open",' '"contact_open"' : 1, '"reed_open"' : 0, '"alarm"'+ : 0,jq '"tamper"' --raw-output : .id 0,
'"battery_ok"' : 1, '"heartbeat"' : '1}'
+ tr -s ' ' _
+ DEVICEID=381036
+ echo 381036
381036```
'"reed_open"' : 0
then, value_template: "{{ 'closed' if value_json.reed_open == '0' else 'open' }}"
A binary template sensor with an opening device_class and this template, value_template: "{{ value_json.reed_open == '1' }}" would be more applicable.
ill try that as well, thank you, also thank you to everyone for trying to assist
Yeah, thatโs a better solution
why is it asking for an off delay, this is confusing me
that's optional
even when in red its saying missing property its still optional?
config passed, i just worry when i get those warnings
Where does it give you that error?
same line as - platform: mqtt
No, what are you doing that says that? You said config check passed
i was just typing in my binary sensor yaml , and as soon as i put in - platform: mqtt it came up with missing property off delay
In VSCode?
yes
Ok, thatโs all I wanted to know
ok cool
What did you end up with?
name: Kitchen Window 1c
state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
qos: 0
device_class: opening
value_template: "{{ value_json.reed_open == '1' }}"```
Ok
its not changing states
hmm, im going to have to come back to this after a bit. i appreciate your patience. thank you
hey, I new to HA, how to only show 1.1 W - and not 1.xxxxxxxxx
value_template: >-
{% if is_state('light.0x000b57fffe116813_light', 'on') %}
{{0.2 + state_attr("light.0x000b57fffe116813_light", "brightness") * 5 / 255}}
{% else %}
0
{% endif %}
best regards
"|round(1)"
{{(0.2 + state_attr("light.0x000b57fffe116813_light", "brightness") * 5 / 255)|round(1)}}
@inner mesa thanks a lot here, might be a side question are it also posible to do the same on a brightness group ?
light group?
yes
I'm not following what you're trying to do. In general, you can do anything to a light.group that you can do a light
i'm trying to get made so i can see an estimate of watt consumption on my light as my ikea bulbs do not have support it that kind of stats
yes
clever
you can do the same calculation on a light.group, but I don't know how it decides what the brightness of the group is
based on the individual lights
if they can all be different, you may want to use a template that iterates through them all and adds up the brightness levels instead
dont know jet, did had a plan todo the calc on every brightness in the group. and the template stuff will be the way to go
shouldn't be too hard. just need to play around in
-> Templates
:) will do
Need help with an if template.
Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
{% if (trigger.entity_id == 'input_datetime.coffee_monday') %) doest seems to work for me
Need a bit more detail on what youโre actually doing and expecting
I have an automation with seven datetime trigger (each day of the week) in the condition section (template), I have an if statement for each day to look if an input boolean are active or not for this day, So if Now().weekday = today and input_boolean.today are active, go to the action, but I need to know which trigger have actually triggered the automation
Are you letting it trigger or are you manually triggering it with โexecuteโ?
I am letting it trigger, I know it because my coffee maker doesnt trigger for the last few day when i've add the if trigger.entity_id = input_datetime ... in the condition section.
Without it.... the action will trigger the action even if its not the good day
And I need my coffe at 6 AM ^^ !
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
the whole automation
you don't get trigger.entity_id with platform: time
you do get trigger.now, which presumably you could compare to states('input_datetime.xxxx')
trigger.now = the datetime object. Does the object are the entity_id ?
The trigger.now are the timestamp. Ok, i'll have to find another solution
I'm pretty sure you could make it work
The thing i'm trying to avoid is to have this automation split in 7 one.
it's no worse than what you already have
you already have now().weekday==xx, so you just need to use triggger.now.weekday() = xxx
actually, what is that even doing? You just care about what the day is, not what triggered the automation
just get rid of the whole trigger variable test everywhere in the condition
it all seems overly complicated
Hi all, currently I have this setup for RM broadlink AC switch which work fine. However I want to make it better and also adding binary_sensor which will allow me to know the correct state of the AC. Need some help on reorganizing this yaml. Can somebody help?
No, i've test it several week without this and i had false trigger. Need this part in the condition. But your last proposition is working. Thanks @inner mesa
the new binary is called binary_sensor.real_ac_daikin_status
@inner mesa huh? its been working since I start HA, that script never being change
anyway is there idea how should I rewrite the sequence so it will add my binary_sensor?
Is it possible to get friendly name of this: {{ states.sensor.sensorname.attributes.min_entity_id }}? I want to use it with google tts but not say sensor in it.
hi i have
- service: tts.google_say
entity_id: media_player.woonkamer
but how to have the
media_player.keuken added so it uses both ?
do i have to do
entity_id: media_player.woonkamer, media_player.keuken
?
Yes, or
entity_id:
- media_player.woonkamer
- media_player.keuken
rx
Hi all. Having a bit of trouble with a script - I want the transition value of a scene.turn_on service call to be drawn from an input helper. currently I have this:
transition: '{{(states('input_number.alarm_minutes')|float))*60}}'```
This seems to evaluate correctly in the template helper, but it's throwing an error "Invalid data for call_service at pos 2: expected float for dictionary value @ data['transition']" - am I missing something obvious? Thanks ๐
(there's a spurious line-break in there - the transition line is all one line in scripts.yaml)
@rare oyster , states.sensor.sensorname.attributes.min_entity_idcontains the name of the entity of which you want the friendly name ? If so,
{{ state_attr(state_attr("sensor.sensorname", "min_entity_id"), "friendly_name") }} should do it
@deft timber Thank you very much!
@paper nexus , you have a 2 "(", and 3 ")"
'{{(states('input_number.alarm_minutes')|float)*60}}'
@deft timber Oh yes, so I do! That's stopped the error showing up, but it's now transitioning instantly, rather than over a minute (the value of the input_number currently being 1) ๐ค
which version of HA are you using ? I think you should use data: instead of data_template: if you are using 0.116
Using 0.116.4, and nil fix using data: instead of data_template:
Huh. This seems to have solved it:
- data:
transition: >
{(states('input_number.alarm_minutes')|int)*60}}
Many thanks for the assist @deft timber ๐
๐
An input_number goes from 70 to 100. How do I create a template light from it, where 70 is 1% and 100 is... well 100%?
{{ ((states("input_number.id")|float) - 70)/30*99 + 1}} ?
Is there an equivalent to ansible's default(omit) filter for HA? I'm trying to make a service call the wraps light.turn_on. I want to be able to apply any of the data attributes from the caller that exist on the light.turn_on service. So like hs_color: "{{ hs_color | default(omit }}" rgb_color: "{{ rgb_color | default(omit) }}" where the caller would typically supply one or the other but not both... I'd like to actually not pass any parameters into the light.turn_on service where the value is not defined by the caller
@wooden sonnet make a script called turn_on_light, then pass the values that you want to pass. Make all the fields in the data section of the light.turn_on service use templates with defaults. Then call the script wherever you want to use defaults.
Thanks. So I need copy the defaults in from the docs explicitly? Ideally I want to flow all of the supported light.turn_on params?
Also if so, how do I convey that the property doesnโt have a default value? default(null)?
Does value_template inside a switch accept unavailable?
I'm not sure. This is what I'm attempting to accomplish: https://hastebin.com/ebawisoquy.less
it works if I'm explicit about which light.turn_on attributes I want to support... but I really want to decide on a case-by-case basis.
err.. I just added default(null) now.. don't think that part works
Get voluptuous.error.MultipleInvalid: two or more values in the same group of exclusion 'Color descriptors' @ data[<Color descriptors>]
can someone just quick check something for me:
value_template: "{{ (states.sensor.temperature_fermentfridge.state) | float < (states.input_select.fermenting_lower.state) | float }}"
this value template should only trigger if the temperature of the fridge is lower than my determined value in "input_select.fermenting_lower" right?
for some reason the automation keeps triggering even though input_select is set to 16, and the temperature has not dipped below that
is it possible this will trigger if the sensor goes to an unknown value?
Hello, can I call Home Assistant Api trough Jinja2 templates like hass object in custom cards?
What are you actually trying to do?
@wooden sonnet Your hastbin post didn't work. You have to assign a default if you want to use default. Otherwise don't use a default, then it's required.
@amber musk No, what are you trying to do?
@mighty ledge try this: https://paste.ubuntu.com/p/58NHDtjZPS/
@amber musk No, what are you trying to do?
@mighty ledge call api to get system metrics
is there a way to convert a state attribute to a virtual "state" that I can track easier in my sql database?
right now the attributes all kick out as a long json string and I'm having trouble accessing the required value contained within
@amber musk are you using duckdns?
@wooden sonnet What you are trying to do won't work. You should investigate a python script instead
@fossil venture I use google ๐คฃ
If so here's some I preprepared earlier https://community.home-assistant.io/t/ha-0-116-supervisor-247-core-and-supervisor-addon-stats/233484/34?u=tom_l otherwise see the beginning of the topic.
@pale idol make a template sensor that extracts the attribute
@mighty ledge I just found this https://community.home-assistant.io/t/reading-a-state-attribute-value/211585/9 and it seems to be along the lines of what I need to do.
do template sensors appear in the recorder as well?
they create entities, so yes
hmmm shows up in the "states" table, inside home assistant, but not in the sql database. maybe it needs to change state before it can populate?
@fossil venture i know that method, I jist thought that I could access the api through jinja2 without that component
@pale idol the database stores state changes, so it may need to change to show up
@inner mesa yep. thats the case. should work now for my needs.
You need to change that with the next SU version @fossil venture https://github.com/home-assistant/supervisor/pull/2154
Nice. Thanks for the heads up.
hello, Im trying to setup my rotary encoder in accordance to my light brigthness and vice versa
is this a legite script to do it
this is setting up a rotary encoder based on the brightness of the light
{{ states('sensor.xagprice' ) | float * states('input_number.xagoz' ) | round(2) }} am i doing this wrong? should my value not be only 2 decimal places
oh nvm i figured it out
you'd need another |float and to surround the result with parens before rounding ๐
Missing casting the input number as a number too. {{ ( states('sensor.xagprice' )|float * states('input_number.xagoz' )|float )|round(2) }} should do it.
hello, I want to be able to put in my conditions if the inpuit parameter is != null or != empty
Is this the right way to go?
can a choose option has multiple sequences? Im not sure either if {{ custom_message != '' }} is a proper way to check if the input param is there or not
you have an indentation problem in your choose
you are missing the conditions: before the condition: for the 2nd and 3rd condition of the choose
yes
but this sequence is too left, I think it should be intended to the right
?
below value_template ?
did you look at the link I pasted? the sequence is at the same level as conditions
still I cant change my audio source
entity_id: script.set_media_player
data:
variables:
speaker: "media_player.zone_12"
audio_source: "AVR Zone2"```
this is the calling example for my script set_media_player
and this is the set_media_player
pardon me
this is the correct script, but either, its not working
I mean it works, but it doesnt set appropriete audio source
if the first condition of your choose is true, then the other conditions won't be evaluated. so if states.media_player.zone_12.state is off, the media_player.select_source will not be called
since your second condition is true (custom_message is not empty), you will never avaluate the 3rd conditions -> and never call the select_source
hm..obviosly I have "nested" conditions
but I dont need that, just each condition for itself
so you should have several choose: statements
oh, for each input in the script I will have one choose:
a choose is a if [cond1] then [...] elseif [cond2] then [...] elseif [cond3] then [...] else [...] statement. If you want if [cond1] then [...] ; if [cond2] then [...] yes you need several choose.
@sonic nimbus if you use template condtions, you can use the shorthand templates in the choose (as from HA 0.115):
So instead of :
- choose:
- conditions:
- condition: template
value_template: "{{ states.media_player.zone_12.state != 'on' }}"
you can use
- choose:
- conditions: "{{ states.media_player.zone_12.state != 'on' }}"
Not an answer to your question, but it does make your code a bit smaller
thanks, i keep forgetting about that ๐
Hi folks, am I correct that I can use a template to create a new climate entity that incorporates an external sensor for my thermostat? It's located in a hallway between 2 bedrooms, so I want the climate entity to read those (maybe an average?), rather than using the internal temp.
I'd love to see a thread or something, but I am coming up empty. I am sure this has been done many times before, so maybe I'm missing something here.
You could create a min/max sensor https://www.home-assistant.io/integrations/min_max/
which will give you the average of your 2 other thermostat
but not sure it will work is climate entity since it can't use the attributes of the entity it is associated to
so I would say a template sensor, were you can compute the average yourself using the attributes of your climate
thanks for the info
i'm starting to wonder if i should just engineer some node red monstrosity to raise/lower setpoint
ie drop to 60 or raise to 75
i would probably not even use the tstat temp because i only care about the 2 bedrooms. the hall will never be cold enough to matter, so maybe min_max will work?
a min/max will give you the average of the states of the entity you are using. If the states are the temperature, you're good. If the states are statuses (on, off, ...), then it won't work
Hi, is there anyway to catch an mqtt sensor update and ignore or discard it before HA processes it?
Well you can filter what gets passed with the value_template
unfortunately it seems that as soon as the value_template is referenced the values will be written to the entity unless I overwrite them in the template itself. I would just like to not process the message at all.
is there a way, when I do a dimming via UI for the light entity, to setup my rotary encoder to brightness level?
Example: I have Xiomi Desk Lamp 1S , and I have a rotary encoder connected to esphome
so, I setup that I can dimm the light of the lamp via that encoder remotely
from another room for an example
but, when I dimm the lamp from lamp button, or via UI, after few minutes it goes to the state of that encoder
so, I need reverse automation, to set that encoder to value brightness lamp
is this doable?
If I use a value_template in a sensor, it doesn't set the sensor to that value (it worked before without a change, probably an update?), however, if I do it in the template dev tools, it gives the right output
Im after the similar solution
how to update sensor value
the only solution that I found is action: service: python_script.set_state data_template: entity_id: sensor.cold_water_rate state: 42
through python_script:
Hey folks, so I'm all about helping myself, but I'm coming up blank on how to deal with the end of the days of "entity_ID" - For example, I have a template switch and I'm calling services by entity_ID - Is there a document that says "Hey, you were doing this, but do this instead" anywhere?
service: climate.set_fan_mode data: entity_id: climate.thermostat_mode fan_mode: Auto Low
huh.....so......hm... and the log doesn't say what yaml they're hiding out in.....
does it ๐
any suggested method for ferreting them out?
(and OK so the switch is still fine, no wonder I was confused)
thanks @buoyant pine you're always throwing me good bones
Just gotta look where you've got template sensors I guess
Gracias amigo
aAAaaah... IT's this little gem, ain't it?
openevse_state: friendly_name: "OpenEVSE State" entity_id: - sensor.openevse_status icon_template: >- {%- if state_attr('sensor.openevse_status', 'state') | regex_match('^[01]$') -%} mdi:power-plug-off {%- elif state_attr('sensor.openevse_status', 'state') | regex_match('^2$') -%} mdi:car-electric {%- elif state_attr('sensor.openevse_status', 'state') | regex_match('^3$') -%} mdi:battery-charging {%- endif -%}
That's what I get for copy-pasting code ๐
OK..well, I guess that's it. Thanks again
U welco
me
no, you
no u
@buoyant pine and I are like this ๐ค๐ป. Sometimes at parties, we find each other finishing the others sentences
You got it though right?
I do now
Indeed โข๏ธ
is there an elegant way to handle a None from state_attr() and output "not found" instead?
some kind of Jinja-jitsu like a ternary operation?
|default("not found")
oh, maybe not
oh.
i was hoping for a x = y ?: 'not found'
do i need to set the first statement as a var?
don't have to but it would make it smaller
{{ val if val else "Not Found" }}```
None is falsy
yeah. looks like default only evaluates on undefined
although i thought None == undefined
unless it's taking a string None
..
nah None is an actual thing
wait there's a thing:
If you want to use default with variables that evaluate to false you have to set the second parameter to true:
{{ state_attr('timer.empty_kitchen', 'remaining')|default('foobar', true) }} works!
oh neat
silly but works ๐
you're not false
how can i get daily increase of covid19 confirmed case from sensor.worldwide_coronavirus_confirmed? This sensor coming from covid19 integration of HA.
what I can think of is a Statistics sensor https://www.home-assistant.io/integrations/statistics. You configure a duration of 1 day, and you will have an attribute min & max which you can use in a template sensor to compute the difference.
Probably simpler to find a decent API and just use the REST integration to pull the value you're after.
what I can think of is a Statistics sensor https://www.home-assistant.io/integrations/statistics. You configure a duration of 1 day, and you will have an attribute min & max which you can use in a template sensor to compute the difference.
@deft timber thanks i will check it
Probably simpler to find a decent API and just use the REST integration to pull the value you're after.
@ivory delta do you know any such API?
No because I don't have a morbid obsession with seeing how many people are dying ๐คทโโ๏ธ
I'm sure plenty of them exist and it won't take much Googling to find one.
pretty much all covid api's report accumulated totals. Always gotta do the math yourself.
there is anyway to create a slider to change colors in light intead of circle?!
Has anyone created a "real feel" sensor based off of temp and humidity?
There's a custom integration that calculates the dewpoint from those two inputs
Not quite what you're looking for, but it can be used as an indication of comfort
yeahs along the same track im looking yeah
i think, could be wrong. real feel temperature is based off of actual temperature and humidity
and dewpoint is the point at which air becomes saturated. which is why they use that number as a comfoort number like you said
Yup
Dewpoint is calculated from temperature and relative humidity. It's the temperature at which the relative humidity would be 100% if the amount of water in the air stays the same
Dewpoint less than 55F is generally considered very comfortable
ahh ok i see how they use that now
its almost a scale rather than an actual temp. so 55+ gets more "sticky" humid feeling
pretty cool and honestly makes more sense than "real feel"
"Real feel" and dewpoint have two different purposes
But yeah, dewpoint is a great indication of how humid it actually is outside
80F @ 70% RH will feel much more sticky than 50F @ 70% RH
well think its cooler/more accurate now because say its 60โข real feel outside based on wind, humidity and all.. that 60โข means two different things when talking to someone from out west where its dry and FL where its humid.
using dewpoint it would be a more accurate indication
cool
learned something new today
that custom integration you speak of in "HACS"? searching dew point didn't turn up any results
No clue, let me find the repo
you can setup a rest for the weather network which has a feels like
that has the code for the rest
- platform: template
sensors:
weather_network_temperature_feels_like:
value_template: '{{ (states.sensor.weather_network.attributes["obs"]["f"] | int * 9/5) + 32 }}'
device_class: temperature
unit_of_measurement: 'ยฐF'
oh, that was 2hrs ago
@topaz walrus see above
I guess I pull dew point from another API of theirs which shows now conditions
hi, trying to build a template {{ trigger.to_state.attributes.friendly_name if trigger.to_state.attributes.friendly_name!=None else "missing" }} that detects if friendly_name is present and puts a useful value if not
it's used in an automation trigger
this doesn't work because when you click execute, i think "trigger.to_state" isn't actually defined.
(it does when it's triggered normally, via state change)
how do i debug this?
if it works when trigger normally, what are you trying to fix?
as you say, there's no trigger when you just hit "execute", so it will never work that way. the trigger variable isn't defined because there's no trigger
yeah, and that's what i've been trying to fix
you can't "fix" it
there's no trigger, so no trigger variable
what do you think the trigger variable should represent in that case?
{{ trigger.to_state.attributes.friendly_name if trigger is defined else "missing" }}
heh
that works, i think
yes, that's better if that's what you're trying to do
initially, I thought you were trying to return the friendly_name if it's been set, or "missing" if not
yeah, that's what i was trying to do, didn't realize trigger is completely undefined.
Is this the right channel to ask help parsing RESTful integration JSON response?
https://www.home-assistant.io/docs/configuration/templating/#processing-incoming-data
Yeah
is HACS supposed to show up in the Integrations list? (Container user)
I don't recognize any custom_component[tm] from the prerequisit list for HACS... sorry if this is not the right channel
you just need to follow the instructions:
Home Assistant Community Store is the successor to the old Custom Updater, and can do so much more - you should check it out. They even have a Discord server for issues with HACS itself.
the fact that you had "integrations" in your question is a clue to the proper channel ๐
you are right of course
Shouldn't this make sure I only get 2 decimals? {{ ((states('sensor.bad_led_over_speilet_power_2') | float) + (states('sensor.bad_taklampe_watt') | float) + (states('sensor.stuebord_taklampe_watt') | float) | round(2)) }}
Sometimes I get values like 45.010000000000005
hello, I tried to have a sensor of the temperature of my cpu but I don't see any add-ons for that. So I tried to create my own template :
- platform: template
sensors:
temperature:
friendly_name: 'Temperature proc'
value_template: shell_command.temp_proc
shell_command:
temp_proc: cat /sys/class/thermal/thermal_zone0/temp```
(I use hassio supervised so this cat command give me the temp of my pi)
but it doesn't work. Do you have any idea ?
ho thank you it's exactly what I want
@distant plover I think you have to round the 3 parameters and not just the third one
But then the calculation could be incorrect, no?
no you just lost a little bit of precision
Yeah, that's what I mean.
or you can do that :
+ (states('sensor.bad_taklampe_watt') | float)
+ (states('sensor.stuebord_taklampe_watt') | float)) | round(2))
}}```
so you are sure that the round is on your 3 parameters
because I think your calculation without this parenthesis round only the third parameter
the | operation seems to be calculated before the +
I see. Thank you ๐
๐
Hi all, I'm using the following template to clean up mqtt input from a ble thermostat. It is perfectly functional but I get the feeling I should be able to shorten the syntax because I'm referencing the same value twice. ' {{ value_json['LYWSD03-24c956'].Humidity if value_json['LYWSD03-24c956'].Humidity != null else states('sensor.ble_temp.attributes.humidity') }} ' Any thoughts?
{{ value_json['LYWSD03-24c956'].Humidity if value_json['LYWSD03-24c956'].Humidity != null else states('sensor.ble_temp.attributes.humidity') }}
Sorry just realised it should be backticks
I'm using it in a sensor template
Then you'll probably add as much work/text making it a variable as you'd save by using that variable twice.
It might look messy right now but it's probably not worth refactoring.
I guess, just a bit ugly was hoping that a bit of 'Jinja-Fu' was available. Thanks anyway
I have this binary sensor w/ this value template
value_template: "{{now().weekday() in (0,1,2,3,4) and states('sensor.date')}}"
any thoughts on why it wouldnt be working? i just want it to evaluate to true/on if tomorrow is monday - thurs
When you say it's not working, what's it doing?
it seems to never be reevaluating
it currently says false but today is a saturday, so it should say that. but for the past week it never evaluated to true
If you put that into
> Templates, what does it tell you?
Then try this and repeat:
{{ states('sensor.date') and now().weekday() in (0,1,2,3,4,) }}
Could just use a workday binary sensor: https://www.home-assistant.io/integrations/workday/
Where's the fun in that? ๐
@buoyant pine i dont want it to evaluate as true if today is a friday
You can define the days
The workday integration allows that.
oh man
But first... you're going to learn something ๐
well now i want my binary sensor to work ๐
Try your template, then try mine.
seems to be working in the template
Yours shouldn't. The first half of your and statement won't evaluate.
The reason yours isn't working properly is that ands will shortcut. If the first half is false, it won't bother evaluating the second half.
Put the thing that changes all the time (sensor.date) first ๐
ohhhh interesting
well it just says false, which probably is what it would do if shortcutting since its a saturday
thanks!
You can tweak the numbers to prove that ๐
yeah i have been ๐
@harsh anchor posted a code wall, it is moved here --> https://paste.ubuntu.com/p/6wvXz8XfKF/
hello wonderful people of the saturday evening templates
or am I the only one? ๐
so I've got myself a iotawatt, and it outputs a lot of json
is there a json way so that I can have all single outputs under a single umbrella, like sub-entities?
I tried like so
https://paste.ubuntu.com/p/PNXjD5yKBS/
but it does not create sub-entites
moreover i did use the outputs[0] selector, but it still carries all the values without care for my selection
do I really need to create a separate entity for each value?
json_attributes is the right way to get certain fields from the response into attributes on the entity you're creating. What state/attributes do you get from your current configuration?
Also, what does the JSON actually look like?
https://paste.ubuntu.com/p/BsXzBfw3yx/
this is the full inputs
taken with curl and jq from commandline, and it's exactly the same I see in my device: its value is the entire json string
Yes, that's normal. What are the attributes of the entity it created?
Remember entities have state (one) and maybe attributes too (many). You can check them at
> States.
honestly I'm not sure what I should tell you: what I see is what I showed you already in json form
I'm playing around with this now, and it's weird: if I use value_template: '{{value_json.inputs[0]}}' I get everything in the states, including also outputs as if the value template had no effect
but if I remove the value template, or leave just value_json then nothing shows
I'm baffled
here is a full state from the developer tools
https://paste.ubuntu.com/p/Vt2t3d68wX/
my last paste was the attributes, straight from the screen
So which piece of information do you want to be the state? You can only pick one.
input voltage is fine
Which field is that? inputs[0].Vrms?
yeah
So you should only need to do value.inputs[0].Vrms
right
You can test if it works in
> Templates with something like this:
{
"channel": 0,
"Vrms": 229.2475,
"Hz": 50.00404,
"phase": 1.48
}]}' | from_json %}
{{ json.inputs[0].Vrms }}```
Feel free to experiment with the last line to extract different values.
yes yours does do what I expect, but when I put it in my config it does not for some reason.... well I'll investigate more
you already opened my eyes on the developer tools ๐
now somehow I have a ton of attributes but no numerical values lol ๐
so I wrote a sensor like this
iotawatt_input_5:
value_template: "{ states.sensor.iotawatt.attributes.inputs[5].Watts }"
but in the UI I don't see the state as a numerical value, but as a json property...
trying to put it in lovelace it says "entity is non-numeric
nothing, looks like using states.sensor.iotawatt.attributes.inputs[n].Watts doesn't return a number
almost like the templated entity is missing a state variable, only has attributes
got it, templating wasn't putting the right number of curly braces
Why do I get Failed to call service input_number/set_value. expected float for dictionary value @ data['value'] when trying to make a service call...
In this template (soon to be used in an automation)
value: {{ states('input_number.fan_speed_trickle') | int + 100 | round | float }}
entity_id: input_number.fan_speed_trickle
It does "resolve" in templates... But not in service calls..
it does work if I just input a number such as 1000 (rpm)
What service are you calling?
You need double quotes around it
The template
No...
value: "{{ states('input_number.fan_speed_trickle') | int + 100 | round | float }}"
entity_id: input_number.fan_speed_trickle
Yes, that
Same error.
You also need some parens. Youโre currently rounding 100
That float doesnโt belong there either
Ummh.. Okay... ?
Yeah, I have tried a few different ways, non has really allowed me to call the service.
... or an automation?
So this should work in an automation:
value: "{{ states('input_number.fan_speed_trickle') | int + 100 | round | float }}"
entity_id: input_number.fan_speed_trickle
?
I think it should be better in 0.117
Ahh, I didn't know about that bug..
You donโt need the |float
Iโll see if itโs fixed in 0.117. Templates return actual data types there
Cool, Yeah. it works in my automation! ๐ Thanks!
Much appreciated for your time and effort to help us!
๐
so im trying to trigger an automation wehever a light state changes from unavailable. I've got this template {% if 'light.' in entity_id and old_state == 'unavailable' %} {% endif %}, but it doesnt seem to be triggering
where did those variables come from?
if looks like you grabbed a single line out of a larger template
or it's just completely wrong
its probably the latter
ok, then random attempt ๐
oh, nevermind. I haven't used that
@inner mesa I'm not opposed to alternative methods though
at the very least, I think you'd want old_state.state == 'unavailable, but I'm still working through how that's supposed to work
ok
~share the whole
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
yeah, I don't really get where that stuff in the thread is coming from or how it even works
this works:
- alias: 'Event Test'
initial_state: true
trigger:
- platform: event
event_type: state_changed
condition:
- condition: template
value_template: "{{ 'switch.fr_' in trigger.event.data.entity_id }}"
action:
data:
message: foobar
service: persistent_notification.create
and to test the state, you'd want trigger.event.data.old_state.state == 'unavailable'
that thread makes it sound like some other variables are being created, and I'm not familiar with them
oh it doesn't like that. now i've got an endless stream of notifications
what do you have now?
it works fine for me when I switch switch.fr_* entities on and off
you get a flood of notifications with that?
is it possible that you have light.* entities suddenly going unavailable?
its unlikely
or at least with a "from_state" that's unavailable
i do have a large number of them, but the network is overall very stable and run by zigbee2mqtt
there is a 1minute timeout between the light disappearing and when it actually gets labelled unavailable too
once I add that "unavailable" check, I get nothing (as expected):
- alias: 'Event Test'
initial_state: true
trigger:
- platform: event
event_type: state_changed
condition:
- condition: template
value_template: "{{ 'switch.' in trigger.event.data.entity_id and trigger.event.data.old_state.state == 'unavailable' }}"
action:
data:
message: foobar
service: persistent_notification.create
I have that in my last paste as well.
I changed "unavailable" to "on" and it notifies me whenever I turn something off (old state was "on")
everything is working exactly as I expect
ok.
i really don't like the UI changing " in to '', but other than that ๐คท
maybe I do have something flapping, but I'm not sure what. I bet there is a way to get the offending entity_id into the notify message
there is, by using exactly the same template in the message of a notification
action:
data:
message: "{{ trigger.event.data.entity_id }}"
service: persistent_notification.create
kinda sounds like it's doing its job and telling you about broken lights
try updating, I guess
im already on 8.3.1 though
then I got nothin'
I'm going to declare the automation as "working as designed", though
@next bluff posted a code wall, it is moved here --> https://paste.ubuntu.com/p/cQDxYCVTch/
I have the template posted up in the paste bin, how I can turn off the entities based on that now?
data:
entity_id: "{{ state_attr('sensor.lights_turned_on_for_two_hours', 'light_entities') }}"
Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
how would i get the values of a input_text and input_number and use it in a autonation
@arctic sorrel will that work with the input_number?
Have you read the docs yet?
ye but im dumb
TL/DR: Yes, it works with any entity
There's a lot of details though
It depends on what you're trying to do, what version of HA you're on, and more
Hence why I keep commenting on the need for actual details ๐
@arctic sorrel so i need to make this work
transition: input_text.fade_time
color_name: red
brightness_pct: input_number.end_brightness``` but im new to templates
Well, you don't have to keep tagging ๐
sorry
See what I wrote before?
brightness_pct: input_number.end_brightness
``` won't work, you need that format I shared
ye i dont realy know bc im new to this
{{ states('input_text.banana') }}
That's how you get the state out, so...
brightness_pct: "{{ states('input_number.end_brightness')|int }}"
Same for the transition
so ```data:
power: true
transition: "{{ states('input_text.fade_time')|int }}"
color_name: red
brightness_pct: "{{ states('input_number.end_brightness')|int }}"
Should be good
didnt work
can you send images
Nope
auto
Auto?
automation
If you dropped that lot in the Service data section, you need to remove data:
ok
ok
Error executing script. Invalid data for call_service at pos 1: expected float for dictionary value @ data['transition']
Replace |int with |float then
so is it "{{ states('input_text.fade_time')|float }}"
Of course, you may want to swap that text for a number ๐
i dont like the sliders
๐คท
is it correct like this service: lifx.set_state data: power: true transition: '{{ states(''input_text.fade_time'')|float }}' color_name: red brightness_pct: '{{ states(''input_number.end_brightness'')|int }}' entity_id: light.ceiling
Looks ok, go paste that into
-> Templates
done