#templates-archived
1 messages · Page 130 of 1
Everything should be UTC in data and presented differently in the UI.
yep
if it's a time datetime it the timestamp should be today at that time in utc
if it's a date datetime it should be the timestamp at midnight your tz in utc
if it's both, well, that's easy
just the damn datetime in utc
suppose that I need to call a service inside my automation
- service: mqtt.publish
data_template:
topic: "tele/solarstation/REMAINING_SECONDS"
qos: 0
retain: false
payload: '{"remaining_seconds":"{{ states.input_number.waterpump_activation_seconds.state | int }}"}'
something like this
how can I insert template in the payload attribute?
I mean something with an if then else
like this
{% if (timestamp_now < state_attr('input_datetime.solarstation_activation_hour', 'timestamp') ) %}
2
{% else %}
3
{% endif %}
I would like that the result of the if then else is the value of one of the json attribute of the payload
Have you tried it?
Well for a start you need payload_template not payload
Check the docs: https://www.home-assistant.io/docs/mqtt/service/
last question
I have this
{% set timestamp_now = as_timestamp(utcnow().replace(year = 1970, month = 1, day = 1)) %}
if I do this
{{ state_attr('input_datetime.solarstation_activation_hour', 'timestamp') - timestamp_now }}
it returns 8269.825654
what the heck is 8269?
now is 18:12
and input datetime is set at 18:30
It's the difference between the two
oh my god
You're doing maths. Subtraction, specifically.
In seconds.
I think that Cobol is better than this
🤯
The language you use has nothing to do with it. It's simple maths.
You're welcome to reproduce HA in Cobol if you like.
in this moment I can't find how to translate that numbers in the difference between the two "time"
expressed in seconds or minutes
how 58560 can be the 18:16? 😄
Does Cobol not have the mod function?
58560 / 60 = 976
58560 seconds since midnight. Where there are 86400 seconds in a day.
but isn't 58560 / 60 should return minutes?
No... dividing an integer by another integer won't give minutes. Why would it?
still don't get how to get the difference between this two time expressed in minutes or seconds mmm
if you have 120 seconds and you divide it by 60
you get 2 minutes
How does it know you're working with seconds and minutes? There are no units.
120 is just a number. 60 is just a number. It's not a mind reader.
What do you want?
I want to get the difference in seconds or minutes between this
as_timestamp(utcnow().replace(year = 1970, month = 1, day = 1))
and this
So do the math...
state_attr('input_datetime.solarstation_activation_hour', 'timestamp')
What format do you want the output in?
integer is ok
You have an integer.
we are talking about seconds or minutes int is ok
120 / 60 = 2. 2 is your integer.
but it doesn't work as I expect
reread this numbers
timestamp_now = 58994.105547 (and now it 18:23)
state_attr('input_datetime.solarstation_activation_hour', 'timestamp') - timestamp_now
returns
7605.894453000001
if I divide 7605 by 60
I get 126
and it's not true
since the solarstation_activation_hour is set to
18:30
Write full sentences on one line, thank you. Don't flood the chat.
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/.
ook
Which timestamp do you think is wrong?
at this point I don't know
Ok. Have fun.
as_timestamp(utcnow().replace(year = 1970, month = 1, day = 1))
this should return the now timestamp
so it should be ok
state_attr('input_datetime.solarstation_activation_hour', 'timestamp') this is too simple to be wrong
That's the timestamp in UTC... you live in UTC+2...
+1 not +2
And it's summer, no?
yes
So... UTC+2?
ah ok no GMT you're using UTC
damn
but is there a simple way to get the difference of a input_datetime and now?
Sure. Subtraction.
what kind?
The kind where you subtract one number from another.
lol
What does as_timestamp(utcnow().replace(year = 1970, month = 1, day = 1)) give? And what does as_timestamp(now().replace(year = 1970, month = 1, day = 1)) give?
59606.619628 and 63206.619795
And {{ state_attr('input_datetime.solarstation_activation_hour', 'timestamp') }}?
66600
Yeah... so you're going to have loads of fun with that, especially since summertime is going to mess with it.
at this point I don't think that "is possible" with this kind of templating
at least
not in a "human readable" format
is there a better approach to the problem?
your input_datetime does not have dates right? just time?
here's what I understand (and I just briefly scrolled, there is too much text to read through line by line) - you want to be able to set a time of day using an input_datetime, and then every day do some automation based on that
is that correct?
ok no, you have two input_number's
more or less yes, but I'll try to give you the context. I have an ESP that wake up every ten minutes and checks when it need to enable the water pump. this information is sent from HA to the ESP and it's the input_datetime.solarstation_activation_hour
you want to use two input_number's, each which represent an hour and minute, to create a datetime for today at that hour and minute
my ESP wake up every 60 minutes but if there is only 15 minutes between now and input_datetime.solarstation_activation_hour it should sleep only 15 minutes
and then from there you want to compare that datetime to some other datetime and do some logic based on that
I switched the two input_number to input_datetime as per suggestion
but I can use whatever I want to solve the problem in the easyer way 🙂
how can I calculate the 15 minutes?
that is what I need to calculate
well, my suggestion is to create a second input_datetime (or first if you stick with the two input_numbers), and then create an automation that runs every day to set the datetime to today with that time
If this is all about controlling the behaviour of the ESP device, why not do all of this on the ESP?
then you have two input_datetimes to compare and the formats are the exact same
I can do it on all esp except one because one does not have wifi an it does not have the possibility for the OTA update
and removing it from his boxes is way too compllicated
ok I'll try this way
do you think that it will help?
doing a simple subtraction from one input_datetime and the second one should return the difference of the two time in seconds right?
And yet somehow, it probably would've been quicker than the 5 hours you've already spent trying to solve it this way 🤷♂️
the state of any entity is a string
you'd need to use one of the filters to convert them both to a unix timestamp
lol you're right
then yes, doing a subtraction would give you the difference between the two in seconds
mmm ok, I need to prepare the dinner for my wife, I will try it later xD thanks for the suggestions, I really appreciate it
PS: after all of this, I'll give you a feedback if it will work xD
no need, I get enough tags, but if it works I am happy for you
hey! is it possible to get the first reading of the day from a sensor?
Maybe with a trigger based template sensor, two automations and an input_boolean. Turn off the input boolean at midnight with an automation (time trigger). Have another automation that triggers on any state change of the sensor (state trigger with no to or from) and a condition that the input boolean has to be off. Action: turn on the input boolean. Trigger based template sensor then triggers on the input boolean turning on and grabs the state of the sensor. Or if you don't need it stored in a sensor, store the sensor state in an input number in the second automation and forget the trigger based template sensor. Or if your sensor polls on a fixed interval you can forget all that and just use a trigger based template sensor that grabs the state of the sensor at time 00:<polling_interval + a little bit>.
i have a custom time template, but it keeps giving me errors [ https://paste.ubuntu.com/p/rCrTNZnm6d/ ] in my log. the template is;
sensors:
time_since_most_recent:
value_template: >-
{{ states.input_text.lastusedss.last_updated.strftime('%Y-%m-%dT%H:%M:%S') }}Z
device_class: timestamp```
is there any way to hush the log or fix the template so it doesn't get mad?
That’s error has nothing to do with that template. That error is coming from steam_online
Hi, i need help with a template which parse JSON, some of the keys in the JSON are numbers. I'm not able to access such keys from template/Jinja. Any idea what my fault is?
{%- set j ='{"count":12,"indices":["component id","component code","component symbol","component unit","component name"],"1":["1","PM10","PM\u2081\u2080","\u00b5g\/m\u00b3","Particulate matter"],"2":["2","CO","CO","mg\/m\u00b3","Carbon monoxide"],"3":["3","O3","O\u2083","\u00b5g\/m\u00b3","Ozone"],"4":["4","SO2","SO\u2082","\u00b5g\/m\u00b3","Sulphur dioxide"],"5":["5","NO2","NO\u2082","\u00b5g\/m\u00b3","Nitrogen dioxide"],"6":["6","PM10PB","Pb","\u00b5g\/m\u00b3","Lead in particulate matter"],"7":["7","PM10BAP","BaP","ng\/m\u00b3","Benzo(a)pyrene in particulate matter"],"8":["8","CHB","C\u2086H\u2086","\u00b5g\/m\u00b3","Benzene"],"9":["9","PM2","PM\u2082,\u2085","\u00b5g\/m\u00b3","Particulate matter"],"10":["10","PM10AS","As","ng\/m\u00b3","Arsenic in particulate matter"],"11":["11","PM10CD","Cd","ng\/m\u00b3","Cadmium in particulate matter"],"12":["12","PM10NI","Ni","ng\/m\u00b3","Nickel in particulate matter"]}' %} {%- set j1= j | from_json %} {{ j1.count }} {# is working --> result 12 #} {{ j1.indices }} {# is working --> ['component id', 'component code', 'component symbol', 'component unit', 'component name'] #} {{ j1.1}} {# is not working nothing will be displayed, should be ['1', 'PM10', 'PM₁₀', 'µg/m³', 'Particulate matter'] #}
{{ j1['1']}}
Keys should not start with numbers. If they do, you have to access them this way instead.
Thank you so much, i searched the whole day and found no solution. This is not my JSON, so i have to use is with numbers in keys, but now i'm happy. 🍻
Yeah, you're not always in control of the data. Just remember there are two ways to access a key 🙂
I don't remember exactly why your first way doesn't work with numbers, only that it doesn't.
Because dot walking is a bit of a hack unfortunately. Best to use the direct python at that point via key lookup or .get()
I remember why. If you use a number, it just gets the character at that index:
{{ test.1 }}```
This returns 'b'.
Stupid Python 🐍
That’s not python, that’s jinja
Indeed:
>>> test="abc"
>>> test.1
File "<stdin>", line 1
test.1
^
SyntaxError: invalid syntax
>>> test[1]
'b'
I think jinja has that so you can properly use selectattr with strings 'x.1' etc
it's fewer characters, but it just gets me in trouble with keys that start with a number, or have spaces. I try to avoid it
but yeah, that is a nice use case for it where the bracketed notation wouldn't work
Trying to use a rest sensor and this value is too large for the state. Is there a way to template it in the rest sensor? https://paste.ubuntu.com/p/xrn2R4yjFx/
if there was a way I could map the description to a/b/c it would save lots of space. The services will change order and types so cant rely on them being like this always
you can use templates to define the value of teh sensor and any attributes you're interested in
oh I found it, value_template: "OK" then sets to attributes which skips the max length
right
I want all the data to avoid multiple calls, so I'll try that
I'm trying to get this label to show the relative time left on a timestamp or input_datetime, any help would be great!
label: | [[[ return 'Turns off in ' + states['sensor.attic_fan_turn_off_timestamp'].state ]]]
You have to calculate it by hand if you're using the button card.
Okay ugh, at least its only minutes/hours in the future
i saw it displaying so nicely on the default dashboard
var statestr = states['sensor.attic_fan_turn_off_timestamp'].state;
var date = new Date(statestr);
let now = new Date();
var tdelta = Math.floor((now - date)/1000);
function plural(descriptor, divisor){
var ret = Math.floor(tdelta/divisor);
return (ret == 1) ? [ret, descriptor] : [ret, `${descriptor}s`];
}
var values;
if (tdelta < 60)
values = plural('second', 1);
else if (tdelta < 60 * 60)
values = plural('minute', 60);
else if (tdelta < 60 * 60 * 24)
values = plural('hour', 60 * 60);
else if (tdelta < 7 * 60 * 60 * 24)
values = plural('day', 60 * 60 * 24);
else
values = plural('week', 7 * 60 * 60 * 24);
return `Turns off in ${values[0]} ${values[1]}`;
cool, thats a helpful start
Just edited it, that should work out of the box
page load only with a template like that
you can add a trigger entity to the button card, like sensor.time to have it update once a minute
so just adding entity: sensor.time into that card?
No, there's a triggers_template field iirc
triggers_update:
awesome ty!
did the template work?
finally getting this fan project close to done!
yep
just switched now and date in the math 🙂
I ripped it from my setup
cant add an image here but yep its working great
the buttons below control the timer for the fan via its remote thru scripts operating a switchbot
ya that was the only 12 mdi 😄
but likely will jsut switch for text
Yeah, you can. Use the rest integration (Not sensor) and you can put all your templates in that.
thanks for your help @mighty ledge !
hey, does anyone know if it's possible to pad left a string to always being 3 characters in a template?
very cool, thanks!
Is it possible to create template sensors from the web UI or yaml only?
Yaml only
if home assistant gives a template warning and it appears to be when using tap action: toggle on a Z2M entity group, would the issue be for Z2M or hass ?
if I change the action to mqtt with payload, it doesn't give a warning
.share the error and the 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.
when I change the tap_action to a call-service for mqtt, there's no warning.
it also happens if the zigbee entity isn't a group
I don't know where to file the issue, hass or z2m
That error doesn't seem to be related to the toggle you're doing from the button.
Hi gang! I'm trying to create a template fan object. Because of some Insteon weirdness with a wall-mounted control, I have to do multiple calls to keep them synchronized, depending on fan percentage. I've created a template fan, and the state and percentage should reflect the existing Insteon fan. When I check states in dev tools, the template fan does not match the Insteon fan. This looks pretty straightforward, so I'm confused. Any help would be greatly appreciated. Thanks!
It looks like
"{{ states.fan.fanlinc_xx_xx_xx_fan }}"
returns the correct state
But
"{{ states('fan.fanlinc_xx_xx_xx_fan.state') }}"
as is used in the example does not
"{{ states('fan.fanlinc_xx_xx_xx_fan.state') }}"
That's invalid...
states('fan.fanlinc_xx_xx_xx_fan')
The states function expects an entity ID only.
{{ states('fan.fanlinc_xx_xx_xx_fan.percentage') }}
This is also invalid. You use state_attr to get an attribute's value.
Ah OK, I was using the example in the fan template docs here: https://www.home-assistant.io/integrations/fan.template/
yeah the example is wrong
wait
no it's not, 'input_number.percentage' would be a helper entity
different from your use case
I see, thanks for that. I'm still a template newb so I appreciate the help
That worked! Thanks for clarifying. Yes, I misread 'input_number.percentage' as an attribute rather than an entity. I appreciate the link to the right section of the template page!
I do have another question folks if you don't mind. I'd like to optionally call certain services based on the value of a passed-in number. I don't think this is correct, but if you could point me to the correct way to do it, I'd greatly appreciate it!
https://paste.ubuntu.com/p/XqBvyb4Cxt/
Namely what I'm trying to do with set_percentage
You can't do that - the keys (left hand sides) have to be set explicitly. It's only the values (right hand sides) that can sometimes be set with templates.
You'll want to head over to #automations-archived for the next part but basically you want to learn how to use the choose syntax.
OK Thanks! I'll keep digging. So in the template could I call a script then that would use automations to choose the correct actions?
Or are you saying I should just have automations triggered by the state change of the fan?
Neither. But take this to the correct channel.
Hi guys im new in HA, i want make script for fan speed percentage and preset mode do you help me with code thx
You're not new...
sorry amateur
There's not nearly enough info there for anyone to even start. But this isn't an "I'd like a burger and fries" place
That's more accurate. So now you can start by sharing what you've done so far, instead of asking someone else to do it all for you.
What's the correct formatting for if/else in templates? This doesn't work.
sequence:
- service: light.turn_off
{% if state_attr('light.test_bulb', 'brightness')|int > 63 %}
data:
transition: 1
{% endif %}
You can’t do that. If you want to optionally add a transition, you need separate service calls and a choose:
There was an almost identical question asked earlier today, which may even be on screen still depending on your resolution: #templates-archived message
So there is. Thanks guys. I'll add a choose instead.
Hi there!
Does anybody know why my binary sensor won't appear? (I'm looking in the dev tools, if that helps)
template:
- sensor:
- 8_hour_rain_total:
friendly_name: "8 Hour Rain Total"
...
binary_sensor:
- name: "Rain Sensor Homekit"
state: "{{ states('binary_sensor.rain_sensor') }}"
unique_id: rain_sensor_homekit
i've just switched from "the old format" to "new format" for my templates, probably that.
neither is this:
- 8_hour_rain_total:
yes, it looks like you're somewhere between the two
would not be surprised.
i'll have to have a go again
the syntax is different enough that I find it challenging to keep track of what's valid where. I've just left mine in the old format for now
template:
- sensor:
- name: "8 Hour Rain Total"
value_template: >
better?
i was considering leaving it, but when i couldn't get a working binary sensor in the old format, i decided it must be the old format and i should try the new one ahah
yes, i've been following that. (or trying to!) it's a bit compilcated.
the very first example is similar to yours
I probably copy pasted it!
- sensor:
- name: "8 Hour Rain Total"
state: >
looks like this now. i think it's right?
looks better
@tight lantern posted a code wall, it is moved here --> https://paste.ubuntu.com/p/2b9tSpwn2k/
there's an example in what you posted
yeah. i wasn't sure how to interpret that.
but now i've fixed the rest of the templates, i bet there's a good chance it could work?
the first bit is for a state-based sensor/binary_sensor and the second is for trigger-based sensors/binary_sensors
...
- name: "Garage Spare Watts"
state: "{{ state_attr('switch.garage_spare', 'current_power_w') }}"
unit_of_measurement: "W"
binary_sensor:
- name: "Rain Sensor Homekit"
state: "{{ states('binary_sensor.rain_sensor') }}"
would this be correct, then? I based it off off that.
assuming there's a - sensor: above that you've chopped off
you can just hit "Reload Template Entities" from
-> Server Controls
if I do that, it doesn't show any errors I don't think?
i restart core via supervisor because it does
huh, i'll use it next time
you can test
2021-07-18 11:35:02 ERROR (MainThread) [homeassistant.config] Invalid config for [sensor.template]: [value_foo_template] is an invalid option for [sensor.template]. Check: sensor.template->sensors->garage_door_state->value_foo_template. (See /config/sensors.yaml, line 62). Please check the docs at https://www.home-assistant.io/integrations/template
just reloaded via Server Controls
huh. must've been solar flares or something, because i swear they didn't appear for me.
¯_(ツ)_/¯
thanks again :-)
Hello. I created an entity from the Utility Meter that takes values from the water meter. Everything works fine. It only shows values of 0.0001 L which is actually 0.1 L of water. I'm trying to modify the template to show it correctly in day mode, but it still doesn't work. I have this template but even this new one still shows values of 0.0001 L. Where is the error please?
Daily water template
- platform: template
sensors:
daily_water_l:
friendly_name: Water day
unit_of_measurement: l
value_template: '{{value | multiply (1000) float}} '
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hatebin.com/.
but your template is missing a |, and your cast is in the wrong place
where is value coming from?
#Denní voda šablona
- platform: template
sensors:
daily_water_l:
friendly_name: Voda den
unit_of_measurement: l
value_template: '{{ value | multiply(1000) | float }}'
it was copied badly, this is how I got it
#Denní voda šablona
- platform: template
sensors:
daily_water_l:
friendly_name: Voda den
unit_of_measurement: l
value_template: '{{ value | multiply(1000) | float }}'
ok, still wondering where value comes from. More than likely you need value | float | multiply(1000)
value is taken from https://github.com/jomjol/AI-on-the-edge-device watermeter
ok, so it's an MQTT sensor?
@summer summit posted a code wall, it is moved here --> https://paste.ubuntu.com/p/VJpfgmhPGf/
nothing is actually assigning anything to value, though
what section is <#templates-archived message> in?
I don't know if I understand, but it should be from this https://paste.ubuntu.com/p/VJpfgmhPGf/
something is not connecting here
where do you think value is coming from?
you just have a template sensor there
it is inserted in the sensor section
it has no obvious relationship to the utility meter
OK, where must it be located? Directly under Utility Meter?
you have to make the value_template rely on another entity, like your utility_meter entities
otherwise, value is just zero
which utilty_meter entity are you trying to convert?
something like sensor.daily_water_l?
this ```
daily_water_l:
source: sensor.meric_vody
cycle: daily
then you want
@summer summit posted a code wall, it is moved here --> https://paste.ubuntu.com/p/3j74cSKmZK/
#Denní voda šablona
- platform: template
sensors:
daily_water_l_new:
friendly_name: Voda den
unit_of_measurement: l
value_template: '{{ states("sensor.daily_water_l") | float | multiply(1000) }}'
Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).
Please take the time now to review all of the rules and references in #rules.
you can't just replace the existing sensor, you need to create a new sensor with a modified value
ok i will try it, thank you
you're just pasting snippets with minimal context, so it's hard to piece them together and fill in the blanks
but the point is that value won't mean anything by itself in a template sensor - it has no idea what it's supposed to refer to
the numbers are so far 0.0 although the main water meter has already shown an increase, but I do not know if the utility meter has a delay and some cycle need 10 minutes.
its OK, and function 🙂 Thnak you wery much 🙂
how do i convert 01:30:00 into 90 mins?
{% set h, m, s = '01:30:00'.split(':') | map('int') %}
{% set minutes = h * 60 + m + s / 60 %}
{{ minutes }}
thanks alot!!!
how do i subtract 3 mins from 01:30:00 so i would get 01:27:00 ?
i need some help regarding a template sensor... can someone tell me why this sensor never turns to "off"?
- trigger: - platform: state entity_id: sensor.sonnen_batterie_verbrauch binary_sensor: - name: "Sauna angeschaltet" state: > {{ states('sensor.sonnen_batterie_verbrauch') | float > 800 }} delay_off: "00:00:30"
I swear to god the input sensor has been below 800w for at least 5 minutes...
This should turn off if my sensor value has been below 800 for 30 seconds right?
i tried {{ 01:30:00 - timedelta(minutes = 3) }}
but it throws an error "TemplateSyntaxError: expected token 'end of print statement', got 'integer'"
Firstly, you need to quote strings. Secondly, you can't do a timedelta on a string.
i got it
{% set x = state_attr('timer.sleeptimer','duration') %}
{% set h, m, s = x.split(':') | map('int') %}
{% set minutes = h * 60 + m %}
{{ timedelta(minutes = minutes - 3 ) }}
all you needed was to subtract 3.
{% set x = state_attr('timer.sleeptimer','duration') %}
{% set h, m, s = x.split(':') | map('int') %}
{% set minutes = h * 60 + m %}
{{ minutes - 3 }}
but this would not result in hh:mm:ss format i guess
then what you have would work but realize if this crosses 24 hours, the format will be d hh:mm:ss
Dates and numbers seem so simple... until you have to do any programming with them 😄
it's that meatspace<->logic space barrier
it depends on the context and the information is stored (unironically) in the context property on the state object
Ok. I have a script for my hallway. It apply's a scene on motion. Normally I want that to be instant. But I also have an automation to adjust lighting throughout the day. That automation runs the same hallway script. When invoked by the automation I'd like to add a transition time to the scene...
just add a condition and supply a variable
a choose*
if the variable doesn't exist, use service call without the transition
assuming that you call the script from the automation with - service: script.xxxx, you can check whether the automation's current attribute is non-zero. If so, the automation is running when the script was called (presumably would always be true)
Oh! That sound's neat
or a petro mentioned, either call the script with a variable to differentiate, or set an input_boolean before and after the call and check in the script
personally, id go variable. Makes it easy and you can define a transition based on an automation
Those are all great suggestions, thanks! But global vars isn't available (yet)?
you wouldn't want that anyway
- choose:
- conditions:
- condition: template
value_template: "{{ transition is defined }}"
sequence:
- service: scene.xyz
data:
transition: "{{ transition }}"
default:
- service: scene.xyz
it's not global variables
it's simply calling your script like this
service: script.xyz
data:
transition: 1
vs
service: script.xyz
Increadible... It sound so easy when you guys get started. I will try this, thank you much!
Hm. Formatting issues most probably, but eludes me... https://paste.ubuntu.com/p/kGH8p8tZRj/ Syntax check gives me this, which I don't fully understand "Invalid config for [script]: Unexpected value for condition: 'None'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['sequence'][0]['choose'][0]['conditions'][1]. Got None required key not provided @ data['sequence'][0]['choose'][0]['sequence']. Got None. (See /config/configuration.yaml, line 15)." Do I need a default value for transition?
the second choose: needs to be part of a sequence:
otherwise, it thinks it's another condition
sequence:
- choose:
- conditions:
- "{{ is_state('binary_sensor.hallway_motion_1_ias_zone', 'on') }}"
sequence:
- choose:
- conditions:
- condition: template
value_template: "{{ transition is defined }}"
Got it working! Thanks guys!
if that's just your script you can also hammer the variables to make it less work to change things, and because you don't have a default you don't need the first choose.https://pastebin.ubuntu.com/p/Pf44pP4zrb/
@silent ember posted a code wall, it is moved here --> https://paste.ubuntu.com/p/5wy8RwBsfR/
Guess that was too long 😅 Its a sensor that Im trying to create to get the trash pickup dates from my cities website. And I only get an unknown return value, even though it should work, as Ive tried via python directly and the template section in home assistant. If anybody has an idea what Im doing wrong, Id be thankful.
value is a string, you want value_json
Can I set mode: queued on a template switch like for an automation? What is the syntax?
it doesn't make any sense there
My template switches call broadlink operations and I get Already running warnings a lot that I think are causing error responses in my voice assistants.
Was trying to eliminate Already running warnings by changing it to like mode: queued or something.
that's only with automations
I think the broadlink operations are internally scripts.
Logger: homeassistant.helpers.script.1_zap_3
Source: helpers/script.py:1310
First occurred: 6:49:56 PM (2 occurrences)
Last logged: 6:53:17 PM
my_switch: Already running
is that not your script?
my_switch is platform: broadlink
script.1_zap_3
post the full error
switch:
- platform: broadlink
mac: 'redacted_mac'
switches:
- name: 'my_switch'
command_on: 'redacted_hex'
command_off: 'redacted_hex'
expand the error and post the error
ugh, apparently that's been changed too
how are you calling my swith from the script. It's odd that the error does not come from broadlink
@patent sparrow posted a code wall, it is moved here --> https://paste.ubuntu.com/p/sWQw7NMRc9/
i don't have any scripts, just template switches that wrapper around broadlink switches (because some are multi-step)
so when the error says "script" i am just assuming either the template switch or the broadlink switch is internally using script and that's why i'm trying to change it to mode: queued
technically that error is referencing the template switch, which is why i figured i should be able to change it to mode: queued
make a script and set the mode, use the script in the turn_on section. You'll want parallel
baaaarf okay.
is there an easier way if i'm just trying to eliminate the warnings (i don't actually care about rerunning it, i just think the warnings are surfacing to voice assistant as bad error code responses (she says "something went wrong"))
remove the delay
or make a script 🤷♂️
you won't way parallel, you will want queued if you want to delay it between presses
I tried it with the assumption that value was a string as well and it was unknown just the same. Is there any way for HA to show me the value and value_json variables? If I just input value without changes HA complains about it being too long and value_json outputs nothing.
the value is a string, so your template with value[0] is only looking at the first character.
value_json turns it into an object. You'll get errors if you're accessing things incorreclty.
so, use value_json and post the error. Otherwise if you just output value you can see what it see's but it'll only be the first 254 characters
Yes, I understand that. I originally had it without the [0]. I tried it with it because beautifulsoup returns a list in python and it already wasn’t working
I’ll have to try some more tomorrow. So far I didn’t get any useful errors except the error I get if I try to straight output „value“ which is that the string is too long.
what's the errors though...
Well. None other than what I just mentioned
Other than that I only get either empty Sensor state values or „unknown“
I’ll try that tomorrow. Thanks.
Hi, thanks for the suggestion. This is the full script. I bet there are much that can be refined as I am just months into Home Assistant... 🙂 https://paste.ubuntu.com/p/mpFc68PDgY/
The issue was that scrape does not return the directly selected html, but rather a cleaned output. So the HTML codes that I was trying to split by werent actually there anymore. Thanks again.
Hello
I want to automate my colour picker - input number
which looks like https://imgur.com/lsZLj0u
then the logic becomes something like
https://paste.ubuntu.com/p/ds4fMvh8DW/
anyone have an idea how to get this done ?
use a custom:slider-entity-row with the following configuration. Replace your input_number, the range on that input number should be the range a color picker. You'll also need card mod.
- type: custom:slider-entity-row
entity: input_number.quick_strip_hue
full_row: true
hide_state: true
style:
.: |
ha-slider {
background: linear-gradient(to right, red 0%, #ff0 17%, lime 33%, cyan 50%, blue 66%, #f0f 83%, red 100%);
border-radius: 10px;
}
The result is
You'll still need the automation with that logic fyi
that you posted
or you can use this logic, which works with rgb
{%- set hue = states('input_number.quick_strip_hue') | int / 360 %}
{%- set s = 1 %}
{%- set v = 1 %}
{%- set i = (hue * 6.0) | int %}
{%- set f = hue * 6.0 - i %}
{%- set p = (255 * (1 * (1.0 - s))) | int %}
{%- set q = (255 * (v * (1.0 - s * f))) | int %}
{%- set t = (255 * (v * (1.0 - s * (1.0 - f)))) | int %}
{%- set v = 255 %}
{%- set i = i % 6 %}
{%- set ret = [
(v, t, p),
(q, v, p),
(p, v, t),
(p, q, v),
(t, p, v),
(v, p, q),
] %}
{%- set r, g, b = ret[i] %}
{{ 'rgb({0},{1},{2})'.format(r,g,b) }}
the range on the input number is 0 to 360
@mighty ledge I was already working in that direction. However I like your card more and would like to replicate it totally. Can you share your full config ?
PS I went through your GitHub but didn't find the above.
It probably won’t help because that whole setup is for a specific led strip that has odd settings. So the code and automation have to be stripped from what I have and you won’t be able to directly copy and paste
@mighty ledge I understand but still it gives an idea how the cards look like, how they work together and which automations you have build. It will most probably speed up my project, starting with this. Please would you send me the relevant info.
That’s the thing, the device I have accepts the numbers in bytes. The automation doesn’t even use that equation. That’s what I’m trying to tell you. It will not translate to you or help. The card is located in config/Lovelace/views/mood_lighting.yaml
Now I understand. Thank you. I understand the code you copied came out of your icon-colour. Still need to get it translated into an automation to make it work.
@mighty ledge The input boolean you use to distinguish between temp and colour where did you place this one ?
I'm not sure what you mean?
You don't need to distinguish between the 2
I only had to do that because of the bytes that my hardware accepts
well a light can't be temperature colour (white) or colour
for you, I'd have 2 separate automations. One that moves the color temp and one that moves the color
yes, so they would have 2 separate service calls
you can attempt to make it in 1 automation, but it would be easier for 2
well, that's what I was trying to explain to you
you used a lot of lovelace_gen
this device that I have is beyond stupid, so I had to jump through hoops to do it
The jinja that you see there just colors the icons, it's not needed
well i'm looking into your templates
all you need for the light slider and the temp slider are the cards that display them
yes but of course I found other stuff that you have done that looks really COOL
like what
for example that you have a way to see all the lights that are on
on your main dashboard
that will be hard to replicate without lovelace_gen
my entire setup is to allow me to be lazy
those files generate upwards of 300K lines of lovelace
so if you were to do this without lovelace_gen, that's what you'll be dealing with
well i played with the templates of custom button card and decluttering card
Yep, I avoid decluttering and using the button card templates because lovelace_gen doesn't need them
i know
so translating it will be difficult
probably i'll start with my colour picker cards
not to mention, I have a card in between that builds views dynamically, which I constantly forget how it works
If you want to use lovelace gen, i suggest learning jinja first.
i looked at your TV remote cards
That one doesn't really use lovelace gen too much
the card that displays the quick light effects doens't use lovelace_Gen too much either
so, you should be able to take that entire quick ligh teffect card and paste it.
you just need to take the equations for the RGB values and use them in an automation
also, you'll have to remove the {%raw%} and {%endraw%} that was needed for lovelace gen
yah thats nice
i'm very happy with this one - probably way too many lines of code
but still it works
and for a "stupid" sales guy not too bad
btw, those pictures in my config are way out of date
i got that
like 3 years out of date
haha
i understand, time is an issue with everyone
but it is because of people like you, that HA has become what it is !
i'm now going to try to replicate your cards and see how it goes
@mighty ledge for the slider what are you starting values ?
thanks - you took Kelvin and not merid
yah because that's what the 'stupid' device uses as a seed value
I like the stupid device, but it required backflips to get the quick lighting effects to work
the --paper-item-icon-color variable, can only be used within the card ?
ya
Is there a way to capitalise (sentence case) the output of a sensor via a template sensor?, eg "rainy" to "Rainy"
Other than, just doing "if, elif elif"
{{ ‘foo bar’|title }} capitalizes every word, but not what I would call ‘sentence case’
title will do every word
that could work. i'll have a look
oh okay, i'll use that instead
just depends on what you actually want. both have their uses
'foo bar'|title -> Foo Bar
'foo bar'|capitalize -> Foo bar
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
that's a default filter of jinja2
aah okay. I'll defo have a look through then.
anyone using mqtt_room?
#integrations-archived probably
tks
I have this template: {{ as_timestamp(states("sensor.tide2mqtt_6_time")) | timestamp_custom("%A @ %H:%M") | replace("@"," " )}} rendering this: Thursday 16:43. How can I add one hour to the time rendered?
a timestamp is in seconds, so add 3600 before calling timestamp_custom()
The time correct or is it off by the timezone?
Off by the timezone, yes...
{{ as_timestamp(states("sensor.tide2mqtt_6_time")) | timestamp_custom("%A %H:%M", False) }}
no, it treats the timestamp as utc
Ah! It works! Thanks! 😉
np
How can I get state of a entity using variable? Something like this.
url: "http://192.168.1.199/api/start/zone/ {{ states('input_select.zonenumber') }}?time={{states('input_number.zone{{ states('input_select.zonenumber') }}timer')}}"
you don't nest {{ }} like that
url: "http://192.168.1.199/api/start/zone/{{ states('input_select.zonenumber') }}?time={{states('input_number.zone' ~ states('input_select.zonenumber') ~ 'timer')}}"
something like that
It's working! Thank you very much 🙂
good, I was trying to figure out how to test it with the least amount of screwing around 🙂
My job to test 🙂 Noobies should be able to spend time trying your advice so you don't waste yours!
template section shouldve worked fine, wouldnt it? with a {% set ... %}
for what?
could have set a variable to avoid repeating states('input_select.zonenumber'), but it wouldn't have saved that much
for testing, i meant.
I wanted to test constructing the string and having states() evaluate it
which would have required having an entity that matched. anyway, testing was done
yeah, but that should work with set, shouldnt it? if you take a different entity and set/update the dict. oh yeah. I was just talking generally.
First edition of my attempt to control my Hunter irrigation controller using a ESP8266 and connecting through Hunter bus. I use this firmware https://github.com/ecodina/hunter-wifi https://i.imgur.com/RBXhMHl.png
Thank you for your help! Goodnight 🙂
Morning All, I think i need to make a template, but i'm not sure how, I have some sensors created from the garbage sensor plug in, and they have show as sensor.dishwasher_child1 sensor.dishwasher_child2 sensor.dishwasher_child3 Then in lovelace I just showa card with the child's name on bassed on if that sensor state is stoday, I'd like to be able to have a sensor or template called Dishwasher day that Show's the Friendly name of one of the above sensors, but i'm not sure how to do it.
Goodmorning! I am trying to set the minutes of a timer form the input_number. In developer tools template the result of this line minutes: "{{ states('input_number.zone_' ~ states('input_select.zonenumber') ~ 'timer') | int }}" its correct minutes: "24" but when I press check config i get Invalid config for [timer]: expected float for dictionary value @ data['timer']['irrigationtimer']['duration']['minutes']. Got "{{ states('input_number.zone' ~ states('input_select.zonenumber') ~ '_timer') | int }}". (See /config/configuration.yaml, line 376). \
inputnumber.zone should probably be input_number.zone Also you may need |float instead of |int.
I tried float and it's the same resutl. The config is right (auto-format maybe?) minutes: "{{ states('input_number.zone_' ~ states('input_select.zonenumber') ~ '_timer') | int }}"
The above is input_number.zone
int reports without decimals
enter the error message between code tags to avoid the auto formatting (3 backticks `)
That field doesn’t accept templates
@gleaming citrus posted a code wall, it is moved here --> https://paste.ubuntu.com/p/NgZ5P6fD8P/
You can’t template a configuration unless the configuration states that it accepts templates. That field does not.
Ok, understood! I bypassed my problem using an automation.
Hello, I am sorry for a newbie question. I want to create a template to count the number of persons inside the house into a sensor. Anyone did something similarly ?
number of what?
Number of persons inside the home based on presence detection iOS app or/and unify
you should start using the forums as a resource. This has been covered many times.
hi everyone. Can someone please help me with a scrape platform? Trying to get a value of the first line (0 in this case)
<td class="COL5 NET"><span>0</span></td>
What have you tried?
Currently I am getting the value through
select: ".COL5.NET"
index: 37
Just thought there is a better way. I can index on DAILY-CASES class, but I do not know how to do a subcall in the same select
Subcall? Do you mean children?
I looked at examples here
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors
but I get underfined value when I try to use select on multiple
yes
Your current select will find all matching nodes that have both class='COL5' and class='NET' because there is no space between them. If you want to specify a parent/child relationship, you include a space. Something like this should pick up the nodes that have those classes and are children of the first table:
select: ".DAILY-CASES .COL5.NET"
there are multiple tables on the page called <table class="DAILY-CASES">
I am trying to get the values from the first line
I tried but got underfined
Ah... so all the tables are the same class too. That's terrible design and one of the things that makes scraping annoying.
yeah. I am dealing with it by using indexes, but at the moment just trial and error to get the right one just on COL5.NET
I don't think there's a better way based on their design. It's also risky, since they might change the order of the rows/cells and your index will be incorrect.
If there's another source for the same data, I would suggest using another site.
its the best I have 🙂
I was hoping to get like the whole html data for the table and use that
I have the following template in use to determine which covers to open in case of upcoming rain: {{ expand('group.screens')|selectattr('state', '==', 'closed') | map(attribute='name') | list }}
However, these covers on report closed when they are completely they are eg 50% closed, they will report open, but also in those cases I want to open them completely
I tried to change the template so it works with the attribute current_position but I'm not sure how to do that
Somethink like this does not work {{ expand('group.screens')|selectattr('current_position', '!=', 0.0) | map(attribute='name') | list }}
selectattr('attributes.current_position', 'test', 'testvalue')
what I want is to show all covers which do have current_position: 0.0
selectattr('attributes.current_position', 'eq', 0)
This was not true, what I actually wanted was to show all covers with current_position not equal to 100.0, but with this new knowledge I could come to this: selectattr('attributes.current_position', '!=', 100)
Hello everyone!
I am trying to create a floorplan with WLED item and I cannot apply a filter CSS option for changing the light color on the floorplan.
Here is my image item: https://pastebin.com/4VcHn6SD
I've also tryied to use the following for the filter setting: https://pastebin.com/9kj31rw3 (I checked it on the developer-tools/template page and it returns the following result: hue-rotate(37.647deg)
Anyway, there is no filter css attribute in the result at all.
But it works fine if I set up this option manually, eg filter: hue-rotate(45deg)
Can anyone suggest me anything or tell me what I am doing wrong?
sounds like something for #frontend-archived
Should I delete it here and add in the frontend?
should definitely post there as there probably won't be anyone in here that can help. deleting is up to you
Thank you
There's this pinned message in #zwave-archived. #zwave-archived message
Would this work to use it as a trigger and get notified when a node goes dead?
- platform: template
value_template: "{{states|selectattr('entity_id', 'search', 'node_status')|selectattr('state', '==', 'dead')|list|count}}"
condition:
- condition: template
value_template: "{{ trigger.to_state.state != 0 }}"
- condition: template
value_template: "{{ trigger.from_state.state != 0 }}"
- condition: template
value_template: "{{ trigger.to_state.state != trigger.from_state.state }}"```
A template trigger should evaluate totrue or false. Your template seems to evaluate to a number.
Compare the result to another number to return a boolean. e.g. count > 0
ok great, thanks. Didn't recall that it should evaluate to true or false.
"{{states|selectattr('entity_id', 'search', 'node_status')|selectattr('state', '==', 'dead')|list|count > 0}}" with this i can also get rid of 2 of the conditions.
could I use message: "Node {{ trigger.entity_id }} has died" in the data field of the action?
Doubtful. The trigger isn't an entity.
These are the fields available for templating when working with automations: https://www.home-assistant.io/docs/automation/templating/
The fields available depend on the trigger type.
My guess... you'd have to come up with a template that lists the dead entities... which shouldn't be too hard, since it's basically a tweaked version of your trigger 😉
ok thanks for the pointer.
even for a template, some entity_id state change caused the trigger
and trigger.entity_id is valid for a template
Ah, noice
is there an attribute that can be used to identify devices sourced from a particular integration in a template (shelly integration for example?)
the domain / type of devices is not unique to the integration
No
thanks @dreamy sinew , I scoured documentation and could not locate such item.
this may be interesting if/when it's merged: https://github.com/home-assistant/core/pull/53131
Hey folks - I'm looking to make a REST sensor to chart river flow rate from USGS. The rate is BURIED in the JSON response, and I've not been able to figure out the proper path for the value_template. Anyone handy at extracting JSON?
If anyone is feeling up to it, here is a copy of what I have in my Dev>Templates for testing/trying to extract: https://pastebin.com/X5N9jinF
{{ (flow_rate_json|from_json).value.timeSeries[0]['values'][0].value[0].value }}
.values is a function keyword and causes issues. need to either use ['values'] or .get('values')
@cinder lotus 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.
@cinder lotus posted a code wall, it is moved here --> https://paste.ubuntu.com/p/KwyfYccPSN/
@cinder lotus posted a code wall, it is moved here --> https://paste.ubuntu.com/p/4B3rKNqfsq/
@cinder lotus 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.
@cinder lotus posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Y3ZJ9Qtdn3/
WTx is going on here. I'm not able to post. Always get a message 'Virus detected' by HassBot
@cinder lotus posted a code wall, it is moved here --> https://paste.ubuntu.com/p/tZymHDfp69/
My post does not contain any link 😫
Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).
Please take the time now to review all of the rules and references in #rules.
And for pictures? Not allowed here...
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images.
And if I'd like to show the result of Developer Tools - States..
6 lots of spam in only a few minutes. That's gotta be a new record.
Show it using text then. Copy/paste is a thing.
If you don't like the rules, you don't have to use this server 🤷♂️
And pictures are really awful for sharing text. They're hard to read on small devices and they're difficult to edit in cases where we want to tweak something for you.
If you want support, share the attributes using a text sharing site.
The rule is there to keep huge posts out, just use pastebin. Anways to answer your question...
sensor:
- platform: template
sensors:
vandaag_actueel:
value_template: "{{ state_attr('weather.buienradar', 'temperature') }}"
friendly_name: Vandaag actueel
Many thanks @mighty ledge, this works. Highly appreciated. I agree there should be rules but anyway, my opinion remains that they are too strict here. Use many channels (esphome, tasmota) and they don't have so many restrictions. It's not user-friendly anymore.
Unfortunately for you, you're not the one setting the rules 🤷♂️
That's right but I may have my opinion, right? About 6 months ago this was all allowed
👋
Na, it’s been this way for the past few years. But thank you for your feedback.
Seems, very quitte now 😉
Hello. Which entity use to make "I'm home!" switch? Idea is to make such button on Lovelace , which can switch other switches, like water pump, motion sensor, etc. And can be switched manually via GUI or auto with some presence detection.
Input boolean helper with automations
Ok. Thanks.
And what's the trigger platform then? State?
yea
Hi Guys, Need your help on this please
21:55:29.775 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:29","APDS9960":{"Down":1}} 21:55:33.050 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:33","APDS9960":{"Up":1}} 21:55:37.584 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:37","APDS9960":{"Left":1}}
The adobe is how my sensor gives me response for which I've created the mqtt sensor as below and this gives me value as Gesture Sensor: {'Left':1}. how can I extract value which shows me only the direction like Gesture Sensor: Up or Gesture Sensor: Down
- platform: mqtt name: "Gesture Sensor" state_topic: "tele/gesture/SENSOR" value_template: "{{ value_json.APDS9960 }}"
@mighty snowhx with that I'm getting a "TypeError: the JSON object must be str, bytes or bytearray, not dict" in the test template.
@dreamy sinew ^
Wrap your sample json in quotes
Like this "{ my sample json }" or this {" my sample json "}
niether seem to work - both give me a "TemplateSyntaxError: expected token 'end of statement block', got 'name'" error. Name is the first key in the sample json
{% set my_json = '{}' %}
i want to create a new template sensor just to discard erroneous values from the real sensor.. i'm getting a lot of negative values, so these need to be filtered out
how can i do that?
and do i need to use an automation for that?
so that every time the sensor changes, then update the template sensor?
Template sensors update whenever the entities they contain change. So no, you do not need an automation.
You don't need a template sensor to remove negative values. You can use the filter integration. Use the range filter with a lower bound of 0. https://www.home-assistant.io/integrations/filter/
value_template: "{{ (states('sensor.p1_rechtstreeks_verbruik') | round(2)) / (states('sensor.p1_totaal_verbruik') | round(2)) * 100 | round(1) }}"
Why does my code ignore the round(1) part? The result of this code is: 51.576292559
You are rounding the number 100: 100 | round(1) use some brackets
Aha I see! Thank you @fossil venture
Home Assistant is not reading My soil moisture sensor after I had introduced a template to limit the display of values. Could you please help me?
ok Thankyou
What would be the best way to "update entity" after something is done?
In this case my blinds doesn't report back state if i dont update the entity.
A script that open - waits - updates?
A switch in Nodered?
Or can i do this with a template?
How are your blinds integrated into Home Assistant? I have the same issue with my TV. Because its state is polled it takes forever to report back that it is on after I turn it on. So I do this in the turn on script https://paste.ubuntu.com/p/GMBWkKfMNh/ You could do something similar either in a template cover or in a script.
Can i set the state on the template entity some how?
Guys, any one help me on this please !!
21:55:29.775 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:29","APDS9960":{"Down":1}} 21:55:33.050 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:33","APDS9960":{"Up":1}} 21:55:37.584 MQT: tele/gesture/SENSOR = {"Time":"2021-07-23T21:55:37","APDS9960":{"Left":1}}
The adobe is how my sensor gives me response for which I've created the mqtt sensor as below and this gives me value as Gesture Sensor: {'Left':1}. how can I extract value which shows me only the direction like Gesture Sensor: Up or Gesture Sensor: Down
- platform: mqtt name: "Gesture Sensor" state_topic: "tele/gesture/SENSOR" value_template: "{{ value_json.APDS9960 }}"
This should do the trick:
{{ value_json.APDS9960 | list | first }}
Thanks you so much @ivory delta This worked 😇
Not sure what you mean by this.
I found a python script that did it. But i threw it all out and just went with a "if state change, wait 30 sec, update entity."
any reason that some devices continue to float in the topology map even when added right next to a router with "add devices through this device"?
It's probably just that they didn't report in when the map was being built. If they work, it's no big deal. The mesh self-heals anyway.
I'm having trouble understanding the documentation. how do I check if a string contains a literal string. I'm not seeing an .contains or .indexof
ah! thank you
you can also do this:
{% for i in states.switch if 'keypad' in i.entity_id %}
- {{ i.entity_id }}
{% endfor %}
{% for i in states.switch if i.entity_id.startswith(‘foo’) %}
- {{ i.entity_id }}
{% endfor %}
somebody really likes { and %
@timber cliff if this is for your calendar no school question. Using Google cal I have a calendar entity based on a string in the cal entry.
I am very new to templates and HA. Is that a helper?
something like
yaml```
- id: '1111111111111'
alias: No School Today
description: ''
trigger:- platform: time
at: 06:00
condition: - condition: template
value_template: '{{ "NO SCHOOL" in states.calendar.schooCalendar.attributes.message|upper }}'
action: - service: input_boolean.turn_on
target:
entity_id: input_boolean.no_school_today
mode: single
- platform: time
Jinja templates are surrounded by {{ }} and it looks like you have a mismatched parenthesis. A better template would be this: {{ "NO SCHOOL" in state_attr('calendar.school_calendar', 'message')|upper }}, or something similar
better yet, just create a template binary_sensor with that template and it will automatically be true or false without the need for an automation
What's that look like?
what does what look like?
a template binary_sensor? https://www.home-assistant.io/integrations/template/
gotta restart every time you add one eh?
Not if you have at least one.
-> Server Controls
I see that. thanks.
Is there an easy way to get the value of a sensors data yesterday at 23:59h?
I have solar panels and I would like to see how much power they produced. It resets every day at 0.00h. So I'd like to see the value it had yesterday at 23:59h.
Is it possible to use a template to check the status of a lamp and if it is on to send the service call in the next line to turn it off?
can command be sent here? ```
I'm able to get the on/off readout of the lamp but just not sure if I can even send the call because none of what I am trying is working or I am not quite sure of the format
You don't need a template for that, https://paste.ubuntu.com/p/KxrWZyZN8m/
I suggest you have a read of this https://www.home-assistant.io/docs/scripts the syntax applies to automation actions as well as scripts.
Hey Guys!
is it possible to specify multiple actions via templating in an Automation?
Like this:
- service: delay
hours: 1
minutes: 0
seconds: 0
- service: switch.turn_on
target:
entity_id: switch.mosquito_killer
{% else %}
service: switch.turn_off
target:
entity_id: switch.mosquito_killer
{% endif %}```
Templates must only be on the value side of a key: value pair. Use a script to contain your multiple actions. Or use the choose action to conditionally run a sequence of actions: https://www.home-assistant.io/docs/scripts#choose-a-group-of-actions
WOW Choose looks promising! Thanks for the quick answer!
i have this template. {{ is_state_attr('climate.airco_slaapkamer', 'fan_mode', 'High') }}
Is there a way to check if attr is not a specific value. i tried is_not_state_attr but offcourse that would be too easy lol
Use state_attr() != 'xyz'
Thanks ill try that. i fixed it now by doing this:
conditions:
- "{{ is_state_attr('climate.airco_slaapkamer', 'swing_mode', 'Up') }}"
- "{{ is_state_attr('climate.airco_slaapkamer', 'fan_mode', 'Low') }}"```
Hi everyone, i just updated hassio to 2021.7.4 and im experiencing issues with the light templates, it seems like the new way hassio is handling white and color brightness separately is giving me issues, i tried finding a solution but im stuck due to the light template not supporting rgbw values as color template (?) witch is the only supported mode my strip has.
Has anyone else experienced something similar and found a solution ?
i have a template that writes an entity _input_text.patiodoortime, but the value clears itself every time HAS restarts. how can i make it persistent across restarts? ex;
- service: input_text.set_value
data:
value: |-
{{ 'Patio Door -
{}'.format(now().strftime('%a, %b %d at %I:%M %p')) }}
entity_id: input_text.patiodoortime
It should retain the value if you didn’t set an initial value: https://www.home-assistant.io/integrations/input_text/#restore-state
Hi, can I ask to guide me for one template. I have raindrop sensor , which is programmed with esphome and have entity , which show me Voltage (1.00, 0.78 and so on). I want to have binary sensor , when the sensor is 1.00 V to be off in other cases to be on.
{{ states('sensor.boiler_flood_2')|float == 1.00 }}
{{ states('sensor.boiler_flood_2')|float != 1.00 }}
What is the proper way to get a last_updated for a binary sensor?
state_attr(“binary_sensor.mysensor”, “last_updated”)
Or
states.binary_sensor.mysensor.last_updated
The latter, because it’s not an attribute: https://www.home-assistant.io/docs/configuration/state_object/
Thank you. Wish there was a ui for this
I’m having a lot of trouble stringing this together..
I just want to have a yes/no of whether another sensor has been opened today.
It was suggested to use last_updated, but after testing, it looks like that tracks Unavailable or closed, which I don’t want; I specially would like whether the sensor has been open today. Is there a combination of tests I can use for this? I’ve been going through several doc pages but cannot crack it
A trivial way is an automation that triggers when it’s open and sets an input_boolean and another that clears it at midnight
Guess that will have to be it. Sucks that you have to go through three separate sections to do this; HA definitely needs self-contained virtual entities. This was a trivial thing to do in SmartThings.
Thank you for the response.
i have 2 different automation using the same wait_template, but seems to only work with the first automation to trigger. Is this a limitation of wait_template?
No
i use this in both automation - wait_template: "{{ states('sensor.powerwall_charge') | int < 90 }}"
but the 2nd automation never goes to the next step
wait_template is pretty straightforward:
WAIT TEMPLATE
This action evaluates the template, and if true, the script will continue. If not, then it will wait until it is true.
Review the automaton trace
this is from the trace ```Executed: July 25, 2021, 12:35:06 PM
Result:
wait:
remaining: null
completed: false
i use the same wait_template in both automation
the other automation show completed: true
I like using a persistent_notification to tell me the value of something before I check it
It might be fluctuating and just a timing issue
i'll take a look at that.. the sensor dropped to below 80 when i noticed the wait_template didn't complete (automation triggers at 95 and supposed to turn off when below 90)
(action to turn off when below 90 via wait_template)
I don’t use them often, but I don’t see why it wouldn’t work. It’s not waiting for a trigger, just an instantaneous test should work
it's just odd that it work on automation A, but not B. Only difference is A triggers at 93, B triggers at 95 and target different entity to turn on. Otherwise, the 2 automation is exactly the same.
~share them and perhaps there’s another clue
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.
@fast oracle posted a code wall, it is moved here --> https://paste.ubuntu.com/p/W3YyvcD8qV/
I recommend creating a persistent notification just before the wait_template that isn't passing. For what it's worth, this test works as expected: https://pastebin.ubuntu.com/p/rWsXSQcbmT/
thanks.. i'll try it out
I am trying to read the RGB_color from a virtual entity, and when that virtual entity changes, update the equivalent actual entity
got as far as the following template {{ state_attr('light.virtual_uplights','rgb_color') }}
trying to figure out how to set the real uplight to match
ok, so I have figured out how to rewrite the template to get the correct list format.
but this is not working for the setting the physical lamps:
type: turn_on
device_id: d77aa2e2df31f76210edfb049d7a16db
entity_id: light.002007915ccf7f498b41
domain: light
rgb_color: '{{ states("sensor.set_color") }}'
it does not like the rgb_color line
does not like
🤔
Please don't say I have an error or describe an error. Share the whole actual error message so we can help you.
Message malformed: extra keys not allowed @ data['rgb_color']
Then it's not allowed for a device. Use entities and services like a sane person.
One of the problems with the device stuff is that it's not well documented.
that seems to have accepted the template. But the automation does not trigger on any changes to the virtual entity
So it's time for the standard automation testing.
See the pins back in #automations-archived
ok, swinging over to automations at this point, but looks like manually triggering the automation works.
Whats the simplest way to get an timer counting up when a smartplug is turned on? I want to display it on my lovelace ui but its way harder to accomplish then i thought. 😄
currently i build an sensor with history_stats which works but now i have the problem with resetting it after turning the smart plug off again.
@plain mural posted a code wall, it is moved here --> https://paste.ubuntu.com/p/RWZjTbRK2t/
Hello,
I want to have an overview over gas prices in the area around me, so I created two groups (Super E5 and Diesel) for. Works so far, but does not look that good.
Best would be to have a table that can be sorted which contains columns for city, brand, e5 and diesel, is that possible?
Current markdown looks like: (Code see Paste by HassBot)
That can only be done with a custom frontend card. Having dynamic sorting otherwise would be very difficult to do with jinja.
oh, damn, i hoped for a quicker solution. Can I use two groups then in the same table? See paste above, there i have the diesel list after the gas list even if the gas stations are the same
you'd have to tabulate the information then display it after collecting what you want
Oh, i guess im too new for that at the moment
Are there NEW and OLD ways to implement Template Entities? I just bumped into the limitation where you can't use Template Integration in packages. I'm reading some refer to these as "legacy templates" ? What is the NEW way to setup template entities ?
Yes there is a new way, it's covered in the docs extensively. The 'legacy' way still works and works with packages.
@mighty ledge Any chance you have a link to a doc that mentioned "legacy" vs "new way" so I can understand which is which?
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- HA before 0.115: rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
that's wrong
Integrations integrate Home Assistant with devices or services, or provide functionality within Home Assistant. Add-ons provide additional software or services, which an integration could possibility integrate with. Add-ons are for Home Assistant OS and Supervised only, other install methods can install software other ways.
just go to the integration docs and search template, it's covered there
click on the one that's just labeled 'template'
@mighty ledge yes I've read both docs...
https://www.home-assistant.io/integrations/template/#legacy-binary-sensor-configuration-format
and
https://www.home-assistant.io/docs/configuration/templating/
From what I gather... the "OLD" way is like...
sensor:
- platform: template
and the new way is using the template integration:
template:
- sensor:
yep
But the new way doesn't work in packages?
nope
before you complain, the old way isn't going away
so stick with the old way.
Can you tell this has come up 100000 times 😆
I was actually wondering why there isn't support for packages in the new format. I'm a bit confused at times why it seems there is an "either/or" approach to YAML vs UI config in HA. I went with packages so that it would be easier to share as well as backup. (snapshots arent as accessible)
Would think this is the format most power users would prefer.
It's 100% the opposite way I think.
Sorry?
how do you organize than and share config with others?
I organize via files
just not packages
anyways, packages are ham-fisted into home assistant. A major refactor is needed in order to properly support packages everywhere, including template.
So, you'll have to wait for the new template style to be added to packaging
very interested if there is a better way to organize as an alternative to packages
Would be helpful to see an example config structure that just uses files and not packages
the problem I have with packages is this: If I have a problem with a cover, where do I look?
essentially its all organized by "integration" and not by logical buckets?
Well, I now need ot remember where I thought the cover should be packaged, then I need to go search for it
with an organization based on integration, I know exactly where it is. Immediately.
logical buckets aren't logical when editing though
also, i means you need to have 2 sections of the same file open in different editors when editing or making changes
fair. Packages is how I think. If I have an issue with something security related (cameras, locks, alarm) its all in security.yaml including all their templates, automations etc.
what happens when you use a template that's used in 2 different packages?
seems like you'd create a new package, then forget about said package, and then spend an hour looking for it
hasn't happened yet. But likely there are going to be edge cases. Most importantly, I'm more inclined to use what is closest to the direction that the core is going. So if the plan is to walk away from packages.... then I'd likely do so as well.
I don't think that is the plan, but it's spagetti code currently so it's not 100% safe
but so many people use it that I doubt itwould go away
K... thanks for the incite.
so, it would probably be a major refactor at some point, then it would be added everywhere
but, currently, there are no maintainers for that section of code. So I'm not sure when any of this will happen.
is either way preferable? {{ state_attr("calendar.school","message") }} or states.calendar.school.attributes.message
the former. it's in the docs
big yellow warning box: https://www.home-assistant.io/docs/configuration/templating/#states
one day I'll read the docs. But seriously there is a lot of information to consume. I appreciate the humans here.
and the bots.
I know I'm being dense but I've attempted many times to use the wiki to figure this out. how do I get the "time" of 2hrs ago
now().something? (hours=2)
?
timedelta doesn't seem to work
It will
do i do it like this? end: "{{ now().replace(hour=0, minute=0, second=0) }}"
duration:
hours: 24
just use now() as end
?
{{ now() - timedelta(hours=2) }}
Thanks Rob!
Hey guys, does anyone know how to pass a predefined variable to be used in templates
- platform: wake_on_lan
name: "RPI"
mac: "DC:A6:22:13::"
host: "192.168.1.43"
turn_off:
service: shell_command.ssh_cmd
data_template:
username: pi
ip: >
{{ host }}
cmd: 'sudo reboot'
I want to pass the host to ip so it doesn't repeat itself in the data_template but it just doesn't work
No, no one knows how because that option does not accept templates. Very few integration configuration options do. And if they do, they say so explicitly in the documentation. Templates are mostly used for services and service data in automations and scripts.
Thanks Tom. I guess I was trying something not possible. I will just repeat the ips then. 👍
You could define and use a secret host: !secret my_ip_address but that's longer than typing out the ip address.
yep. typing it is then 😄
Actually i thought you meant templating the host: option. You can actually use a template in the turn_off action. The problems with using {{ state_attr('switch.rpi', 'host') }} are twofold, 1) I don't know if that attribute actually exists, and 2) Even if it does exist after the WOL switch is initialised, it wont exist while the WOL switch is initialising, which is when it is needed.
as someone who's complete config is organized in (75) packages, I can assure you forgetting a package is not very likely to happen. And in the edge case a config item (like a template, or maybe an automation, heck a global script even) should be needed in more than 1 package, creating a 'meta' package for those is very easy. And keeps the logic of the complete config in tact. Only exceptions I encountered are the browser_mod settings and the 'new' template: integration. Not sure why we would need a 'major refactor' just for those, though appreciative of the efforts it would take to only support packages for template: alone.
and if one is really lost in their own config, a global search in the editor is very quick 😉
Trying to wrap my head around templates for effect_list. Monitoring the MQTT device, it publishes "rgb_cycle" or "color" or "white", but to set it, I set with 0,1,2. So Right now, I can have an effect_list with the correct names but doesn't push the right data to the device, or I can set the list as "0,1,2" but the device status shows the string, not the number... so it is broken either way. I'm having problems figuring out where/how to set the "0 == rgb_cycle" and "1 == color" settings
You can map values to strings. See this example: https://community.home-assistant.io/t/vacuum-send-command-help-with-rooms-in-command-spot-area/321342/2
still doesn't change the fact taht I don't think in features. I think with domains which is how the config is naturally set up. There's pretty much nothing you can say to get me on board with packages. It's a level of management that I don't want to deal with.
sure, and please have it your way, totally appreciated. then again, that needn't necessarily be the absolute truth for HA. Many users use packages and organize the config around their sense of logic.. To me pushing the domain concept as central to the organization is not how I feel my surrounding.
thanks @fossil venture ! I was looking for a mapper and just could not find the right keyword (granted, i wasn't thinking of the word "mapper")... but this still doesn't quite solve it. The command to send to the mqtt device is with a number, but the stat/%topic%/effect output is in the string... so if I define the strings with the mapper, it will still have a problem with reading the current state, or can I set a mapper for both the input select as well as the current state value?
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.
hey guys how can I fix these errors 'sensor' is undefined when rendering '{{ sensor.garage_smoke_battery_level }}' https://paste.ubuntu.com/p/V6yQjY3rSM/
what am I missing
You're missing the actual code. You just placed the entity_id in there. Take a look at any example and compare it to what you wrote
every one of those templates has a basic error in them
how do you get a state out of an entity?
okay so looking at the template guide this is what I have now {{ states('sensor.garage_smoke.attributes.battery_level') }}. I am no longer getting an error, but now I am getting this ```Result type: string
unknown
This template listens for the following state changed events:
Entity: sensor.garage_smoke.attributes.battery_level```
what you have there is not an entity_id
is the unkown a limitation of the device or my understanding of templates. Okay can you share an example with me?
the unknown is because you passed something that isn't an entity id to states() which is expecting an entity_id
this is the entity_id of the device sensor.garage_smoke_detector_battery
ok, that's step one
so this is my new template {{ states('sensor.garage_smoke_detector_battery') }}
that will get you the state of that entity
so it should be this `{{ state_attr('sensor.garage_smoke_detector_battery') }}, but that give me an error in Dev/Template.
UndefinedError: 'states_attr' is undefined
so I changed the entity id and I now hove a reading . {{ states('sensor.garage_smoke_battery_level') }}
but this how not triggered an error during the config check process
Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states('sensor.garage_smoke_battery_level')", None)])"
in "/config/packages/emergency.yaml", line 102, column 0
With no context on where you're using the template how the heck do you expect anybody to be able to help you?
I am not yet using the template anywhere, current I am trying to solve an warning that has appeared in my log almost 7000 times https://paste.ubuntu.com/p/dr4FVxFvVy/
I have trying to understand why this is throwing this error and correct the problem.
I plan to eventually use the output in some notification about changing batteries.
Those templates are coming from somewhere in your config
so while I was doing some research I found this thread https://community.home-assistant.io/t/howto-create-battery-alert-without-creating-a-template-for-every-device/30576/7. Since I want to be notified when ever any device has a low battery like the author mentioned, then it does make sense to step back from the individual device and take a look at it from all devices and how to get notified. Anyone else implemented/ing something similar?
Hi, is there a way to get in a template, from HA's config, the working local HA url (http://x.x.x.x:8123) and the User Profile Language selected?
Not directly in a template. Maybe you can set up some kind of sensor that exposes that (head to #integrations-archived for that).
I found the base_url in the API, could access it via rest command. But not the language unfortunately. I'll ask in integrations, thanks.
base_url was eliminated last year
hass.axel.dom:8123/api/discovery_info
{"uuid": "e7ce4a1xxxxxxxxxxxxxxxxxxce71d098", "base_url": "https://k37yyyyyyyyyyyyyyy8mje8x88a.ui.nabu.casa", "external_url": "https://k37y9yyyyyyyyyyh78mje8x88a.ui.nabu.casa", "internal_url": "http://hass.axel.dom:8123", "location_name": "Casa Del Prete", "installation_type": "Home Assistant OS", "requires_api_password": true, "version": "2021.8.0b1", "currency": null}
base_url, internal_url, external_url
I need to access the internal_url from a template but I guess I'll need to do an API call with a rest command
I couldn't find the language setting in the API though
Hello, how to get source of input of my tv?
`is_state('media_player.kitchen.source', 'Tuner')'
I know how to ask if device in some state => True/False, but I really need to get the actual source name
for example Spotifyor Plex..
I tried this but I have still None : {{ state_attr('media_player.livingroom_tv', 'source') }}
I want to get the status out the follow API/JSON output {"status":"OK","meta":{"time":"2021-07-29T16:19:09","tid":"1627575549_MtLg","version":"1.0","token_limit":2000,"token_remaining":1019,"last_active":"2021-07-29T16:19:09","token_reset":"2021-07-30T00:00:00"},"data":{"sensor_data":[{"id":13169891,"time":"2021-07-29T16:04:02","local_date":"2021-07-29","local_time":"19:04:02","moisture":14,"sunlight":0.832,"celsius":28.0786,"fahrenheit":82.5415}
.status
i have the following code
- platform: rest
name: whisperer
json_attributes_path: "$.[0]"
json_attributes:
- moisture
- sunlight
- celsius
resource_template: "http://www.api.com"
scan_interval: 3600
value_template: "{{ value_json.status[0].status }}"
but don't get the status
why are you treating status as a list?
"{{ value_json.status }}"
.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.
And what do you get from {{ value }}?
all nothing
Then you're probably getting nothing back from the command. Where are you running it from when you see it work?
Then there's a chance it's not running where you think it is. But this is a topic for #integrations-archived, since the problem isn't with your template.
i see , what do u mean by where you think it is ?
Well first... move to the right channel.
on it 🙂 doing now
I created a template to know if a certain spot is covered by my west-facing awning or exposed to the sun. https://hastebin.com/qewafelebe.cpp
y0,z0 mark the position of the awning with respect to the spot when closed
y1,z1 mark the position of the awning with respect to the spot when fully open
yc,zc mark the position of the house roof (which also can cast a shadow on that spot) with respect to the spot
It is working, so I hope it could be useful for someone else.
Also, any comments on how to improve it would be really welcome. Please do @ mention me.
I think you just made it more complicated using dictionaries and you made it lengthier and harder to read and edit. Also, you made some unnecessary float casts. Attributes hold their type and don't need to be cast because they are not strings.
template:
- binary_sensor:
- name: "Toldo1 sol"
state: |-
{% set y0 = state_attr("cover.toldo1","y0") %}
{% set y1 = state_attr("cover.toldo1","y1") %}
{% set yc = state_attr("cover.toldo1","yc") %}
{% set z0 = state_attr("cover.toldo1","z0") %}
{% set z1 = state_attr("cover.toldo1","z1") %}
{% set zc = state_attr("cover.toldo1","zc") %}
{% set pos = state_attr("cover.toldo1","current_position")/100.0 %}
{% set elev = pi*state_attr("sun.sun","elevation")/180.0 %}
{% set azim = pi*state_attr("sun.sun","azimuth")/180.0 %}
{% set y = y0*(1-pos) + y1*pos %}
{% set z = z0*(1-pos) + z1*pos %}
{{ elev > 0 and
(y*sin(elev)/z - cos(elev)*sin(azim) > 0) and
(yc*sin(elev)/zc - cos(elev)*sin(azim) > 0)
}}
Thank you! Yes, that's indeed easier to read. The float casts, however, were necessary, as I added those attributes as customizations (probably not the best way? but then it works regardless of what technology is used for that particular cover [tasmota, esphome]), and realized they were stored as strings.
Next thing I did is I created an automation that makes sure that the spot is actually in the shadow at all times, by slowly opening the awning as needed, using those binary sensors in automations.
Then I turned the automation into a blueprint (so that I could more easily change the logic for my three awnings)
But the template binary sensors... I don't see how I can "factor them away"
You can factor them away by putting all the constants into variables in the automation and performing the calc live as a template trigger.
That (variables in template triggers in automations) does not work - I tried
It works in a template in the actions, but not in a template in the triggers, #blueprints-archived message
In conditions, I have not tried (I would need that to work too)
you need to use trigger_variables, but I"m not sure if they work with a normal template trigger.
{% set power = states.sensor | selectattr('attributes.unit_of_measurement', "equalto","W") | selectattr('attributes.device_class', "equalto","power") |map(attribute='state') |list %}
{% set powerTotal = 0.0 -%}
{% for value in power -%}
{% set powerTotal = powerTotal + value|float -%}
{% if loop.last -%}{{powerTotal}}{% endif -%}
{% endfor %}
it is not summing up powerTotal, what im doing wrong?
Trying to automatically get all values from all power sensors and sum their values up, thats my main goal so i can make a template sensor which has the sum of all power entities.
need to use namespacing
stuff in a loop can't affect stuff outside of a loop without namespace
Ahh thanks that was the only thing i needed for the fix 😄
You don't need namespace for that. You can map and calculate in 1 line:
{{ states.sensor | selectattr('attributes.unit_of_measurement', "equalto","W") | selectattr('attributes.device_class', "equalto","power") |map(attribute='state') | map('float') | list | sum }}
Theoretically yes, but later I do add some logic to only sum up all sensors which are lights and i do this via the firendly_name if it contains "Light". This sorting is easier in a for loop for me via if statements
you can still filter to find out if it contains light
But im doing this directly from brain to terminal without making any concepts, so it could be that a better solution exists for that case 🤪
| selectattr('attributes.friendly_name', 'search', 'Light')
The use cases for namespace are extremely small in the current version of home assistant
is search case sensitive?
it is
and 'match' is equivalent to startswith
so, namespace is barely needed unless dealing with datetimes
yeah i hope theres nothing named "ight" that isnt a light so then i can search without worrying witch casesensititvity😂 Thanks for the help
the domain is sensor cause which I created with a custom component for each light. So the other created power sensors e.g. my pc is also on that domain. But should work this way. Otherwise i can take the old ugly solution or i can introduce a manual naming convention for the sensors instead of letting the custom component create the friendlyname
Hi Guys
I'm trying to set a sensor which show me the battery in % from voltage I've tried the following, how ever this will give me wrong results as the Li-Ion battery min voltage is 3.2 that is it should tell me 0% and 4.2 is 100% how do it do it in a template, help please.
cube_battery_level: friendly_name: 'Battery Level' unit_of_measurement: "%" value_template: > {% set bat = states('sensor.power_cube_battery') | float %} {{ ((bat / 4.2) * 100) | round(1) }}
{{ ((bat - 3.2) * 100) | round(1) }}
Thanks much @inner mesa
Can I call a service in a template?
Thanks 😄
I haven't got a lux sensor in my bedroom so I was going to make a template sensor to act as one, but it would need to convert the light brightness value to lux, which I have in a function in pyscript. But I've just realised that I'm setting light_lux on the pyscript entity so the template sensor can track that
Until I get the lux sensor, of course
services don't return anything, so it's not possible to call one and get a result that you can use later. And only Jinja is supported in templates
Templating time... I give up...
I have a sensor (sensor.docker_adguard_up_time) that has a state in this format: 2021-07-31T22:38:16.301019+02:00. How can I calculate how long ago that is??
value_template: "{{ relative_time(states.sensor.docker_adguard_up_time.last_changed) }}" Try this @trail estuary
That is pretty close! I assume this doesnt actually look at the timestamp itself, only when it was last changed? So in thery I can use this with any sensor?
It outputs as 30 minutes right now. Does it add hours and days as time goes by? So for example 1 day 2 hours 12 minutes?
Brilliant! Thank you!! 😄
The only problem with that is of course that it will reset when I restart HA... That wont work....
Yes that's true, I was using it to check when was the last time any of my door or motion sensor was triggered and with every reboot it use to reset.
There's always pyscript (or python_script). It would be utterly trivial then
This {{(as_timestamp(now()) - as_timestamp(states.sensor.docker_adguard_up_time.state))}} gives me this: 3823.7006199359894. I am sure there is way to print that in a human readable format?
@sturdy rock posted a code wall, it is moved here --> https://paste.ubuntu.com/p/94WZWRf2mV/
and it gives output as 1 Day, 4 Hrs & 56 Mins
I'll give it a go! 😉 Thanks!
That worked perfectly! I get the logic behind but the formatting you use is magic!
i have a button containing motion icon. i am using custom button card. i want to use variable to change the color of the icon. i am using following code for this. but its not working. can anyone correct the code?
custom_fields:
motion:
- color: >
[[[ if (states.binary_sensor.hue_motion_sensor_1_motion.state === 'on') {return var(--primary-color)} ]]]
working code:
custom_fields:
motion:
- color: var(--primary-color)
I've hit some odd situations in which despite specifying an availability_template that should evaluate to false the value_template renders with bad data; I think there's a race condition and problem with evaluation order but I'm having a devil of a time chasing the flow of the code
To work around the issue is it sufficient to just return the string "unavailable" in the value_template or will that have side effects? While my template takes a number of inputs limiting with triggers has been successful
ended up figuring it out. It looks like a bug (either a doc bug or behavior bug, but in either case it's possible for the availability to be silently ignored): https://github.com/home-assistant/core/issues/53819
How would I return a dict from a sensor? I have this in DevTools https://paste.ubuntu.com/p/xcKSxCfJHk/, but cant figure how to create something like ['K': K, 'B': B] to be picked up by my scripts... Ideas? Background is I do a lot of the same calculations in many scripts/automations. It would be neater to have this done once and then reuse the sensor value/dict
a simple list like this {{ [K,B] }} is easy, but a dict? I guess I could always expect values are in the same order, but calling by name would be better
got it I think, please correct if can be done better; ```
{% set dict = {"Kelvin": K} %}
{{ dict }}
This was the result, but returns Unavailable in DevTools when called from States tab? What did I do wrong? https://paste.ubuntu.com/p/8xzjrFSPh6/
Have a read of this https://www.home-assistant.io/docs/configuration/templating/#tofrom-json
Thanks, modified {{ dict }} to {{ dict | to_json }}, and restarted HA, no change yet tho...
I get this in DevTools Template tab, so it seems to work somewhat at least? { "Brightness": 88, "Mireds": 286, "Kelvin": 3500, "Pod": "day" }
Looks like it is working to me.
Ok. Perhaps States tab can't show this? I'll give it a try in the script then. Thanks 🙂
The States tab should be able to.
So I thought, but it still reports as unavailable. Same result when tried to access it in a script. What else can be at fault here?
I made a small script with this declaration```
variables:
map: "{{ states('sensor.lad') }}"
brightness: "{{ map['brightness'] }}"
pod: "{{ map['pod'] }}"
Think I found it... 😦 Variables was defined in DevTools, forgot that when adding to configuration.yam, so unavailable was indeed correct. Thanks @fossil venture for the help
Thank you! I tried trigger_variables and a simple template trigger (outside my automation) and it worked perfectly. I have searched the documentation for those, and the only place I found them just tells you that templates in these variables are limited, but no explanation on how they are used or where they can be used. https://www.home-assistant.io/docs/automation/trigger/#trigger-variables
Hi. I noticed that my REST sensor with a value template updated the state every 3 minutes and write it to the Database. As the value doesn't change that much I do not need so much information.
So is there a way to prevent writing the state to the DB when old and new value are the same? I tried it already but it doesn't work 😦
Here is how it looks like: https://pastebin.com/2ghJLRx6
That's only the template, not the full sensor config. Share the whole thing.
im not sure if this is the right place. Is it possible to stream local music stored on the raspberrypi to a media player in the form of a playlist? Singel mp3 files work fine.
Templates? Nope, not the right place. You want #integrations-archived
thanks 🙂
Ok @ivory delta here is the whole sensor: https://pastebin.com/eA3xtMPg
But I think I just got it by myself as I added force_update = true
🤦♂️
Yeah, that was going to be my guess 😄
I have a group light.all_lights with all my light entities. I made a template to use a brightness slider only for the lights that are on from the light.all_light entity. For some reason soon as i adjust the slider all other lights from the group will become on. Anyone know what is wrong in my template? 🙂 https://pastebin.ubuntu.com/p/dcBvpw8Z24/
any idea how I cloud remove the duplicate entries in the madiadb now?
Why would you want to? Just let them expire naturally.
bacause the DB is grown to multiple GB of data -.-
And now you've figured out how to stop it growing so quickly. Those entries will disappear after a few days.
If it's filled your disk and you desperately need the space back, you can either delete the DB or you can go learn some SQL to delete specific things.
yes... was looking for a SQL that deletes entries with same states value of the same entity (but different time). To just keep the oldest... but didn't find one