#templates-archived
1 messages ยท Page 118 of 1
well, thanks for your input anyway :) gonna play around later
hmm, could I create an if there? to check that all the 5 sensors have data, unless return the value of another sensor?
you could
would that other value be populated?
it can get a lot messier though
{{ [
states('sensor.sensor_1') if states('sensor.sensor_1')|float else states('sensor.sensor_2'),
states('sensor.sensor_3')...
]|map('float')|sum|round(2) }}```
or are you wanting to default the whole thing if any of them are missing?
{%- set values = [
states('sensor.shelly_makuuhuone_total_consumption'),
states('sensor.shelly_norttinurkkaus_total_consumption'),
states('sensor.shelly_nuutin_huone_total_consumption'),
states('sensor.shelly_tv_taso_total_consumption'),
states('sensor.shelly_tv_taso_viihde_total_consumption')
]|map('float') -%}
{{ states('sensor.other_sensor') if 0 in values else values|sum|round(2) }}
I have the following mqtt light defined in configuration.yaml
- platform: mqtt
schema: template
command_topic: 'insteon/command/modem'
state_topic: 'scenestate/movielighting'
command_on_template: '{ "cmd" : "scene", "name" : "movielighting", "is_on" : 1 }'
command_off_template: '{ "cmd" : "scene", "name" : "movielighting", "is_on" : 0 }'
optimistic: true
state_template: 'value.upper()'
unique_id: 'movielights'
name: 'Movie Lights'
I'm totally guessing on that state_topic and state_template. I want to be able to send mqtt messages so that HASS will update the state of the device. I thought I could send a MQTT message to topic scenestate/movielighting with a payload of "ON" or "OFF" and that would make HASS think the scene state was ON or OFF accordingly. But when I do that, all I get is an error message:
WARNING (MainThread) [homeassistant.components.mqtt.light.schema_template] Invalid state value received
How can I send a message to make HASS think this device is ON or OFF?
Oh, and that optimistic: true, I have no idea about that. I saw it in the docs and thought I'd try it.
none of your template values are correct
That doesn't surprise me! I'm just starting out and I saw some of this online. The command_on_template and command_off_template seem to be working. I can send messages to turn it on and off. But I want to be able to update the state independently of activating the light.
Hello! I have seen templates beginning with > and >-. What is the difference? I haven't found it in HA documentation.
> is used for multiline templates, - is used to remove line-breaks also inside templates eg: {%- something -%} if you have a short oneliner, just surround it with "" on the same line and don't use the >
Is it not just that?
{% set a = 17.62 %}
{% set b = 243.12 %}
{% set alpha = log(hIndex/100) + a*temp/(b+temp) %}
{% set ts = b * alpha / (a - alpha) %}
{{ts}}
?
ah...lo instead of ln ๐
Quick question: is it possible to use templates for scan_interval? Currently I have the config below, but HA complains about this line.
scan_interval:
minutes: "{% if is_state('device_tracker.blokmeisternas', 'home') %}1{% else %}1440{% endif %}"
Doc doesn't say you can: https://www.home-assistant.io/docs/configuration/platform_options/#scan-interval
scan interval sounds like something in the configuration.yaml. templates there don't seem very usefull
So I guess you can't ๐
๐ฆ
as these are only read at reload to determin HA config
What you could to is to put a very very high scan_interval so that you entity actually never refresh, and manage the refresh of the entity in an automation
That's too bad. I'm monitoring my home server. But sometimes I turn it off for power saving. In that case, HA is throwing lots of errors for all command line (ssh) and rest sensors.
That might actually work.
That's what I did for my solar panel, to not refresh the sensor when the sun is down
๐ from what I read, the higher scan_interval you can set is 315360000
In minutes?
my name might confuse people... it's my gamertag, but I'm a guy ๐
Okay. I have written the automation. Let's see how that works! Thanks again for the suggestion!
end of the stream or a document separator is expected at line 7, column 8:
{% set a = 17.62 %}
and in dev-templates runs succesfully
can you show the whole config, likely you forgot quotes "" or > for multiline?
- platform: template
sensors:
real_feel:
value_template: >
{% set temp = states('sensor.temp_act') | float %}
{% set humid = states('sensor.um_buc') | float %}
{% set a = 17.62 %}
{% set b = 243.12 %}
{% set alpha = log(humid/100) + atemp/(b+temp) %}
{% set ts = b * alpha / (a - alpha) %}
{% set hIndex = -8.78469475556 + 1.61139411temp + 2.33854883889ts - 0.14611605tempts - 0.012308094temptemp - 0.0164248277778tsts + 0.002211732temptempts + 0.00072546temptsts - -0.000003582temptempts*ts %}
{{ (hIndex) | round }}
Error loading /config/configuration.yaml: while scanning for the next token found character '\t' that cannot start any token in "/config/sensors/real_feel.yaml", line 7, column 1
oh....wierd...seems i have a tab space instead of space space
now it says ok
in front of line 7
not sure if this is what you want:
{% set humid = states('sensor.um_buc') | float %}
{% set a = 17.62 %}
{% set b = 243.12 %}
{% set alpha = log(humid/100) + a*temp/(b+temp) %}
{% set ts = b * alpha / (a - alpha) %}
{% set hIndex = -8.78469475556 + 1.61139411*temp + 2.33854883889*ts - 0.14611605*temp*ts - 0.012308094*temp*temp - 0.0164248277778*ts*ts + 0.002211732*temp*temp*ts + 0.00072546*temp*ts*ts - -0.000003582*temp*temp*ts*ts %}
{{ (hIndex) | round }}```
you seem to miss that you need to add * between variables to make them calculate. just writing 1.6temp does give warnings
guess is a copy/paste thing but looks like u wrote . thank you
hi how to get the days of the week ? like now(). to give as Wednesday for example..
just to print out the name of the day only
{{ days[now().weekday()] }}```
never mind made one ๐
{{ as_timestamp(now()) | timestamp_custom('%A') }}
Or {{now().strftime("%A")}}
There can be issues with .strftime which is why I don't recommend it
oh ok, what kind?
well, if you set your system up incorrectly or expect it to work on all datetimes, it won't work because the timezone may or may not be set
in normal python, i'd use the strftime, but you can't ensure a timezone in jinja because you can't create a timezone
it's best to always use the filter
use utcnow + strftime -> strptime with your timezone added
or they could just set up their system properly ๐
You should check out the forums. You'd be surprised at how many installations are set up incorrectly for time. Then getting these people to change it is like pulling teeth because they don't know what they're doing. Way easier to just point them towards the filter.
indeed
Hello, does anybody know how to extract one part of a mqtt topic to forward it to another topic, or make a sensor with one of the values? Let's say I have a topic where I can find the following string: (1.0, 20.0) . I want to send one of the 2 values to another topic, or make an mqtt sensor with one value.
is the one you want always in the same position?
I tried to make an automation with```
- alias: OpenTherm Send
trigger:- platform: mqtt
topic: "HVAC/otresult"
action: - service: mqtt.publish
data:
payload: "{{ trigger.data.split(',')[0] }}"
topic: "opentherm-thermostat/setpoint-temperature/set10"
retain: true
qos: 0
- platform: mqtt
the position is of interest, because the value changes
but yes, position is always the same,
so something ending in .split(',')[0] will be ok
I do not know what to write before this ๐
i wonder if the data is coming back as a tuple? i'm not sure if json supports that though
I am publishing the data
it is something like this: {% set result = (1.0,20.0) %} {{ result }}
and this (1.0, 20.0) can be found in the mqtt topic
i can see it in mqtt explorer
try trigger.data[0]
nope, nothing ๐ฆ
how do i add 2 state_attr together?
this just appends one to the end of the other
state_attr('switch.dehumidifier', 'total_energy_kwh') + state_attr('switch.washing_machine', 'total_energy_kwh')
Yes, adding two strings together does that.
You need to cast them to a number type first.
'1.0' + '2.0' = '1.02.0'
'1.0' | float + '2.0' | float = 3.0
yay string math
hello guys, is it possible to combine two templates somehow? I'd like to control a fan via hassio, its all about calling curl (for which I found a template, called command_line) - also there is a template for fans - can I just merge them?
you can create template entities that use data from two or more existing entities
thanks alot, will try that ๐
{{states.media_player|map(attribute='entity_id')|list|random}} Now to download squeak sounds and drive my dog crazy ๐
@narrow topaz posted a code wall, it is moved here --> https://paste.ubuntu.com/p/RxCqPZYS86/
how to remove the initial 0 in a date by replace ? for example converting 01/18/2021 to 1/18/2021
or is there a way to avoid the 0 from the beginning in this formula ? timestamp_custom("%m/%d/%Y")
solved: .lstrip('0')
possibly timestamp_custom("%-m/%d/%Y") would work too according to python time format documentation
Hello everyone and sorry to come back again with the same issue, but I am still trying to split the info on an mqtt topic. Maybe someone here did not see my request yesterday. I have this: (1.0, 20.0) coming in an mqtt topic. I want to either forward one of the values (they change, position remains the same), or make a sensor out of one of the values. ```
- alias: OpenTherm Send
trigger:- platform: mqtt
topic: "HVAC/otresult"
action: - service: mqtt.publish
data:
payload_template: {{ 'trigger.payload[0]' }}
topic: "opentherm-thermostat/setpoint-temperature/set10"
- platform: mqtt
Coming from a very nice guy, who makes me even more interested in learning c++, :```
- alias: OpenTherm Send
trigger:- platform: mqtt
topic: "HVAC/otresult"
action: - service: mqtt.publish
data:
payload_template: "{{ trigger.payload.split(',')[0][1:] }}"
topic: "opentherm-thermostat/setpoint-temperature/set10"
retain: false
qos: 0
- platform: mqtt
How can I make a template output the number of days in the current month. So like right now it would output 31, but next month it would output 28.
I'm pretty sure I've done it before, but I can't find the docs to remember how to do it.
for context, I'm trying to make a template sensor with my estimated electric bill by effectively doing
( [bill so far] / [day in month] ) * [total days in month]
but I'm open to doing it other ways if there is another better way
{{ (now().replace(month = now().month % 12 +1, day = 1)-timedelta(days=1)).day }}
thank you friend!
that doesn't look the same as I remember it from last time, but if it works it works ๐
Most Python solutions will recommend using the calendar library, which you don't have access to in HA's templates. That's the solution at the bottom of this post: https://stackoverflow.com/questions/4938429/how-do-we-determine-the-number-of-days-for-a-given-month-in-python
makes sense
statistics platform can be used for templating max value of a sensor for a day ?
No need for a template for it, it's just an integration.
well....i have 24 values (one each hour) and i want to now the max of them
then i want to store that value
Where do the values come from? Same sensor or different sensors?
same sensor
But for more help with that... #integrations-archived
I'm trying to get the number of seconds remaining for an active timer. Is there a function for that specifically or do I need to compare "finishes_at" with the current time?
i can't tell from the docs. What are the attributes of the timer when its running?
duration, editable, finishes_at, and remaining.
what's the value of remaining?
It looks like it's deprecated in favor of using the finishes_at attribute
the value is the same as duration, doesn't appear to change
I thought I had an easy with with the "relative_time" method, but it only works with dates in the past
Is it possible to concat a !secret value with text in a template?
Trying to do something like this
- service: notify.all_ios_devices
data_template:
message: 'A {{trigger.payload_json["after"]["label"]}} was detected.'
data:
image: '{{"!secret ha_url"}}/{{trigger.payload_json["after"]["id"]}}/thumbnail.jpg?format=android'
tag: '{{trigger.payload_json["after"]["id"]}}'```
never tried it but i highly doubt that would work.
Well I can confirm it doesn't
makes sense, secrets are only read on boot/once. you're trying to call it after HA has started
You can create a variable that you can use in your template
- action:
- variables:
ha_url_var: !secret ha_url
- service: notify.all_ios_devices
data_template:
message: 'A {{trigger.payload_json["after"]["label"]}} was detected.'
data:
image: '{{ha_url_var}}/{{trigger.payload_json["after"]["id"]}}/thumbnail.jpg?format=android'
tag: '{{trigger.payload_json["after"]["id"]}}'
ah, that's a nice new way to do this, before variables you had to use template sensors for that. I'll have to update some of my config too then ๐
Neat. I'll have to remember that
hmm too bad that doesn't help here:
camera:
- platform: generic
name: iss
still_image_url: 'https://maps.googleapis.com/maps/api/staticmap?key={{states("sensor.google_api_key")}}¢er={{state_attr("sensor.iss", "latitude")}},{{state_attr("sensor.iss", "longitude")}}&zoom=6&size=600x300&maptype=hybrid&markers=color:blue%7Clabel:ISS%7C{{state_attr("sensor.iss", "latitude")}},{{state_attr("sensor.iss", "longitude")}}'
limit_refetch_to_url_change: true
this is a secret: sensor.google_api_key but since this a configuration thing no way to use the variable there
I have to say even though it's configuration, it works very well to get maps of your appointments etc. or in this case the postition of the ISS space station ๐
Hi all! I'm new to HA and I'm trying to create temperature graphs for my rooms. I figured out how I can build a template sensor to extract the temperature attribute from the climate/termostat entity. However some rooms have several termostats and thus several readings. I can't figure out how to aggregate them into one sensor (average?). It seams like it should be straight forward but haven't found any example. Does anyone have any suggestions?
I you want to create a sensor that will have as value the average of other sensors, you can use min/max integration : https://www.home-assistant.io/integrations/min_max/
Ah thanks will try that and see if I can get it to work.
Hello! Is there a way to get a value of a specific mqtt topic in templating, withoutt it being used as a trigger?
I want to make an automation, and do something with the value of an mqtt topic. But the automation will have to be triggered on different triggers, not THAT topic.
You can use wait_for_trigger: https://www.home-assistant.io/docs/scripts/#wait-for-trigger to wait for a message on a topic
So how could I get te value on the mqtt topic intro the payload_template section?
That I don't think you can do with wait_for_trigger
you have to create a sensor on that other topic, so that you can use that value in your automation
Follow up question - is there a way to use attribute value directly in min/max or do I need to create a template for each thermostat to expose current temperature and then use it in min/max?
Ah. Thanks. Yeah - that's what I have now {{climate.guest_room_temperature.attributes.current_temperature}}
{% set temps = [state_attr('sensor.one', 'temperature'), state_attr('sensor.two', 'temperature'), state_attr('sensor.three', 'temperature')] %}
{{ (temps | sum / temps |count) | round(1) }}
Even better - thank you so much!
just pay attention that this simple code doesn't deal correctly with unavailable states
Would you do it like this or create a template for each termo and then use min/max on those? What is the better route?
One small pickle, if anybody knows how to send off from (1.0, 20.0, 'off') using this: payload_template: "{{ trigger.payload.split(',')[1][:-1:] }}" - service: mqtt.publish data: payload_template: "{{ trigger.payload.split(',')[2][:-1] }}" topic: "opentherm-thermostat/mode/set" retain: true qos: 0 first line manages to extract the value 20, but last line will result in 'off' instead of off
Good question. Personnaly I would create one single template sensor, but that's really my opinion
Thanks - I appreciate it. I'm leaning the same way - solves my problem and avoids "chains" that can introduce errors.
You could add a filter | replace("'","") to remove the extra quotes
Hmmm Let me see ๐
Getting some errors.
Looks like it can't take out the 'character
unexpected end of the stream within a single quoted scalar
payload_template: >
{{ trigger.payload.split(',')[2][:-1] | replace("'","") }}
sure ? ๐ on a second line ?
wait
Using > avoid using the quotes around the template a fix therefore your issue
ohhhh thank you thank you thank you ๐
hi! I have my cameras sending motion detected data to nodered and I was wondering if there's something like a "virtual motion sensor" in HA that could receive the current state from nodered
i've found the "template binary sensor" but i'm not sure how to write the current state to it (https://www.home-assistant.io/integrations/binary_sensor.template/)
because it seems like the "value_template" field just accepts values from existing devices
got it! -> entity node in node red (required HACS)
Could CT clamp accuracy be improved by using the line voltage somehow in the template?
I've got an automation triggered by timer.finished. In the action, trigger.event is empty. Am I missing something silly?
Here's my automation, if it helps any: https://paste.ubuntu.com/p/9rnMGqnn8v/
I'm trying to alter a script I found online (https://github.com/basnijholt/home-assistant-config to notify me when my washing machine/dishwasher is done including time and energy usage), but I can't get it to work
You just linked to someone's entire config. Would you like to narrow it down a little so we know what you're actually asking?
I've altered this part:
variables:
switch: "{{ 'switch.{}'.format(name) }}"
to this:
variables:
switch: "{{ 'switch.{}'.'plug_' + name + '_relay_0' }}"
sorry mono, was still anwsering ๐ Yes, hold on
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.
So you're changing line 13? What's the problem?
The original script uses the name variable and I think it matches exactly in the authors code, but in my case I need to change it to match, but that doesn't work it seems
setting up the variable switch: "{{ 'switch.{}'.'plug_' + name + '_relay_0' }}" give an error when reloading my code
(TemplateSyntaxError: expected name or number) for dictionary value @ data['variables']['switch']. Got None. (See /config/configuration.yaml, line 15).
Ok. Your template is invalid. If works for them because the .format function does a substitution of {}
Figured as much, I can't find any documentation on this format function. Is this Python? Or some custom Home assistant stuff?
It looks like you want something more like this:
{{ 'switch.plug_{}_relay_0'.format(name) }}
Aha, so format() puts the name instead of the {}'s?
.format is Python, yes. Templates are a mix of Jinja2 and native Python, with a few things turned off for safety.
Thanks, makes it easier to search myself
If you want to test something that uses variables, you can do stuff like this in Dev Tools > Templates:
"temperature": 25,
"unit": "ยฐC"
} %}
The temperature is {{ my_test_json.temperature }} {{ my_test_json.unit }}.```
I have some experience in programming, but mostly Javascript/PHP so Python is a little awkward for me still
set lets you assign something so you can test the variable in a subsequent template.
Yes, Dev tools is a great resource to quickly test stuff out
Was already working in it to test
or {{ 'The temperature is {}{}'.format(my_test_json.temperature, my_test_json.unit) }}
Great, I'll try the use the format() function and see how it works
useful for constructing strings from multiple vars
Well, yes... my example is an old one that's just parked in my Dev Tools from months ago ๐
Before I learned more about templates ๐
haha
No, wait... it's lost my stuff ๐ฎ
i've been learning ya
That's a native example... ๐ฎ
browser cache reset?
Kinda. Just realised what it was... I pointed a subdomain of my personal domain at my home server. The cached versions I'm used to are from when I was using DuckDNS... ๐
Copying them across now ๐
lol
But yeah, good to know they're just cached by the browser. I did wonder what the mechanism was.
yup, i hop across machines often enough that i have different things in all of them
almost none of it for stuff i actually use ๐
I don't use any of the stuff lying around in my Dev Tools, which is kinda the point. Stuff I care about is in config already... this is a playground and where I keep examples for quick access to share with people.
I should probably save them somewhere just in case.
lol i just re-create things
Hello, how to match time from the trigger or something similar
I have two triggers, and I want to set my input_boolean to true if '00:30:00' and to false if '07:30:00'
or maybe to create two helpers time and set those timings
{{ now().hour == 0 and now().minute == 30 }}
Change the numbers as needed.
But since you didn't say what you want to happen at 00:31:00, 00:32:00, 00:33:00, etc, I don't know if that's what you're after ๐
I will check it tnx..well, I want just to set my input boolean at specific time
so if my boolean goes to true at '00:30:00' it should stay in true status until the morning at '07:30:00' when its setting it to false and so on
Well that depends on your triggers too, which are #automations-archived territory.
I gave you an example of a template you can use for your condition.
I think I got it..I will test it ๐
Sorry to bother again. I'm continuing on the script but I'm stuck on a wait_for_trigger, see this script (https://paste.ubuntu.com/p/j8qv878Xwj/), it fails on line 22
hey everybody! Any idea why this doesn't add up?
{{ states('sensor.watt_panelovn_stue_a') + states('sensor.watt_panelovn_stue_b') }}
{{ binary_sensor }}
binary_sensor isn't defined there ๐
Because states are strings.
String math ๐
Milenco - to debug stuff like that, you should send a persistent notification with the variable name, then you'll see what its current value is (if it has one).
Hmm, not sure how to do that..Just noticed that I made some other mistakes as well, will take a few more hours I guess..
Hi, if i use a template in a variable and use that variable in a loop inside a script, will the value of the variable be updated if it changes? or will the variable only be set at the beginning of the script?
Hey Everybody im triyng to get a temparute offset to work but no template sensor is showing in my entity list ๐ i already created a topic in the forum but iยดm a bit impatient. tought maybe some of you could help me out ๐
.share your config
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.
Me or Sam
Sam asked a general question. You said you have a problem with your config.
Ah didnt noticed was busy with the pastebin :D. configuration.yaml: https://paste.ubuntu.com/p/k5tVZRCTgS/ sensors.yaml: https://paste.ubuntu.com/p/zxvp2YMdGC/
It looks okay. What does the command line config checker say?
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
good question how do i check that learning everyday something new
nevermind think figured it out waiting for the result
oh no did the core check i post if i got any news
so did the check it says: Successful config (partial) octoprint
No complaints about the template sensor then? Have you restarted HA since you added the config?
yeah did via the server menu in the gui maybe a hard reset will solve the problem?
A 'hard reset'? You should never reboot the host. Just use the restart button.
i meant just pulling the cord dont know the term in linux language ๐
bit yeah you right doing a restart the right way
ohhh yeah thanks mono
the command line ha core restart did the trick i dont know if the restart button in the gui did not work but now iยดm seeing my sensor
i just saw it becuase you gave me the tip with the command line checker ๐
variables wont update
I want to set a trigger to fire eg. 30 minutes before my alarm clock is set input_datetime.alarmtid, but I cannot get this right:
{{ ((now().strftime("%s") | int - 1800) | timestamp_custom("%H:%M")) == states.input_datetime.alarmtid.state }}
I suspect I am doing something dumb here, trying to pull an item from a weather provider forecast.
{% set weather_provider= "weather.kgrr_daynight" %}
{% set forecast_index= "0" %}
{% set forecast_attribute= "detailed_description" %}
Not working: {{state_attr(weather_provider, "forecast")[forecast_index|int].forecast_attribute}}
working: {{state_attr(weather_provider, "forecast")[forecast_index|int].detailed_description}}
don't you have to concat weatehr provider?
not sure i follow that one
and quote it
weather_provider is a var
no idea about those attributes
but trying to do the same as a key for a dict... doesn't. at least not the way i'm trying to do it up there ๐
you can't dotwalk with a variable. it'll just try to find an attribute with that name instead
{{state_attr(weather_provider, "forecast")[forecast_index|int].get(forest_attribute) }}
BOOM that was exactly it. i've never heard of dotwalk, so now i have some googling to do. thank you @dreamy sinew for helping me and giving me something new to learn. i really appreciate it!
ah that's the python part of templating
and now HASP has a blueprint to show weather forecasts ๐
yeah you're touching a dict() so all of the dict functions are available there
i'm trying really hard not to make a joke about touching dict()s
"dot-walking" is a thing that JS and jinja let you do. its kinda odd.
Given this dict:
d = {"foo": {"bar": "blah"}}
you can get to "blah" by using:
{{ d.foo.bar }}
but it doesn't work in some cases. You can't use it with a variable as you noticed and you can't use it if the key you want to use has a space in it
I am using a template sensor to pull out an attribute of a climate entity that captures what equipment (heat, fan, etc) is running. When no equipment is running the climate's equipment running attribute exists but has no value and template sensor has a value of *unknown *instead of *none *like I'd like. My various template attempts work fine in devtools but not as config.
- platform: template
sensors:
hvac_equipment:
friendly_name: 'hvac equipment'
value_template: >-
{% if state_attr('climate.living_room', 'equipment_running') %}
{{ state_attr('climate.living_room', 'equipment_running') }}
{% else %}
None
{% endif %}
I've tried the states.entity.attirbutes.attribute_name method, ive tried if.., and "if... defined", is_state_attr looking for '', and others. Nothing that I try that works in dev tools templates works in the actual config. I've googled and searched here a good bit and I'm out of ideas
None is a special word
ok let me try something
Also it's probably in state unknown so just check for that
dev tool states has it has nothing after the name just equipment_running:
trying something other than none now
ha! <template TemplateState(<state sensor.hvac_equipment=something; friendly_name=hvac equipment @ 2021-01-29T22:23:35.561688-05:00>)>
and as soon as you said that, i recall someone saying that a few weeks ago
thank you!
I want to make an if statement for a sensor, this because one of my sensors becomes negative, but if the value is negative it must be 0. I found this:
{% if states.sensor.measured_current_spa_heating.state < '0' %}
But i dont know how to go further?
You can use logic like this to ensure you always return zero or higher:
{{ [-10, 0] | max }}
The -10 is just an example, you'd put your sensor state there.
I want to use an input_number in place of the '3' in a service call like this:
service: climate.set_fan_mode
data:
fan_mode: '3'
entity_id: climate.hvac_office
it seems like I can just replace the '3' with a template but I'm not sure that's right
Have you tried it?
oh.. shit.. I just remembered I can trigger an automation!
well now I'm just confused.. something happened that I don't understand.. I'm going to guess that my template was wrong because rather than switching to 2 which is what it was set to it switched to AUTO.. So I'm guessing maybe it has to be converted to a string first
or maybe the other way around.. I can't remember how it works..
fan_mode: '{{ states(''input_number.office_aircon_boost_level'') }}'
is what I tried
no... string IS the default... can't possible be a number as AUTO and QUIET are not numbers... so.. I don't know..
I tried
fan_mode: '{{ states('input_number.office_aircon_boost_level') }}'
that works in the template editor (to get the number).. but it still doesn't work in the automation.. and is apparently not valid
for now I'll just continue editing the automation about 6 times a day to change the number until I can figure out if this is possible to do
You have to cast the state in float before comparison
| float. And use states() function instead of states. ...
any idea if i can make this work ?
mode: parallel
fields:
service:
description: 'the service to run'
example: 'light.turn_on'
data:
description: 'the data to pass to the service'
exemple: '{"entity_id": "light.thatlight", "effect": "blink"}'
sequence:
- service_template: "{{ service }}"
data_template: "{{ data|to_json }}"```
What do I need to write to have a template that sends me a message in the official android app, to turn off the ventilation when all humidity sensors report a value <=60.0, and s message to turn it on when any sensors reads >=60.1 ?
2 trigger with state number above or below your value
a choose block in the sequence that send the notif with a diferent text based on the said value, then you wait for the event on the button click and add another choose based on the reply
Could you show me a mock-up of what the code would look like?
I don't know the syntax
I use utility_meter to calculate monthly consumption price. Is there way to "save" monthly price and have chart of those values ?
Jan - $x
Feb - $x
Mar - $x
....
Is there a way to dynamically populate an input_select? I would like to build some front end in HA to OTA update my z2m lights. Lights with updates available publish update_available: true, so it would be nice to dynamically populate an input_select with all lights with an update available. I can then trigger the update command once I selected a lamp from the list.
Dynamically updating? Sounds like you want #automations-archived
Did't really think about it like that, brilliant! ๐
as much as i try i can't get this to work
mode: parallel
fields:
service:
description: 'the service to run'
# example: 'light.turn_on'
data:
description: 'the data to pass to the service'
# exemple: ''
sequence:
- service_template: '{{ service }}'
data_template: '{{ data|to_json|d({}) }}'```
I feel like it should now that template can return other thing than string...
how do you call the script, as this is only showing the definition, calling it determines what's data is going into service and data. Also I wonder if this might be because these names might be reserved. Also do you get errors ?
right no i don't call the script since i can't reload them
: expected dict for dictionary value @ data['sequence'][0]['data_template']. Got None. (See /home/homeassistant/.homeassistant/config
uration.yaml, line 218)```
i need to make a warper in order for other script to call service that may failed, without failing themself.
So i though i could make a generic one, with data_template being a json map given as a parameter
warper_service_nofail:
mode: parallel
fields:
service:
description: 'the service to run'
# example: 'light.turn_on'
data:
description: 'the data to pass to the service'
# exemple: ''
sequence:
- service_template: '{{ service }}'
data_template: '{{ data|to_json|d({}) }}'
I think it's identation ๐
wut ? you mean the '-'
after sequence you need to ident the rest 1 step deeper
this is how the UI save them in the script file, but i can try moving the all sequence block one space :)
nop, no luck
janv. 31 11:33:15 ap-univm-016 hass[23150]: 2021-01-31 11:33:15 ERROR (MainThread) [homeassistant.config] Invalid config for [script]: expected dict for dictionary value @ data['sequence'][0]['data_template']. Got None. (See /home/homeassistant/.homeassistant/configuration.yaml, line 218).
But to note, the UI say that the config is valid when i check, on the log say otherwise
i have also tried - service_template: '{{ service }}' data_template: '{{ data|d({"message": "empty"})|to_json}}' just to make sure it wasn't because it was empty
data is usually a list of things:
data:
something: value
something2: value2
so not a single string
yea i know, that's why i wish to send it a map.
It wasn't possible before the rework of template because template where always string.
But now template can return anything, map, int, array...
so this should work, no ?
yeah it should... I'm messing with it in
-> template
it work well in template, but that sadly not what happend :(
Maybe it's simply not possible based on how data_template is rendred.
i am working on a pythonscript alternative for now... i hop i won't need it but at least i'll have something :)
tankyou for trying
i've made this python script as a workaround ```nofail_service = data.get('service')
nofail_data = data.get('data')
try:
hass.services.call(nofail_service.split('.')[0], nofail_service.split('.')[1], nofail_data, False)
except Exception as error:
logger.warning('error occured in a nofail call: {}'.format(error))```
I have a template that I have used for a long time that now shows an error. I can't see the issue ```
platform: template
sensors:
ha_uptodate:
friendly_name_template: >
{{states('sensor.ha_local_version')}}
value_template: >
{{state_attr('sensor.supervisor_updates','newest_version') == state_attr('sensor.supervisor_updates','current_version')}}
icon_template: >
{{ 'mdi:circle-outline' if states('sensor.supervisor_updates','newest_version') !=
states('sensor.supervisor_updates','current_version') else 'mdi:check-circle-outline' }}
unit_of_measurement: Up to date``` TypeError: __call__() takes 2 positional arguments but 3 were given
without diging at all, i see Up to date, witch is 3 word ... maybe quote this ?
Thanks, Tried it in developers tool and same error
more of the error message 'Template("{{ 'mdi:circle-outline' if states('sensor.supervisor_updates','newest_version') != states('sensor.supervisor_updates','current_version') else 'mdi:check-circle-outline' }}")' for attribute '_icon' in entity 'sensor.ha_uptodate'
and states() can only have one attribute.. doh!
i have stuff to do, hop this fixed it bschatzow ๐
Do what you need. Thanks. I changed the states in the two places to states_attr and now in developer template I get UndefinedError: 'states_attr' is undefined
state_attr not states_attr
Thanks
It works now. Not sure why it worked with no errors for over 6 months until today
I'm trying to convert from C to F, and round, and for some reason it isn't rounding {{ states('sensor.ble_temperature_a4c13807de90')|float*9/5+32|round(1)}}
{{ states('sensor.ble_temperature_a4c13807de90')|float*9/5+32|round(1)}}
am I chaining wrong?
also similarly, why does {{ 10|float+1|float*2 }} return 12, does it work backwards?
{{ (states('sensor.ble_temperature_a4c13807de90')|float*9/5+32)|round(1)}} works
I get it now, math operations aren't filters
I am struggling to figure out a way to cycle through a list and find next/previous items in the list. Anyone have any pointers? cycler is almost what I want but still not really.
For example, say I have a list {% set compare_list = [2,8,6,4,5] %}
and a current value: {% set compare_value = 6 %}
what i'd like is some way have a previous_value == 8 and a next_value == 4
The trick is that I want to loop/cycle/modulo/etc this list. So, if compare_value = 5 then previous_value == 4 and next_value == 2
finally, there's an off chance that compare_value is not in the list at all and I would need to do something intelligent in response. kinda doesn't matter that that actually is, so long as previous_value and next_value return some valid item from that list (maybe elements 0 and 1? or the first and last? open to most anything there)
think i have a workable solution. if anyone looks at this and thinks MAN LUMA YOU ARE DOIN IT WRONG MY FRIEND please let me know ๐
{% set page_current = 2 %}
{% set page_list = [2,8,6,4,5] %}
{% set page = namespace() %}
{% set page.previous = page_list[(page_list|length)-1] %}
{% set page.next = page_list[0] %}
{% for item in page_list %}
{% if item == page_current %}
{% if not loop.first %}{% set page.previous = loop.previtem %}{% endif %}
{% if not loop.last %}{% set page.next = loop.nextitem %}{% endif %}
{% endif %}
{% endfor %}
Page = {{ page_current }}
Previous page = {{page.previous}}
Next page = {{page.next}}
if page_current is outside of the list, previous will be the last element, and next will be the first element, and that seems pretty reasonable
HI, I have the following in configuration but when I check configuration validation before restart the check seems never stops. If I comment the lines out.. all is oK
- platform: template
sensors:
total_power_shelly_em:
friendly_name: "ShellyEM Total Power"
unit_of_measurment: 'Watts'
value_template: "{{ states('sensor.shellyem_b03059_channel_1_power')|int + states('sensor.shellyem_b03059_channel_2_power')}}"
Waht am I doing wron here? Thanks
Your template is invalid. Test it in Dev Tools > Templates
And don't rely on the UI config check:
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
Thank you. Its states "unsupported operand type(s) for +: 'int' and 'str'"
I want to add the 2 figures together.
Yes... can you see why it's an int and a str?
Bingo
Always be learning
I have now corrected and checked it developer tools template and it returns the expected result. But when I paste it from there into config I'm getting the same loop when checking config before a restart... hmmm
Use the command line version of the check. Follow the link in the bot message.
mono thanks for your help. After trying all sorts of things. I found that if I commented out the unit_of_measurment: 'Watts' it passed.
My template sensor doesn't like a unit of measurement
Hello, I have this template -
value_template: '{% if trigger.payload_json.command is defined -%}True{%- else -%}False{%- endif %}'Can you tell me how to add an 'and' condition to the 'if' such that 'command' is defined and its value == "White" ? Thanks
those get funky
because if it isn't defined and you try to check the state it'll throw a value error
thanks... can i just stack the conditions so that if it is defined then it checks on value ?
{{ True if trigger.payload_json.get('command', None) == 'White' else False }} might work
@dreamy sinew cheers, ill try it
Thanks! .. ill test it a bit more to be sure but looks good !
Good morning all. I wanted to make a template with the full date of tomorrow. I already made something but found out yesterday that it returned 32 januari instread of 1 febrauri ๐
https://paste.ubuntu.com/p/nGSMXFQXNR/
Do I need check on over 30/31 , i.e. add more if statements. Or are there any nicer ways?
{%set tomorrow = now() + timedelta(days=1) %}
{{ days[tomorrow.weekday()] + ' ' + (tomorrow.day) | string + ' ' + months[tomorrow.month-1] }}
Thx will give it a shot Slash !
Graag gedaan
(fyi using tild avoid the casting in string {{ days[tomorrow.weekday()] ~ ' ' ~ tomorrow.day ~ ' ' ~ months[tomorrow.month-1] }})
Mooie toevoeging ! / Nice to add !
hi how would i go about writing a template to simulate the numeric state trigger using the below and for options?
but using input_number helpers for the values
You don't. You'll likely have to use a template trigger to set/unset an input boolean when it dips below/above and another template trigger to see how long it's been on.
can i use input helpers in a threshold binary sensor?
ok they way i thought it would work it dident so im not sure it is possible
this is what i have:
binary_sensor:
- platform: threshold
entity_id: sensor.bedroom_temp
lower: "{{states('input_number.ac_off_temp')}}"
upper: "{{states('input_number.ac_on_temp')}}"
hysteresis: 0.0
name: Bedroom Temp Threshold
i also tried lower: {{states('input_number.ac_off_temp')}} and lower: input_number.ac_off_temp
https://www.home-assistant.io/integrations/threshold/#upper
upper float (optional)
Doesn't say they take templates
ok i wanted template binary sensor not threshold
Hey all. I'm slightly confused around the use of is_state. I have 2 sensors which currently hold my e-mail address and when I use something like is_state('sensor.email_sensor_1', 'myemail@test.com') it becomes True, but if I use is_state('sensor.email_sensor_1', 'sensor.email_sensor_2') it becomes False. I have ensured that the state of both sensors indeed contains the exact same e-mail address. Is this not the way to compare 2 sensor values? or am I missing something else?
because that is checking if the first sensor has the state that matches the string you give
since that'll never equal sensor.email_sensor_2 it'll never work
not even if the second sensor contains a string value? It will only compare against an actual, hard coded, string?
but you can do {{ is_state('sensor.email_sensor_1', states('sensor.email_sensor_2')) }}
that's what you're telling it to do
you are giving it a hard coded string value to check against
if you want a var, you gotta give it the var
aaahhh cool! Checked it in the developer tools and it works!
Because it was "automagically" grabbing the state of the first sensor, I expected the same to happen if I passed a sensor in as the second parameter.
Thanks a lot ๐
np
def is_state(hass: HomeAssistantType, entity_id: str, state: State) -> bool:```
ignore the first input but this is how its working
takes an entity id and compares against a state
Nice. I'll have to practice my Python a bit more ;P
jinja syntax is "pythonish"
you see more of the python when you're dealing with objects but its an odd mix sometimes
@fleet wyvern let's chat here so we don't pollute the other thread
what's the state of your input number?
thanks a lot
sorry, i just saw what marcel wrote and i thought it was related
input_number.trv_living 255.0 initial: null
editable: true
min: 0
max: 255
step: 1
mode: slider
friendly_name: TRV living
same error
and you are casting it to int right?
this is the service call i am trying from developer tools
oh... are you using data_template as a key instead of data?
no i am not
try data_template
like this?
data_template:
entity_id: light.trv_living_dimmer
brightness: {{ states('input_number.trv_living') | int }}
I checked the code, you shouldn't need to cast it, the service will convert it for you
ah you are calling it from dev tools
yes
It doesn't ๐
aha, ok, i will try it in automations then
๐
thank you, i was using dev tools as a quick way to test actions without annoying the wife
it's either you or your wife, you gotta pick one ๐
better me of course :)) happy wife, happy life...
fair
@night imp posted a code wall, it is moved here --> https://paste.ubuntu.com/p/6xGhC4R5PC/
...ugh it's not a fkng codewall it was 8 lines. I hate hassbot
16 lines... and watch your attitude.
@night imp 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.
For sharing code or logs use https://paste.ubuntu.com/.
Hi Mono.... so it was exactly at the bare minimum. I don't have attitude towards anybody, I was frustrated by hassbot
It doesn't matter if it's 'at the bare minimum'. Rules are rules. If you're unclear about any of them, go re-read #rules
awesome thank you so much for keeping me on track ๐
Let me rephrase.
Hi everybody, hope your day is going well ๐
I'm trying to implement kasa smart strip and get a lovelace card based on attributes in one of the plugs. However I don't know how. I'm looking at template sensors and I don't quite understand a few things. How do I know what to tab and why and what needs hyphens prior? Is this yaml specific or HA specific? an example (made sure to pastebin this time to make things easier for everybody ๐ ) https://pastebin.com/42mk7H1n
@ivory delta is it 16 lines in discord or just /n returns? what's counted? I don't want to go over again if I keep typing. I'd imagine on crt monitors you get less space and more lines. Should I wait for another post first or can I add?
@night imp Generally, don't tag people to ask for help - it comes across as bad manners, youโre demanding somebody answers you. Itโs different if youโre thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.
Similarly, please donโt DM (direct message) people asking for help. It also comes across as demanding, and means that others canโt learn from what you do.
Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).
You're on a roll today.
I'm not tagging for help, it was asking you to clarify.
And no, don't keep adding to posts. That would still come under spam, since flooding is listed in the rules ๐
I don't care what you're tagging me for. It's annoying being tagged.
And it will cause people to block you... like this.
I'm just asking for help and clarification. Dude I'm literally trying to be nice and ask about the rules
Should I use reply instead or just type only and hope you see it?
I'd imagine I can't just put text in one of these channels and guarantee to get a reply from a member of staff
There are no staff...
That explains why my drinks are taking so long to arrive.
Well, it doesn't help I gave the delivery to a geordie staggering on by
That doesn't narrow it down much. They all stagger.
Hello,
I'm looking for an example to make a sensor to get the number of minutes between midnight (00:00) and an input_datetime (time)
Any ideas?
lol you know what I meant. Somebody who can directly speak on behalf of the discord
I think if you search "custom countdown component" I found a few examples that might help. Check on community forums
No, it's not that. I need to get the number of minutes elapsed since the beginning of the day and a specific input_datetime (time)
Yeah I understand, I was just saying you can swap some things out, such as instead of date time now, you can setup *from midnight.
While there may be something that fits you perfectly, there's not always a perfect match. There are lots of scripts and such out there that are close enough you just need to slightly adjust some things
midnight or other input-datetime set to 00:00:
{{ (state_attr('input_datetime.ac_start_1', 'timestamp') / 60)|int }}
Iโd make sure you always watch the data types carefully. What they are and whatโs needed. If thatโs a time stamp, it has a specific format, can it be divided by 60? Imagine itโs 1:00:59. Which it wonโt be that pretty Iโm sure. I think itโs output is a string and it wonโt be divisible by 60. Somebody with more experience can probably drop in on that, but likely.
easiest way to find out is to test that in
-> Template. That gives what type it is too, at least when you just have 1 thing in there.
is it possible to use a template with an if to set the value of a text helper?
the specific template is this:
{% if states('fan.bedroom_fan') == 'on' %}
{{ state_attr('fan.bedroom_fan', 'speed') }}
{% else %}
off
{% endif %}
yeah should be valid
Hi, I'm looking for a way to modify this tamplate in order to also show days:
value_template: "{{ states('sensor.time_remaining') | int | timestamp_custom('%H:%M:%S', 0) }}"
Currently it ignores the "day" part so if it's 25h it will just show 1h. Although nice, I don't need it to show 1d 1h... just 25h would be good enough. Any tips?
to have the number if days, just add %d in your timestamp_custom
i must be formatiiong it wrong then. this wont save:
service: input_text.set_value
data: >-
{% if states('fan.bedroom_fan') == 'on' %} {{ state_attr('fan.bedroom_fan', 'speed') }} {% else %} off {% endif %}
entity_id: input_text.fan_mode
this is the error Message malformed: expected dict for dictionary value @ data['sequence'][0]['data']
that just seems to display the current day ๐
Apparently you may have to remove (60*60*24) from your sensor
Correct tom:
service: input_text.set_value
data:
value: >-
{% if states('fan.bedroom_fan') == 'on' %} {{ state_attr('fan.bedroom_fan', 'speed') }} {% else %} off {% endif %}
entity_id: input_text.fan_mode
see https://www.home-assistant.io/integrations/input_text/ you set a value, not the data
ah thanks
i know it would be something like that
so my sensor looks like this :
unit_of_measurement: s friendly_name: OctoPrint Time Remaining icon: 'mdi:clock-end'
I use something like this for forcing a date into HH:MM:SS, where the HH can go beyond 23. You should be able to adjust it to mod 24 the hours and show days too:
{%- set map = {
'Hour': (seconds / 3600),
'Minute': (seconds / 60) % 60,
'Second': (seconds % 60) } -%}
{% if seconds <= 0 %}Idle{% else %}
{% for item in map if map[item] | int > 0 -%}
{%- if loop.first %}{% else %}, {% endif -%}
{{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
{%- endfor %}
{% endif %}```
That is, if you can't get strftime working for you.
thanks, I found something similar on the community forum. Seems to be working now after some tweaks.
lengthier piece of code, but gets the job done
@gritty ice posted a code wall, it is moved here --> https://paste.ubuntu.com/p/PYPGdFk6SF/
hello, Im having a script which has some input fields such as speaker. The script is works fine - for particular speaker and message I play tts notification
but I want to pass multiple entities
such as {{ media_player.room1, media_player.room2 }}
is it doable through fields?
because:
{% set speaker = "media_player.bathroom_ceiling_speaker" %}
{{ speaker | join(', ') }}
results in:
Result type: string
m, e, d, i, a, _, p, l, a, y, e, r, ., b, a, t, h, r, o, o, m, _, c, e, i, l, i, n, g, _, s, p, e, a, k, e, r
you can verify that yourself in
-> template
yes, I've just found that retrieves like that
but better approach I think would be
{{speaker.split(', ')}}
but when I add that into my script, Im getting error
voluptuous.error.MultipleInvalid: Entity ID m is an invalid entity id for dictionary value @ data['snapshot_entities']
I have no idea what your input looks like but this works just fine:
{{ speakers.split(',') }}```
Output: `['media_player.speaker_one', 'media_player.speaker_two']`
As long as snapshot_entities is a list, it'll work.
hmm..still I have an error
Set notification speaker: Error executing script. Invalid data for call_service at pos 2: not a valid value for dictionary value @ data['entity_id']
this is how I call the script entity_id: script.play_notification variables: speaker: "media_player.bathroom_ceiling_speaker" source: "Primary Chromecast" volume: "0.4" custom_message: "Welcome to the bathroom."
or
variables:
speaker: "media_player.bathroom_ceiling_speaker,media_player.hallway_ceiling_speaker, "
source: "Primary Chromecast"
volume: "0.4"
custom_message: "Welcome to the bathroom."```
So which bit is wrong? I don't know which entity_id line you're talking about.
Your script uses entity_id at least 3 times.
hm neither than I ๐
I have play_notification script
which is doing some math and calls another script
set_speaker.yaml
You can find both my script on the link above
so, I get it that in first (main) script I do split function and then I get an array of my speakers and thats seems quite ok, but when I try to proceed to my set_speaker.yaml with variable {{speaker.split(',')}}
in that moment, something goes wrong in the second script
Error during template condition: AttributeError: 'Wrapper' object has no attribute 'lower' this is the error now
when I tested with persistent notification I got just like media_player.bathroom_ceiling_speaker media_player.hallway_ceiling_speaker
@sonic nimbus posted a code wall, it is moved here --> https://paste.ubuntu.com/p/dSqyRyD9sP/
and I tried just to pass through that speaker template entity but it doesnt work
@shy yoke posted a code wall, it is moved here --> https://paste.ubuntu.com/p/QWmHxKDQ7W/
Heya! ๐ I am pretty new to Home Assistant, so please excuse my ignorance about how the scripting works. I am trying to write a script that uses the android tv adb command runner to poll the TV about it's active HDMI port. What I need from it is basically the return value and do something with it (i.E. change color of lights etc.) I couldn't quite find how to handle the return of the adb command yet, however. This is what I have so far: https://pastebin.com/3Hkjf8F7
Hi, is it possible to expand this template code so that the status change is executed only if the value is below the defined voltage for a specific time (f.e. 30 secondes)?
https://paste.ubuntu.com/p/Mx3tfGr3xr/
same functionallity as possible in automations (for:)
how to extract entity names from list and pass them on service?
Hi guys, I'm trying to get power consumption from few devices. The problem is that I cannot extract consumption from Samsung AC. When I'm trying to get it with:
{{ ((states.sensor.shelly_shsw_pm_e09806a9eefc_current_consumption.state | float) +
(states.sensor.shelly_shsw_pm_f4cfa2e3ab20_current_consumption.state | float) +
(states.sensor.shelly_shdm_2_8caab5557cd2_current_consumption.state | float) +
(states.sensor.shelly_shdm_2_f4cfa2e113c2_current_consumption.state | float) +
(state_attr('climate.klimatyzator_biurowy', 'power_consumption_power') | float)) | round(0) }}
It works but only in Dev Tools -> Templates.
When I paste above code into configuration file, editor shows a message:
bad indentation of a mapping entry at line 10, column 24:
(state_attr('climate.klimatyzator_biurowy', ' ...
^
What am I doing wrong?
show the sensor config
sensor:
- platform: template
sensors:
total_power_usage:
value_template: '{{ ((states.sensor.shelly_shsw_pm_e09806a9eefc_current_consumption.state | float) +
(states.sensor.shelly_shsw_pm_f4cfa2e3ab20_current_consumption.state | float) +
(states.sensor.shelly_shdm_2_8caab5557cd2_current_consumption.state | float) +
(states.sensor.shelly_shdm_2_f4cfa2e113c2_current_consumption.state | float) +
(state_attr('climate.klimatyzator_biurowy', 'power_consumption_power') | float)) | round(0) }}'
maybe its because of '
I will replace them with double "
try + "(state_attr('climate.xxxx ....floate))"
You can't do multi line that way (and you are using single quotes within single quotes, which won't work):
- platform: template
sensors:
total_power_usage:
value_template: >
{{ ((states.sensor.shelly_shsw_pm_e09806a9eefc_current_consumption.state | float) +
(states.sensor.shelly_shsw_pm_f4cfa2e3ab20_current_consumption.state | float) +
(states.sensor.shelly_shdm_2_8caab5557cd2_current_consumption.state | float) +
(states.sensor.shelly_shdm_2_f4cfa2e113c2_current_consumption.state | float) +
(state_attr('climate.klimatyzator_biurowy', 'power_consumption_power') | float)) | round(0) }}
Or :
- platform: template
sensors:
total_power_usage:
value_template: >
{{ [states('sensor.shelly_shsw_pm_e09806a9eefc_current_consumption'),
states('sensor.shelly_shsw_pm_f4cfa2e3ab20_current_consumption'),
states('sensor.shelly_shdm_2_8caab5557cd2_current_consumption'),
states('sensor.shelly_shdm_2_f4cfa2e113c2_current_consumption'),
state_attr('climate.klimatyzator_biurowy', 'power_consumption_power')] | map("float") | sum | round(0) }}
just to know, why does some users have to post their code in "paste.ubuntu.com" and some not?
All users have to if it's over 15 lines ๐
ok, thank you ๐, I have to confess that I read this over in rules-an-welcome..๐ฌ ๐
is there a special way to send integers to a shell_command? I have two variables in the command, {{ device }} and {{ hex }}. {{ hex }} is a string and works, but device is an integer and doesn't work
(the command fails)
i've tried debugging but it never shows the rendered command, it shows it with the {{ placeholders }} so i can't tell what it's sending ๐
The command fails how?
Don't just say something is broken, say how it's broken. Then hopefully someone can answer the why.
sorry, that was bad of me:
Error running command: `ssh -o StrictHostKeyChecking=no pi@192.168.86.28 -i /config/ssh/pizero luxafor-python/luxafor-linux.py -d {{ device }} color -x \"#{{ color }}\"`, return code: 1
NoneType: None
If you suspect it's a problem with data types... what happens if you SSH into that Pi yourself and run the command manually with the arguments you're expecting it to pass?
oh it works fine. and if i hard code the values into the shell command config, also works fine
it's when i have a script that calls the shell command it seems to break
The fact that it's templated shouldn't matter at all. You could try sticking some logging in that Python script and see what it's receiving.
ok, will do
does shell_command: allow data_template:?
i'm wondering if it did, i'd be able to see the real values instead of the variable placeholders in the logs
new question. in the following context, what is the syntax for substituting the _1_ digit with an incoming data variable {{ device }}?
- service: script.luxafor_color
data:
hex: {%- set h = states('input_number.luxafor_1_color_h')|float / 60 %}
not sure how {{ }} reacts within {% %}
i am passing {{ device }} to the script hosting this service call
not that, h
it needs to be used 3 more times in the code body for hex
@deft timber thanks
got it
oh yeah h is used a bunch. i truncated the inline ncode
.share the full thing.
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.
every time i do, and edit with the UI later...
So don't use the UI if you're doing advanced stuff. UI's are for newbies.
I'll be honest... I'm not even going to try to read that mess.
i will have to separate this script to a separate YAML file then. i use the UI for certain things on the fly with my phone
the point is, inside that inline code, i want to use variables being sent to this script
{%- set h = states('input_number.luxafor_{{ device }}_color_h')|float / 60 %}?
Setting and re-using variables is fine. I just don't know what else is wrong with your template.
Why Im getting an error for simple check
Send Announcment to speakers: Error executing script. Invalid data for call_service at pos 1: Entity ID is an invalid entity id for dictionary value @ data['snapshot_entities']
- service: script.luxafor_color
data:
{%- set entityName = 'input_number.luxafor_' + device + '_color_h' -%}
{%- set h = states(entityName) | float / 60 %}
hex: {{ h }}
``` does this work
hmm. i'll try
What value do you have in your input_text?
check your template in dev tools if you haven't yet
This worked: {%- set h = states('input_number.luxafor_' + device|string + '_color_h')|float %}
If you want to cut a few more characters, this might work:
{%- set h = states('input_number.luxafor_'~device~'_color_h')|float %}
Unless I've borked the syntax.
neat!
hey, today i have unexpected restart, and after this ui cannot turn on my light over mqtt. I thinks that because i cannot set colour, i can onlly set brightness. This is my template: https://pastebin.com/2bH1c1q2
But now i clink to turn on lights, and it works, but with errors: https://pastebin.com/KsxSJaej
I'd be surprised if that ever worked as intended. You're saying that the state of the light is whatever is in value_json['20'] if that exists, and the state of the light otherwise? That's bound to break.
qq for here. I am moving over to zwavejs2mqtt and as a result the way that my motion sensor alarm levels are now reported changed a little bit. Instead of a sensor with a state its now a sensor with an attribute
So I'm working on it and so far I've come up with - platform: template sensors: living_room_motion: value_template: '{% if state_attr('sensor.living_room_burglar', value) %} {% if state_attr('sensor.living_room_burglar.attributes', value, "8") %} active {% else %} inactive {% endif %} {% else %} n/a {% endif %}' friendly_name: 'Living Room Motion'
but this bombs HA lol so now I discovered the Template Tool (very nice btw) trying to figure out what the magic formula is here to have this monitor the attribute of value
Ok fixed it ๐
sensors:
living_room_motion:
value_template: >-
{% if is_state_attr('sensor.living_room_burglar', 'value', 8) %}
active
{% elif is_state_attr('sensor.living_room_burglar', 'value', 0) %}
inactive
{% else %}
n/a
{% endif %}
friendly_name: 'Living Room Motion'```
Okay, sorry for what I think is a very noddy question ... but I am clearly missing something ... any idea why this binary_sensor is not working in the way I think it should be ... It records "away" if only one person leaves the house where as I just want to know if anyone is home (incidentally using a group of people and checking their status seems to do the same)
maybe a group is simplier
family:
name: Family
icon: mdi:home
entities:
- device_tracker.xxx
- device_tracker.xxx
I tried with a people group ...
household: name: Family entities: - person.one - person.two - person.three - person.four
but get the same behaviour ... it will show away as soon as only one person leaves
impossible
as long as one person is home, the sensor should be home
is stated in docs: https://www.home-assistant.io/integrations/group/
I understand, which is why I am so confused and yet this is the behaviour I get ... when I put group.household into a lovelace dashboard (entities card) it switches to away whenever a single person leaves the house ... I have been scratching my head with this on and off for a few days now, hence the call for help - because I agree, its does not seem to be working as designed or documented to me
but its the reason I created the binary sensor to try and get different results, but all I can get is the same ๐
u track properly all persons?
yes, all 4 people are using the HA app. All 4 are showing individual home/away status correctly, all 4 people have their phone as a device tracker such as this:
(ahh no image pasting ? ;-))
1 sec ...
@solar knoll Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
anyway, individual status is reported correctly for each person
oh. u have viruses ๐ฎ
LOL, no ... apparently the blacklist here thinks pasteboard_dot_co might though
heya ppl
I want to track my energy usage and compare with my utility company, trouble is I don't have a proper ticking signal
I have continuous energy readings, does anyone have/knowof a readily available template to construct a sensor that ticks every kWh?
hi, i want to use tempating on service call ligth.turn_on. i want to configurie it via "gui" this is my approach:
brightness: >- {{ (2 + (state_attr('light.shellydimmer_indirekt', 'brightness') | float / 2.55)*0.3) | int }} white_value: >- {{ (2 + (state_attr('light.shellydimmer_indirekt', 'brightness') |float )*0.3) | int }} entity_id: light.shellyrgbw2_tv_led
i get an error like ...expected int for dictionary value @ data['brightness'], can you tell me how to proper use service template when working with the "gui" ?
all suggestions, threads and whatsoever are for configurations.yaml
i try to find the answer for like an hour
changing > to >- and try various versions of '' and ""
but most of the time the solutions are related to replace like data with template_data but when working with the "gui" i cant change this
yes
that tool does not support templates
๐ซ
omg
pasting my educated guess into the automation i wanted to create and it worked right away
thx
How do I return the brightness of a light?
Hi everyone. I have a doorbell a bit far away on a flaky wifi, and last_changed for the last ring instead turns into the last reconnection. Can a template that sets itself to on when the state is on, and to off any other time, be used instead?
as its own sensor probably
A template sensor. I'll try that!
usually {{state_attr('light.entity_id', 'brightness')}} will work
I use mirrors to return brightness. Works really really.
Hi, can I access (read) the field of a script (https://www.home-assistant.io/integrations/script/#fields) from the UI or another script/automation?
see https://www.home-assistant.io/integrations/script/#passing-variables-to-scripts, you can pass variables to a script, if that is what you're asking
Thanks for the hint. I am talking about reading a variable if a script is running. Let's say a script is called with the varibale value "a". I would like to read this variable from another script or automation (or the UI).
as far as I know only the calling automation and the called script have that information, but what do I know ๐
Yes there is no way to catch that information from another script. Except of course if your first script store that info somewhere
Thanks to both of you! ๐
This isnt rounding to 3 decimal places
value_template: "{{ states('sensor.dehumidifier_volts') | float / 230 | round(3) }}"
returns value_template: "1.0078260869565219"
any ideas why?
how do i do that?
how would you do that with math?
Would anyone know how to do the following correctly, to compare multiple values for selectattr:
{{ expand('group.lights') | selectattr('attributes.brightness','equalto', [255, 245, 200]) | map(attribute='entity_id') | join(',') }} If not, is there a better method? Thanks!
I mean, how do I round the resulting number from the sensor / 230
right, but if you were to write this on a piece of paper, how would you write it?
think back to highschool math
work the answer out then simplify?
ok thanks
np
selectattr('attributes.brightness','in', [255, 245, 200])
Thanks, unfortunately this isn't working either. Maybe i am missing something.
then your light isn't set to exactly 255, 245, or 200
Apologies, this is working perfect. Human error! Thank you!
np
Oh I would very much like to show which of my cameras is not in privacy mode (a camera entity attribute) do we have some sort of template wizard ?
Your template wizards tonight are petro and phnx. ๐งโโ๏ธ
and the template petro just posted might apply directly to your situation
But no... no templates. There are so many things you could write that there's no easy way to suggest templates.
Hm that's sad - I'm trying to find some examples where attributes will be shown in messages based on attribute conditions and only batteries states is the most typical
If you don't know how to write templates, start by reading the links in the topic and the pinned messages.
If you want to know more advanced techniques, read the Jinja2 documentation.
Thanks and thank you for a pleasant "tone" it is very much appreciated (most people starts as Noobs)
No problem. Templates are difficult. If you start with the basics, they gradually make more sense.
I think I've got it:
{% if state_attr('camera.kokken_cam_sd', 'privacy_mode') == 'off' %}
The camera in the kitchen is ON
{% endif %}
Now an OR sentence would be nice in the condition line - like if this camera1 OR this camera2 then message: The camera1 or camera2 is ON
That's okay... but what if you have 5 cameras? Or 10? The template gets big ๐
That's why things like this are useful: #templates-archived message
Hm then I know something about groups
Try putting your cameras in a group and then doing something like this:
{{ expand('group.cameras') | selectattr('attributes.privacy_mode','equalto', 'off') | map(attribute='entity_id') | join(',') }}
cool yes
And now groups can be made from UI (I will go for that)
Well no groups from UI ๐ซ yet - I bet I have seen something - ok YAML we go
Get it works Thanks again Momo
No problem, MrBorb
well MrMono - any idea why this is not showing anything:
{%- set ns = namespace(message = 'These cameras is turned ON:\n') -%}
{% set temp =expand('group.all_cameras')
| selectattr('attributes.device_class', 'eq', 'privacy_mode') -%}
{%- for item in temp -%}
{%- if item.state == 'on' -%}
{%- set ns.message = ns.message + ' - ' + item.name + ' \n' -%}
{%- endif -%}
{%- endfor -%}
{{ ns.message }}
when this one does:
{{ expand('group.all_cameras')
| selectattr('attributes.privacy_mode','equalto', 'on')
| map(attribute='entity_id')
| join(', ') }}
I have no idea what you're trying to do with the first one.
But if the second one works... just use the second one.
hehe - I just try to extract the "items" where attribute is eqto privacy_mode and then check state for each
Oh, you're trying to get the names instead of the entity ID's?
yep - Just like I do with this battery argument:
{%- set ns = namespace(counter=0) -%}
{%- set threshold = 100 -%}
{% set temp = expand('group.battery_levels')
| selectattr('attributes.device_class', 'eq', 'battery') %}
{%- for item in temp -%}
{%- if item.state | int <= threshold -%}
{%- set ns.counter = ns.counter + 1 -%}
{%- endif -%}
{%- endfor -%}
{{ ns.counter }}
Maybe this (I haven't tested it):
{{ 'These cameras is turned ON:\n'~(expand('group.cameras') | selectattr('attributes.device_class', 'eq', 'privacy_mode') | map(attribute='name') | join('\n')) }}
YES !
It's so easy if you know it
The trick is the pipes (|), especially | map. They're very powerful.
hm cool
There's a link to those filters in the pinned messages if you want to learn more.
thanks - I will check it
Just to tell you what this meant - now we get a message on our phones if somebody is at home and the cameras turns on = Exit Privacy-mode - and it tells us which of the cameras is turned on - Cool feature
Hi Guys, I'm extracting a temperature value using this code: value_template: "{{ state_attr('sensor.uRad_Cloud_Multiple', 'temperature') }}" How can I round the extracted value to no more than two decimal digits?
{{state_attr(...) | round(2) }}
thanks a lot @charred dagger
Hey nice people.... I have a DHT22 sending a mqtt topic once a min via cron on a remote machine..... The state gets set as nothing due to unreliable results from the sensor sometimes
is it possible to have a template that if the result from the last topic is null/0 uses the last value ?#
or maybe better the other end.. to not send if empty ... yea that sound better lol
i think you're spot-on fixing the problem at the source ๐
template stuff only really knows what the current state of something is
there ya go. bitta bash and mktemp tail -n 1 woop woop lol
oh and sed of course ๐คฉ
good evening is it possible to make a template that check's if there is a value written on a sensor before writing it on a new sensor? i am using the utility meter for showing my last periods in dashboard but if the target sensors goes to 0 / nothing and the value comes back it counts up the complete value from 0 once extra on the utilitymeter
now i am making a comparison if the new value is greater then the already written value but home assistant makes note of a detected loop in the log
this is my current configuration
- platform: template
sensors:
stroom_export_totaal:
icon_template: mdi:home-export-outline
friendly_name: Stroom export totaal
unit_of_measurement: kWh
value_template: >-
{% if (states('sensor.p1_meter_total_power_export_t1') | float + states('sensor.p1_meter_total_power_export_t2') | float) >= (states('sensor.stroom_export_totaal') | float) %}
{{(states('sensor.p1_meter_total_power_export_t1') | float + states('sensor.p1_meter_total_power_export_t2') | float) | round(3, 'floor') }}
{% endif %}
how to avoid TypeError: argument of type 'NoneType' is not iterable when checking for an attribute that may, or may not exist, but the execution requires it exists and matches pattern?
since in automation I can't directly use a sensor attribute as trigger, as I learned here last week, I'm using the state update as trigger, and using a condition. In this case, it's a phone notification.
State trigger is the last notification sensor.
Ok... what does this have to do with #templates-archived ?
original question
the condition is template, such as {{ 'foo' in state_attr('sensor.op7tpro_app_last_notification', 'json') }}
but the field 'json' may not exist every time this template is called, and the template engine doesn't like that - as such I'm getting errors in the log
So... you need to create a template that doesn't give an error ๐คทโโ๏ธ
Next time... provide the template first ๐
I had to ask my rubber duck and it told me to at least remove my home address from it
|default([])
Nah, that'll blow up ๐
I was going to go with the messy...
{{ state_attr('sensor.op7tpro_app_last_notification', 'json') and 'foo' in state_attr('sensor.op7tpro_app_last_notification', 'json') }}
Would still fail because it'll eval both every time
It works ๐คทโโ๏ธ
I just tested it
It's lazy evaluation, no? Shortcuts when the first half is false.
seems to me it wouldn't bother evaluating the 2nd step if the 1st fails, so this should be good
Odd probably some jinja stuff. Python evals the full thing
๐
iirc python lets you do lazy matches too, so why not lazy evals as this
I'm just looking forward to upgrading all my projects to Node 14 for that sweet sweet optional chaining.
@final zenith something like this:
{% set test ='light.upstairs_bedroom1' %}
{{test |regex_match('light\.upstairs_.+', ignorecase=False)}}
and then combine with https://www.home-assistant.io/docs/automation/trigger/#template-trigger
and of course this is just an example that works in
-> template
anyone that can help me with this one?
Hi! I want to catch any action/subtype of an Ikea remote (integrated via z2m) with one trigger to avoid an automation for every action-type and also a long trigger-list. But out of course I need to filter other changes like linkquality&battery then. I'm just struggling with the template-condition:
{% if ((state_attr("trigger.from_state.entity_id", "action") != state_attr("trigger.to_state.entity_id", "action")) and not is_state_attr("trigger.to_state.entity_id", "action", "")) %} (...)
Valid code but this is also filtering out all actions...?! Has somebody an hint for me why?
I'ce never used a template before so I'm not super familiar with them. But it looks like you are wild carding the name of the entity aren't you? I'm trying to wild card the value. Something like:
entity-id: sensor.my-sensor
value: "partial-val*"
You should not quote trigger.*
Uhm, they are needed?! Another similar template is also working with the quotes. Or am I completely wrong
Just tried it out...
You should not mix up variables that contains the id if an entity and strings that represent an entity. Here trigger.to_state.entity_id is a variable containing the identifier of an entity -> no quotes
Hey guys can anyone explain how to view trigger/event data?
I have some MQTT things happening and I want to use templates but I don't know how to see what I can work with and what the layout of incoming trigger data is.
okok.
{% if (state_attr(trigger.from_state.entity_id, "action") != state_attr(trigger.to_state.entity_id, "action")) and not is_state_attr(trigger.to_state.entity_id, "action", "") %}
But still not working ๐ฆ But the attribute (action) needs to be in quotes as we are checking for this value, right?
'not working' doesn't help anyone.
Please don't say I have an error or describe an error. Share the whole actual error message so we can help you.
I used zigbee2mqtt logs to see the payload and used trigger.payload_json to access the payload like such:
trigger.payload_json.angle
For anyone wondering
Hi all! I have a climate.hallway entity (Nest thermostat). I'm trying to write a script that will just add one degree to the current set temperature using the climate.set_temperature service. I tried using the following template as the service data , but I'm getting a Message malformed: expected dict for dictionary value @ data['sequence'][0]['data'] error:
temperature: {{ state_attr('climate.hallway', 'temperature') | float + 1 }}
The temperature is an attribute of climate.hallway that is what the thermostat cooling/heating temp it's currently set to, btw. Any ideas of what I'm doing wrong here? Thanks for the help!
sorry. It's just that I'm confused because no error on the GUI-configCheck occured. On the CLI-check there is one, but he also occures when the condition I'm currently debugging is commented out, so I think it is something different. https://paste.ubuntu.com/p/RWQVTmSk3n/ Can I provide something else?
is there a way to access all sensors of a certain type?
like "for each sensor in binary_sensor" or something like this?
What do you need? All the state objects, just the state values, just the names?
hi guys, because HomeKit climate control doesn't have support for "Dry" or dehumidfiers, I've created a fan template that I will then present to HomeKit to give us control of the dry function on our split system A/C. But I can't remember how to get the input boolean switch i created for tracking the state of my fan template to detect the state of the A/C. Am I asking in the right channel for help with this?
trigger:
platform: template
value_template: "{{states('sensor.my-sensor') |regex_match('partial-val.+', ignorecase=False)}}"
You should not quote your template when using a multiline (usage of >)
@ivory delta I created n utility meters, so I would have a template in the tariff switching automation to call all meters and switch their tariff
something like "for each meter in utility_meter do meter.select_tarif = xyz"
Ok, so you want the entity ID's? This gets you a list of ID's for a given domain:
{{ states.utility_meter | map(attribute='entity_id') | list }}
ok I need to understand this syntax better, thanks for the hint @ivory delta !
different question:
{{ (((states('sensor.garage_powermeter_electric_w_value')) | float) * 0.001 ) }}
this template works perfectly when in developer mode, but when I put it into a yaml, the sensor doesn't work
garage_powermeter_kw: value_template: "{{ (((states('sensor.garage_powermeter_electric_w_value')) | float) * 0.001 ) }}" unit_of_measurement: kW device_class: power
any clue what I'm doing wrong?
I want to add a number of sensor values. However, if I do this, it does not add them up, but they come out one after the other. How do I fix this?
'{{ ((states.sensor.today_consumption_sven.state + states.sensor.today_consumption_los.state + states.sensor.today_consumption_wasmachine.state)) | round(2) }}'
You're adding strings together. 'bob' + 'bob' = 'bobbob'
You need to cast each item to a number type first. states.sensor.today_consumption_sven.state | float
Also, you should use that format (states.sensor.today_consumption_sven.state). Instead, use states('sensor.today_consumption_sven')
How can I accumulate daily power costs if unit rate changes every half-hour? I have the current wattage and total for the day
and I have a rest sensor with the current unit rate
Update the tariff when it changes: https://www.home-assistant.io/integrations/utility_meter/#service-utility_meterselect_tariff
But that's an #integrations-archived discussion.
Maybe #automations-archived, depending on how you update it...
the unit price varies, does tariff accept a number?
Read the docs I linked, it'll tell you.
Then you have your answer. But this conversation belongs in #integrations-archived
why even suggest it then
Because now you have more knowledge than you had before. I don't know if there's a finite or infinite number of prices for your energy supplier ๐คทโโ๏ธ
If it was finite, you could create tariffs... ๐คฏ
Yes but it isnt. I did say the rate changed every half hour
anyway, can I not just do unit price * watts then accumulate it in a sensor?
Maybe... but that's #integrations-archived
How can I set a list of spotify uri's and then do {{ list | random }} ?
should I put in this automation just above something like {{ set list = ['list1','list2','list3','list4','list5']}} (pseudo code)
@ivory delta it doesn't give any error, it's just unavailable
I checked the logs and there is nothing about that sensor, but when I try to read it it's just not available
Is this the correct way:
'{{ ((states(sensor.today_consumption_sven) | float + (sensor.today_consumption_los) | float )) | round(2) }}'
Because now it says unavailable.
step 1) #templates-archived message
step 2) #templates-archived message
@harsh anchor Generally, don't tag people to ask for help - it comes across as bad manners, youโre demanding somebody answers you. Itโs different if youโre thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.
Similarly, please donโt DM (direct message) people asking for help. It also comes across as demanding, and means that others canโt learn from what you do.
Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on). 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.
Anyone can answer your questions if you give the right information. It gets really annoying being tagged throughout the day.
ok sorry, I'm used to forums really
anyway as I said before, in developer tools - templates it works fine, when I put it in the config it doesn't, and there is no error in the logs
single quotes I think should be around the name of the sensor inside the braces
I would probably do it like this
"{{ ((states('sensor.today_consumption_sven)' | float + (sensor.today_consumption_los) | float )) | round(2) }}"
notice the single and double quotes
this is how I do all my sensors recently
Hello Community, I would like to set an input_datetime but with my template is not wants to work.
Service: input_datetime.set_datetime
Entity: input_datetime.bedheater_time
datetime: {{ (utcnow().strftime('%s') | int + (60*60)) | timestamp_custom ("%y-%m-%d %H:%M:%S") }}
In the developer tools its giving back the correct value, but in services I cannot test it.
Error:
Failed to call input_datetime/set_datetime service. Invalid datetime specified: {'[object Object]': None} for dictionary value @ data['datetime']
Thank you very much.
It can be its an issue and the service is not working? Even the examples from the docs are not working. and I found 1-2 year old community forum entries about this problem and the moderator told them to open an issue.
(sensor.today_consumption_los) is not a thing. It should be states('sensor.today_consumption_los')
Thanks for your help, if I do this I would not add the sensors, just give the value of the first sensor
Can someone be kind to test an example with input_datetime.set_datetime service? Looks like its not working, but I want to be sure.
before I spend hours or days to fix my script.
just try this please from the official documentation in developer tools -> Services
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.XXX
data:
datetime: "{{ now().strftime('%Y-%m-%d %H:%M:%S') }}"
Is there a syntax like: for name in states.person where name.state == 'home'?
background:
{% if name.state == 'home' %}
{%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%}{{ name.name | capitalize }}{%if loop.last %} are home.{% endif %}
{%- endif %}
{%- endfor %}```
in the above, if the first person in the list is away, the result is ", Bill, Entrick, Jimmy, Mark and Sven are home." (note that it starts with a comma)
Something like this?
{{ states.person | selectattr('state', 'eq', 'home') | map(attribute='name') | list | join(", ") }}
It won't do the 'and' for the final entry. You'll have to get clever to do that.
wheew...uh...that's way over my head. LoL
It's Jinja filters. Each step is just passing the results of the previous step through another filter.
haha. I'm trying to grok your example
It takes state.person, picks only the ones where state=home, then picks the names of those, turns then into a list (because map() returns a generator), then sticks 'em together in a readable format.
Play around with it in Dev Tools > Templates.
Will do.
I spotted you have a | capitalize in yours too. Add that in just after | list if you need it.
Tell ya what... this might work:
{{ people[:-1] | join (", ")~" and "~people[-1] }}```
First line returns a list (array, in other words) of the names. Second line just does some templating with the results. All but the last item are joined with ', ', then you add ' and ' and the final name.
And since I can see them lurking already, I'm gonna thank slashback for the ~ trick ๐
You can add | map("capitalize")| to capitalize the elements of the list (just before the | list)
...mind blown.
That template will probably give odd results if there's fewer than 2 names found. Be sure to test it yourself.
You can always separate the two bits of logic by doing something like this:
{{ people[:-1] | join (", ")~" and "~people[-1] }}```
Easier testing that way.
After you gave me the first line, I was working down that path...creating the "people" variable then looping...but the second line I wouldn't have gotten ๐
The second bit is a mix of Python and Jinja. Jinja for the | join filter but Python to select items from the list and mash 'em together.
I used to hate templates. I'm making an effort to learn more.
...just...wow!
Filters are incredibly powerful once you learn how they can be used. Someone recently had a 9 line nested loop with namespaces... turned it into one line with filters ๐
Thanks mono for your help!
No problem. Always happy to help a newbie out.
slightly off topic, but I'll keep it quick because it's cool. Using that template as an Intenet, which is called from a Google Assistant bot I created using Google's Dialog Flow project. Basically, I can ask my bot "who's home" or "is XXX home". Super cool stuff!
That sounds great ๐
{% if peopleNotHere == ['pfunky'] %}
Everyone is home except you!
{% else %}
{% set peopleHere = states.person | selectattr('state', 'eq', 'home') | map(attribute='name') | list %}
{{ peopleHere[:-1] | join (", ")~" and "~peopleHere[-1] }} are home
{% endif %}```
Is the test is number supported for state attributes? It's giving me unexpected results in the template editor, see: https://imgur.com/a/4pRQsCU
is number returns true if the variable is a number, not if it is String representing a number, and since states are always string, is number on a state will always return false
{{ 3 is number }} --> True
{{ "3" is number }} --> False
You your sensor should always be positive, you wan use this : {{ states('sensor.your_sensor') | int(-1) >= 0 }}. It it fails to cast in int, the cast will return -1 which is below 0 -> it will return False
@fossil venture ๐
This isn't a state. It's an attribute. Attributes can have different types than just string.
See the "Templates" breaking change in this release https://www.home-assistant.io/blog/2020/11/18/release-118/
"Entities with templated attributes. Attributes keep their native Python type, thus if the attribute is used/processed in a template again later, the type might be different."
Indeed, if it's an attribute, it can be a number (my bad, I missed that).. but is it a number in your case?
Yep. See the first template result in the images I posted.
I don't think you can trust that.
I put {{ "3" }} in the template tool, and it says it is a number. While clearly it is a string type for jinja.
Hmmm.
You could be on to something. The dev tools states menu returns this for the attribute: temp: '19'
So it's the template editor that is misleading.
Hi I'm trying to create a template for a binary sensor that show "on" when my iPhone is connected to the downstairs router. this is what I've got so far:
- platform: template
sensors:
tonys_iphone_downstairs_sensor:
friendly_name: 'Tony Downstairs'
value_template: >-
{{ is_state_attr('device_tracker.tonys_iphone_wireless', 'Connected to', Downstairs) }} ```
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/.
These are backticks: ``
Close. 3 of them on each end looks better ๐
binary_sensor:
- platform: template
...```
Hi
Im trying to get the weather state into a conditional type and then also use that state as an image.
ATM im using this (works) but want to make the my newbie code shorter
https://paste.ubuntu.com/p/4CQw93yVtN/
im trying this, but don't show the icons.
https://paste.ubuntu.com/p/w55cRkysZt/
thanks for the tip! @ivory delta
If 'Connected to' is an attribute of that sensor, the only thing that looks wrong is the last part... you need quotes around 'Downstairs'
In case you didn't already know, you can test templates at Dev Tools > Templates. It's quicker than reloading sensors.
@ivory delta ok, the example in the documentation has without quotes
let me try with
If you do it without, it's a variable. It needs to be with. Could you share a link to the docs?
btw downstairs is the vallue its polling for, not the attribute
@ivory delta thanks! But same result. I'm starting to wonder if Connected to is even an attribute of the sensor: https://imgur.com/a/QQEuAOa
go in the Tools > State and check the name of the attribute
Don't trust what you see in 'more info'
Always use the Dev Tools to check states/attributes.
link to docs: under "states" https://www.home-assistant.io/docs/configuration/templating/
This?
is_state_attr('device_tracker.paulus', 'battery', 40)
That works because it's a number.
Strings must have quotes.
@ivory delta @deft timber thanks so much! it should be "connected_to" not "Connected to". I feel dumb but I'm a bit smarter now. Thanks allot for your help, its working as expected now.
The UI will try to make it readable. The code doesn't care about readability ๐
Hello everyone, quick question:
Using a command line switch
command_state: "/usr/bin/curl --digest -u user:pass -X GET http://X.X.X.X/ISAPI/Intelligent/channels/2/behaviorRule/1/notifications"
value_template: >-
{% set status = value | regex_findall_index('(?<=id>).*?(?=<\/id>)') %}
{% if status == "email" -%}
true
{%- else -%}
false
{%- endif %}
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.
What's wrong in value_template?
We can't say what's wrong if you don't say what's happening. It would also be helpful if you shared some example values.
value -> refers to GET result from command_state right?
I would like to understant you value_template works: if I want to turn the switch on whats should I put there? and if I want the switch off?
Yes... but I don't know what possible values you can get back...
And if I don't know what possible values you can get back, I don't know if your template is valid ๐คทโโ๏ธ
I wish to control my two covers Aqara switch. One click and it will open/close left one. Two clicks and it will open/close right. It works. But when they are moving and I click again it will not stop them and go back up. I am thinking I need to detect if they are moving. My covers are mqtt based connected to Shelly 2.5 without cloud. How can I tell covers are currently moving?
@ivory delta thanks for your help friend. My switch was not updating the state correctly. And wont be able to fix it if I dont understant how things work. From GET im getting a xml file. Assuming the value is by default the response from GET applying this regex: regex_findall_index('(?<=id>).*?(?=</id>)') % on var status I will have either or "email" or nothing. If what I said is correct, I understood perfectly until here. My doubt is how to make the switch on? Is the if really necessary? To change the switch state should I use true and false like above?
Fixed with a state_image.
@blazing cradle can u share new code and from where u get svg files ?
Hi Adrian
I simply can not remember which weather station I watched them on and borrowed them via developer tools in the browser for my private home setup.
But the way I did the other thing was:
https://paste.ubuntu.com/p/ZzP5fKP6h7/
u got rid of all conditionals?
yes going from 120+ lines to 22 lines.
Can see that the icons/images look likes these, after i open on in NotePad++ and and search for @keyframes am-weather-cloud-1 on google.
https://gist.github.com/AlexBlack88
But I know it was an weather station i saw em at.
i have something similar but for whole dashboard and i thought it could be nicer to have only a weather card
Take front-end talk to #frontend-archived please
I got todays weather in one side and tomorrows weather in another.
Hi, anyone can help getting this automation working. It works fine sending a notification to my phone but the available version always is none instead of the latest available version of HACS. Hope that anyone can guide me what I did wrong. ๐ https://paste.ubuntu.com/p/GBn3swSSbz/
It's because the attribute you're looking for doesn't exist ๐
{{ state_attr('sensor.hacs', 'available_version') }}
Check what's in Dev Tools > States. What's in the 'attributes' box for sensor.hacs?
Seems itโs there but under repositories, is that the issue?
That's part of the issue.
Firstly, it's not at the 'top' level.
Secondly, it's in a list and that list could be in any order.
So... you need to search that list for the item where the name is hacs/integration and then get the value of that item.
Like this...
{{ (state_attr('sensor.hacs', 'repositories') | selectattr('name', 'eq', 'hacs/integration') | list)[0].available_version }}
Thanks allot, works perfect! I also asked it to @acoustic finch and posted the same. Thanks both! ๐
{{ state_attr('sensor.hacs', 'repositories') | selectattr('name', 'eq', 'hacs/integration')|map(attribute='available_version')|first }}
slightly safer if you miss
Thanks all! @acoustic finch posted this which is also working fine. Better to use the other one you and @ivory delta posted? {{ state_attr('sensor.hacs', 'repositories')[0].available_version }}
if you get None or [] back from that attribute, as you have it written it will throw an exception
This is true... but he's already using a condition that he can adapt to prevent that ๐
I'm sure there are better ways to do it in a single template too. I'm a mere padawan.
I have a sensor which supplies the status as a text. I want to trigger an automation based on the content content of this text. So, if it contains a specific string, the automation should run. I am guessing that a data template should work, based on a text pattern in the string. Would that be possible? And if so... How? ๐
something like:
trigger:
platform: template
value_template: "{{states('sensor.my-sensor') |regex_match('partial-val.+', ignorecase=False)}}"
match in this example is starting with, but with some regex magic, this can be anything
Good Morning. I am trying to match specific angles of a window or garage door with an Aquara Vibration Sensor. The Sensor has an attribute called orientation that returns three comma seperated, numeric values.
The output of this orientation attribute looks like this [ 1, -76, 14 ]
I am struggling now to find a way to match the position because the last value differs time to time by one or two.
something like {{state_attr('sensor.something', 'orientation')[1]}} might work
Is it possible to console log a value from value_template?
I'm getting trouble with value_template, and I would like to see whats coming from value to help me debug
Is this in an automation or script, or something else?
It's a Template Switch using command_line
Then you'll need to execute the command line yourself to see what is normally returned.
Use the template editor
It returns a xml file when I use curl on cmd
based on that curl if word "email" exists switch should be on
ok, then paste the xml files contents into a string named value in the template editor, it's the same thing
value_template: >-
{% set status = value | regex_findall_index('(?<=id>).*?(?=</id>)') %}
{% if status == "email" -%}
True
{%- endif %}
{% set value = 'contents of email' %}
That value_template I sent is causing "Update for switch.cam_piscina_mail fails"
so you aren't even going to try what i'm suggesting, just argue?
I'm going to try and I appreciate it, I just would like to know what I'm doing wrong
again, take the contents of the email and set it in a variable. IF the contents of the email are "HEY MY NAME IS"...
{% set value = "HEY MY NAME IS" %}
then test your template
in the template editor
Sorry petro, i'm not understanding, the GET from command_state returns a xml file. I need to search in that if the word email is present (it appears on xml <id>email</id>, when the motion detection on this camera is active) and use it to correct the status if home assistant restart or in power failure.
value_template: {% set value = "HEY MY NAME IS" %}
value_template: {% set value = "email" %} is this your sugestion?
sorry for bothering I just started templating a few days ago
If you want to test your template, do it in the Dev Tools. To simulate what you would get back from the GET, assign it to a value in the Dev Tools.
When you are confident your template works, put it in your value_template:
Do you know what 'Developer Tools' is?
On the main bar on the left side of home assistant, there's a section called "Developer Tools". Inside that page is a tab named "Templates"
That's the template editor
it allows you to edit and test templates
yes petro I already done it
I'm not telling you to put {% set value = "HEY MY NAME IS" %} in your value_template
now you can
Ok, so what's the template output
on the right hand side
can you please pastebin your email
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.
