#templates-archived
1 messages · Page 142 of 1
oh, didnt notice the edit. one sec
just refactored a bit
wasn't expecting a change, but still not getting any back from temp_bool
when just testing these very specific parts of the template
{% set temp_bool = states.input_boolean|selectattr('object_id', 'in', bools)|map(attribute="state")|list %}
{{ temp_bool }}```
You’ve mixed things up
Go back and revisit the example
Note that you have full entity_id in the first line and you’re checking object_id in the second
ahhhhh
ok
thank you
i made a small change to use a sensor entity for all_temps and this is exactly what I need. Just need to play around with last_updated/last_changed to calculate if its been in an on state for 10m
much appreciated for the guidance!
@inner mesa I think there might be something amiss with the loop logic. no matter which input_boolean I set to on, its always pulling the temp from the first sensor on the list.
It seems like the condition if logic on the for loops might be throwing off the index counter
Could be. You can just move the ‘if’ inside the loop
just tried, getting odd behavior still. will keep playing!
It was both the combo of moving the if into the loop + needing to start the loop at index0
{% if temp == 'on' %}
{% set ns.temps = ns.temps + [all_temps[loop.index0]] %}
{% endif %}```
yeah, I arrived at that too, but I think it's still broken
so far, it seems to be working as expected, by manually switching the input_booleans on/off
you're depending on the order in which the states are evaluated in each of the lists, and it might not align
worst case, you can just make the lists manually with the states of each entity, but that gets annoying fast and I was trying to avoid it.
if it's working for you, that's what matters. just keep that issue in mind
yes I noticed that during troubleshooting, that the new lists that were created are not the same order as how they are defined in temps/bools. The outputs however did match up
im guessing this is the order of which they exists in states
yes, you might get lucky
is it possible to define a dictionary where we can tightly align the bool and the temp?
im guessing you cant do that in jinja
yes, you can
was just thinking about that
it's just more cumbersome and again I was hoping to avoid typing it all out. but it might be unavoidable here
makes sense. alright ill keep at it. appreciate the guidance
meh, losing interest. I can simplify it, but problem remains
{% set temps = ['input_number.test', 'input_number.test2']|expand|map(attribute="state")|list %}
{% set bools = ['input_boolean.test2', 'input_boolean.test1']|expand|map(attribute="state")|list %}
{% set ns = namespace(temps=[]) %}
{% for bool in bools %}
{% if bool == 'on' %}
{% set ns.temps = ns.temps + [temps[loop.index0]] %}
{% endif %}
{% endfor %}
{{ ns.temps }}
right, im gonna give a dict a try tomorrow. ty 😄
I was making it way more difficult than it needed to be:
{% set map = {'test1': 'test', 'test2': 'test2'} %}
{% set ns = namespace(temps=[]) %}
{% for bool in map %}
{% if states("input_boolean." ~ bool) == 'on' %}
{% set ns.temps = ns.temps + [states("input_number." ~ map[bool])] %}
{% endif %}
{% endfor %}
{{ ns.temps }}
that should work reliably
@trim leaf
Is the delay_on and delay_off for binary sensors hours:minutes:seconds? I'm assuming it is, but it doesn't explicitly say as far as I've seen (so far, I may have missed that)
just match the object_id's for the input booleans with the object_id's on the sensors and it becomes an easier to manage, only 1 list:
{%- set object_ids = ['test1', 'test2'] %}
{%- set on = expand(states.input_boolean) | selectattr('object_id', 'in', object_ids) | selectattr('state','eq','on') | map(attribute='object_id') | list %}
{{ states.input_number | selectattr('object_id','in', on) | map(attribute='state') | map('float') | list }}
How do you use a variable to reference an object? For example:
{{ states.input_boolean.test.last_changed }}```
this doesnt work, im not sure what syntax to use here?
thanks, that worked!
Not sure if template question but might me the answer.
Can I have more than one state topic in mqtt binary sensor? OR logic.
2 topics feeding one binary sensor?
in a multi user config, can we jinja template the current logged-in user, preferably to see if current user is_admin?
need that for conditional cards (not views)
found the attribute in browser-mod browsers, but that is not device independent, so we'd need to know And hard-code those devices...?
Possibly in the front end but the backend doesn’t really have a concept of who is logged in
Likely a silly question but this template works fine until I add a decimal, what syntax do I need to surround it with to keep functionality? {% set ectarget1 = states('input_number.ec_1') | float %} {{ (ectarget1 + 2) }}
I need + .2
I've tried ".2" (".2") and (.2)
What I didn't try was 0.2 lol
Yes that is too bad really, just like where we are in the dashboard. Trying a cc for that. For now I just realized we can use state-switch
Hi guys, noob question, but I cannot figure out what I'm doing wrong with the 'new' template sensors. I have the following in my sensors.yaml file.
- platform: template
sensors:
- name : "Avg zolder temp"
state: >
{{ ((states("sensor.zolder_temp_sensor") | float) + (states("sensor.avg_temp_plants") | float)) | float| round(1) /2}}
But it keeps saying this? The indention is correct, right?
in "/config/sensors.yaml", line 135, column 12```
Nope 😉 check https://www.home-assistant.io/integrations/template/#legacy-binary-sensor-configuration-format and move the ‘sensors:’ back. Name: is not an option in the legacy format though… you’re mixing styles here
Yes I'm trying to 'rebuild' them into the state-based template sensors. But all my sensors in my sensors.yaml are starting with - platform: because it's of course in my sensors.yaml file.
the new template format will not work in sensors.yaml as it is not part of the sensor integration. It is part of the template integration.
Unless ofc that is a package name 😉 still, what Mike posted is incorrect in more than 1 aspect
yes
Make 2 mqtt sensors and then a template sensor using the other 2. If the topics are event topics, make 2 template sensors using mqtt topic triggers. Then make a template sensor from those.
@floral shuttle posted a code wall, it is moved here --> https://hastebin.com/teriwimivi
darn, codewall, sorry bout that. So it's either:```
sensor:
- platform: template
sensors:- avg_zolder_temp:
friendly_name : Avg zolder temp
value_template: >
{{ ((states("sensor.zolder_temp_sensor") | float) +
(states("sensor.avg_temp_plants") | float)) | float| round(1) /2}}
- avg_zolder_temp:
or in the template format:```
template:
- sensor:
- unique_id: avg_zolder_temp
name: Avg zolder temp
state: >
{{ ((states("sensor.zolder_temp_sensor") | float) +
(states("sensor.avg_temp_plants") | float)) | float| round(1) /2}}
icon: >
- unique_id: avg_zolder_temp
(blindly copied your template) so didnt comment on that
Thanks guys! You were right, I've placed it under 'template' instead of sensor and now it's working! I prefer to have it in the sensor file, but your first example isn't working.. but the second is, so I keep it that way! Thanks!
and yes, if you use an sensor: sensor.yaml in your configuration.yaml, you can not use the template: there
Exactly, that's my mistake haha. Thanks again! Appreciated.
if on the other hand you use packages, you can throw them all in that same file, and copy the top level integration names template: and sensor: in there
oh right!! that's exactly what I wanted 🙂 I will try to do it like this. Many thanks
the template integration doesn't work with packages
oh sorry, it seems to be working since 2021.8 as I just saw in the FR you created
Yes it does
Yep, I seem to have missed that in the 2021.8.2 changelog 🙂
Ya my Internet was flaky a sec ago and I didn’t have your second message
yep, working wonders here ever since, and superior file organization, very glad with that change
so back to my one line configuration.yaml: homeassistant: !include_dir_merge_named /config/include/home_assistant
That doesn’t make sense
Remove config if you just have include/homeassistant folders
They might be using it to organize themselves more than anything, does it really cause a problem?
use: packages: !include_dir_named packages and all packages files go in to config/packages.
doesnt get easier than that
every package file the uses the identical order of things, with all top level integrations unindented or un '-' listed
and that even includes nested files. And all of those can be filled with the yaml I dropped here:#templates-archived message
the word 'config' in an include will cause it to fail. all paths in home assistant are relative paths so you don't need to include /config, it's already working from that dir.
but in Lovelace I do need to use - !include /config/lovelace/buttons/buttons_shortcut_menu.yaml, because all is relative to /config/lovelace/views/ ?
sure, ofc all depends on where you store,
config is usually always implied.
It works fine as it is now.. with the /config
I had some issue with an include at some point, and this seems to solve it at that time. And it is stil working 🙂
The packages include is in /config/include/home_assistant btw, and includes /config/include/integrations (I actually only use it to split the integration config)
But I guess we are rather #the-water-cooler now
Hey guys, I'm trying to get a list of sensors for my alarm system. I've figured out i need to loop through states.sensor and use the selectattr() function, but I can't figure out how to match them if they have a 'tamper'/'contact'/'occupancy' attribute, to check if the binary sensor has been triggered in the last n seconds..
Could anybody give me a lead/example/a way to figure this one out? 🙂
Is it possible for an end user to create their own template filters without having to create a custom version of HA? I have the docker version of HA on debian.
No, you’d need to modify the HA code
Would it be easy to build this feature? My python knowledge is limited but I could look in to making a PR at some point. I feel like it would be useful for people.
I suppose such a plugin interface could be built, but I imagine that yes, it would be a lot of work and prone to cause breakage
Okay, thanks for your feedback 👍
Knock yourself out 🙂 https://github.com/home-assistant/core/blob/dev/homeassistant/helpers/template.py
hello hello, so this is the most viewed blueprint. But its giving me a warning in my log when getting executed. 'list object' has no attribute 'entity_id' when rendering https://www.toptal.com/developers/hastebin/ovazazejan.kotlin
What are you trying to add? There's very few things that jinja filters don't do at the moment.
exclude.entity_id exclude is a list, it doesn't have entity_id. Change it to exclude
Its related to raw data processing using bitmasks and bit-shifting (I know the bitwise_and filter exists but it is limited).. but I feel like I am also going to come across other things where I want to create a custom function in the future too. Maybe I am just more of a power user than the average user 🤣
can you provide an example? You can convert bits to values and do your operations that way
there's ALOT of things jinja can do that are not listed in the docs.
that are 'advanced'
and if you want to actually bitshift, just add those to core and make a PR. I'm sure people would accept it... because everyones had to use it at some point in their career
Well there are a few open PR's which I am waiting to see the outcome of before doing anything, but some were closed without being merged so I was considering implementing them myself if they weren't added officially, but I couldn't figure out how I could persist my changes when updating HA that's all.
A theoretical example to extract and convert 5 bits in a 2 byte array would be something like ((value & 0x7C) >> 2) / 10 - currently I can use bitwise_and and perform 'hacky' bit-shifting by subtracting a decimal from the value, but I can't think how I can work with arrays of unknown/variable length. I'd like to test conditions and then perform bitwise operations based on the outcome.
So yeah thats odd.. I changed the template and also fully restarted HA and its still giving me the error message with exclude.entity_id in it. Also saved it and looked in ssh nano just to be sure that it really got changed. https://pastebin.com/HsS7ySKF
right but look at the template it responds with
Yea thats what I dont understand..
the reload didn't occur because your config is invalid somewhere
run a config check and look at the logs
by docker exec home-assistant python -m home-assistant --script check_config --config /config ? The Check Configuration button in HA itself not showing anything and also nothing in the logs expect the spamming template warning
it's not possible to use friendly name on template sensors no more?
interesting, thanks!
There is nothing in the logs expect the template variable warning.. Also as a side-note docker exec home-assistant python -m homeassistant --script check_config --files is giving me File configuration.yaml not found.
sorry not familiar with the argument --files
I'd just run the config check the normal way
you know
through the UI
then look at the logs
via ssh or samba
The config check command is apparently the proper way
Yea thats what I am doing. Thats not giving me anything. I am looking at ssh/samba/portainer.
Yea thats what i also read somewhere. But I guess its not even really working, since that error message above.
docker exec -ti home-assistant hass --script check_config -c /config
you can do it either way, just the results go to your logs
thats it
instead of being printed in your face
I don't use the docker script so I don't know the commands or arguments
Right, but apparently the UI check isn't equivalent to the command
🤷♂️ never failed me yet, but I know how to debug shit prior to checking
Either way, there is nothing in both. In ssh where I execute the command and in my logs after pressing check configuration. I am so omw to just removing that automation.
are you sure you're editing the correct file?
are you sure you reloaded your automation?
I mean I shift + f the exclude.entity over visual studio code over samba. Nothing there expect the entries in the log files. Also restarted HA completely. I guess I can try to restart my Nuc..
Yea still the same.. I guess I am just going to remove it then
I was wondering what the best way would be to template the last zone location that a device had been to? if I just use device_tracker.name.last_changed, that would give me "Away" too. I want to make one template sensor that looks to see if Im at work, and then sets my "desitnation location" as home for instance.
I think I can achieve it with two sensors, but I was interested in having it all be in one. Cant I create a variable inside the template with my last named location?
Maybe I can use a trigger-based template sensor.
Im not familiar with what you mean by pita? :P
pain in the ass
Ahh.
you need to know how to query things in the database
I think I can use a trigger to update the sensor only when I am at work to say "Home" or the lat/long coords.
So when Im at work it updates to say my destination is home
(trying to get only one sensor for google maps travel time with dynamic sensors)
yeah but that doesn't really "tell you what the last state was"
true, but I guess it would work for my sepecific case.
if that's all you want just make a template sensor that provides the lat/lon attributes for where you want to go after you enter a zone.
you don't need a device tracker for the travel time integraitons, they accept sensors with lat/lon attributes or a state which is lat/lon
lat/lon attributes are easier because then you don't need to know the order, unlike when you use lat/lon as the state.
I'll be using the device tracker on the phone as the origin point, so the destination will be a sensor for lat/lon depending on where I am.
I think I know what to do now, thanks ;)
are you able to group lights and switches together in home assistant?
or do you have to convert the switches to lights then group the lights
Groups allow the user to combine multiple entities into one.
Is there a template I can use to control a linear actuator using L298N and ESP32?
In case anyone was wondering, I've got it working. code here: https://pastebin.com/Es35KR2V
{% set value = states('counter.chore_ava_counter') | int %}
You've earned ${{ value / (50) * 15 }} so far.
This returns a float no matter what I do
I'm using this in a markdown card
And I'm trying to get it to round to the hundreds place instead of doing this.....
Oh, I can't post screenshots
2.699999999997
Is what it returns
I want it to be 2.70
When I try....
{% set value = states('counter.chore_ava_counter') | float %}
You've earned ${{ value / (50) * 15 | round(2) }}
It doesn't do jack
Just still spits 2.699999997
Btw, that value of the counter is 9. Not sure it matters
You’re rounding 15
Pemdas
Wow. I guess I didn't think round would do work before the rest of it
That works. Thanks
Filters only apply to the item directly in front of the pipe
I was wondering if someone can help me with a template. I have an input select for "manual alarm setting" where "unset" means I didn't set it manually, "on" means I set it manually to on, and "off" means I set it manually to off. If it's "unset" I want to use the workday sensor to specify if an alarm should go off, but in all cases I only want it to trigger an alarm if it didn't already today. I currently have this: https://www.codepile.net/pile/jMQRq7E6
(Sorry for formatting it in Twig, but codepile doesn't have Jinja support and Twig is fairly similar.)
Is there a better/easier/simpler way to do what I'm trying to do?
how can I put in my template level of light brightness? I want every single time, when lights goes on to put maximum brightness to 60%
trigger:
- platform: state
entity_id: light.livingroom_ceiling_led_1, light.livingroom_ceiling_led_2
to: 'on'
action:
service: >
light.turn_on
#here I need to put brightness value#
entity_id: >
{{trigger.to_state.entity_id}}```
but I don't know how? as a data_template maybe?
Usually services are like this:
service: light.turn_on
data:
brightness_pct: 100
target:
entity_id: light.bed_left
thanks
now I have a different problem, when I do check config it shows me an error
so this OR condition makes me trouble, if I remove this condition OR automation passes as it should
but what I really want to do is to put some and conditions and then to put or
This sounds like an #automations-archived rather than a #templates-archived?
there's really not much that you can do other than refactoring it.
{% set lastNotToday = state_attr('automation.wake_up_light_alarm_with_sunrise_effect', 'last_triggered') < today_at() %}
{% set setting = states('input_select.manual_alarm_setting') %}
{% set alarmOn = is_state('binary_sensor.workday_sensor', 'on') if setting == 'Unset' else setting == 'On' %}
{{ alarmOn and lastNotToday }}
I didn't think there was a lot I could do, but wanted to see if there was a better way I hadn't thought of. Thank you!
states('binary_sensor.workday_sensor') doesn't return true/false
so i made it is_state(...,'on')
Ahhh, thank you! It has been working, but I presume that was by accident rather than by design
well yeah
it would have failed if workday_sensor was off
well, by fail i mean it would have still triggered
That might explain my alarm clock last Saturday
Yup, makes perfect sense in the world of truthy evaluations
Yeah, makes perfect sensor. For some reason I assumed the state of a binary sensor would equal that. Now I know better
well, all states are strings
tbh, I don't like it but that's what it is
I'd rather have states be typed and the frontend take care of it. Then templates would be super easy, but it's an old design decision from years ago.
TBH, I think they are moving that route long term
Yeah, the mistakes of years past easily come back to haunt you in programming. Though there was likely a logical reason at the time.
no, it's just how base jinja works
jinja always returns strings
This typing stuff that it does was added recently
It's all a programmer's fault somewhere down the stack (says the programmer)
IIRC the original reason jinja was developed (outside HA) was an "easy" language to create forms of populated information without a huge memory overhead
which is why namespace and if/else scoping is so limited
Yes, twig, blade and liquid are all much the same thing.
What does it take for my template sensor to be selectable in the Energy dashboard? I have device_class: energy and kWh as units...
state class
check the #energy-archived pins
Roger that. state_class and last_reset got it selectable. Now it just says" statistics_not_defined"
I have this entity which grabs some data from my local school's menu, but also a ton of other stuff. I want to grab todaysFood from the entity in this screenshot: https://imgur.com/a/mOdKucv and use it in a text-to-speech intergration.
I'm using the "skolmaten" intergration from HACS
It’s just an attribute
And how would I go about using it in TTS
No idea. But the template is explained here: https://www.home-assistant.io/docs/configuration/templating/#states
TTS is an #integrations-archived
You should probably ask this in #energy-archived
Issue isn’t related to templates
I would like to build a template that evaluates to true if a light has been on within in the last 10seconds. How can get the template to evaluate states from the past?
{{ ( as_timestamp(now()) - as_timestamp(state_attr('automation.mail_notification', 'last_triggered')) |int(0) ) > 30 }}
I tied using last_on with the above example but I had no success.
Thanks for sharing this.
According to the description this would check the condition until x time has passed.
The amount of time (ie 0:00:05) the template state must be met before this sensor will switch to on. This can also be a template.
I would like to check if the condition has been true within the last 10sec but not for the last 10 seconds.
I think history stats
with a count
The other should do that too. It has a count
i do that all the time
Anyway, OP has vanished
I pop into this channel just to get ideas from time to time. It's amazing how often I see the solution to a question I had in the back of my mind. Thanks for pointing out statistics!
I always forget about history_stats, so there are many such exchanges where I suggest statistics and history_stats is more appropriate. They each have their own uses...
This will also help me set up some things because I now remember I can look at past data to see how things change
A bit unsure where to put this one:
Looking to set up a sensor that records max energy used by the hour. The sensor should automatically reset each month.
Have set up a utility meter, and was looking at long-term statistics which look to have the data I need, but not necessarily available to an automation?
i'm a bit confused regarding the use of unique_id, name and friendly_name .. i want to have something that i can change throught the UI.. for instance for a sensor that's moving around..
and also i may want to use some special characters in the name visible in the UI
what is the correct/best way of setting up sensors to accommodate this?
Neither of those options are templateable.
Hey, i'm adding switchbot curtain to HA. I noticed a issue in the code here: https://community.home-assistant.io/t/switch-bot-api-integration/270550
Which is value_template: '{{ value_json.body.slidePosition }}' this should be a float (or int) because the output of curl is: <output-truncated>"slidePosition":100},"message":"success"}
How can I edit the value_template correctly? I'm not that great at coding stuff :/
On HA the error is: 2021-12-04 16:11:32 ERROR (MainThread) [homeassistant.components.template.cover] could not convert string to float: '' but of course if i remove the double ' or use double quotes, it won't work. HA complains of an issue in the code.
Solved 🙃 a typo in the curl
you shouldn't ever have to cast the ending result. People do that in error
the only time it would be needed is if you are trying to round the sig figs
otherwise, home assistant will type it after the resolution of the template
right, i thought that actually but kept seeing that error and that mislead me. At the end was really the url the issue. copy/paste didn't work properly and had empty deviceId everywhere in the secrets file.
Anyway. New issue 😄
https://www.home-assistant.io/integrations/cover.template/#position_template
Legal values are numbers between 0 (closed) and 100 (open).
Mine are inverted. 0: open, 100: close.
Do you by any chance know how to invert that?
100 - position
was looking to a "change direction" option but turns out the math way was easier. wow. thanks!
the math is stupid easy if you know templates
yes i'd say so too 
hey guys if I want to have a customer variable for my AC unit can I not put it in the climate.yaml?
current_blower_speed isn't allowed apparently
Need help in understanding this
{{ states('sensor.cam_storage') }} MB
{{ states('sensor.cam_storage') | filesizeformat }}
{{ states('sensor.cam_storage') | int*1000000 | filesizeformat }}
{{ states('sensor.cam_storage') | float *1000000 | filesizeformat }}
{{ 12920000.0 | filesizeformat}}
The results of the above are
12.92 MB
12 Bytes
1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB1.0 MB
TypeError: can't multiply sequence by non-int of type 'float'
12.9 MB
the sensor is a folder platform which provide the state info as a size of the files within that folder in MB. However, when applying the filesizeformat it behaves quite strange in 3rd and 4th values Shouldn't it display the value correctly like 5th value? I understand that the 2nd value is incorrect since the state returned is 12.92 and hence it tries to convert only that value
The reason I want to use the filesizeformat is that it dynamically applies the correct notation kb,mb,gb etc
ah okay - so this works {{ (states('sensor.cam_storage') | float *1000000) | filesizeformat }} gives 12.9 MB - thanks!
a little lost how do I update this template so a default is provided? - name: "Garage OctoPrint Time Remaining" unit_of_measurement: 's' availability: > {{ not is_state('sensor.garage_cr6se_estimated_finish_time', 'unavailable') }} state: > {% set finish = as_timestamp(states('sensor.garage_cr6se_estimated_finish_time')) %} {% if is_number(finish) %} {{ (finish - as_timestamp(now())) | int }} {% else %} unknown {% endif %} attributes: start_time: "states('sensor.garage_cr6se_estimated_finish_time')"
If you’re just seeing the warning at HA start, there’s an issue in 2021.11 that can cause that despite the availability template. It’s fixed in 2021.12
Ah good to know beta time 😂
has anyone gotten Dwains Dashboard working
many people have, but you should probably ask in #frontend-archived or on the dwains theme post.
Does anyone have an idea why data from my template sensor does not end up in InfluxDB? The entity does, but no data. The sensor works fine in hass...
- sensor:
- name: "Medeltemperatur Nedervning"
unique_id: medel_downstairs
unit_of_measurement: "°C"
state: >
{% set toalett = states('sensor.toalett_sensor_temperature') | float %}
{% set lekrum = states('sensor.lekrum_temperature') | float %}
{% set hall = states('sensor.hall_temperature') | float %}
{% set tvattstuga = states('sensor.tvattstuga_temperature') | float %}
{% set vrum = states('sensor.vrum_temperature') | float %}
{% set kok = states('sensor.kok_temperature') | float %}
{{ ((toalett + lekrum + hall + tvattstuga + vrum + kok) / 6) | round(1, default=0) }}```
The template isn't the problem, it would be influx. Please ask in #integrations-archived or #add-ons-archived if you're using the addon
hey guys - if I could have your advice on this... I have created a script that takes a capture using the camera.snapshot service from a camera entity passed as a parameter to the script and then sends this capture via telegram to a user.
So there is a second service call for telegram_bot.send_photo. I am using now().strftime to produce the filename for the capture and I would like to ensure that the same filename can be passsed (somehow) as the file and caption for the telegram service call.
Because seconds are also used in strftime I am worried that if I reuse the same line of code , if he time between service calls has passed by 1 second then the telegram service won't be able to locate the file.
Here is my code: https://paste.debian.net/hidden/b1d5a472/
Suggestions are highly appreciated.
The obvious workaround would be to lose the "seconds" and leave it at %H%M
make a variable that has the time.
take_screenshot:
...
variables:
thetime: "{{ now().isoformat() }}"
...
sequence:
....
data:
filename: /config/www/camera_captures/{{ camera_entity }}_{{ thetime }}.jpg
Is there a way to filter out an entity not available? I tried filtering out entities with a state of unavailable but some entitities are orphaned and the entity itself is unavailable how do I filter out those entities in a template.
{{ states('your.entity') not in [ 'unavailable', 'unknown' ] }} might do the trick
hello , my philips hue sensor also shows temperature. But it has an offset of 2C less than the actual temperature. How can i make it show the measured temperature +2 C ?
Or how do i add a new entity with the philips sensor temperature + 2 as value ?
(oh i scrolled up and saw an example ... nvm)
Can anyone shed some light on how I remove the date from a sensor? The following code outputs: 2021-12-06 13:35:00. I would like to get just the time, 13:35. Also, what is the preferred method, top or bottom code?
{{ states.calendar.family.attributes.start_time }}
{{ state_attr('calendar.family', 'start_time') }}
bottom is preferred, as is also mentioned quite clear in the docs:
https://www.home-assistant.io/docs/configuration/templating/
Avoid using states.sensor.temperature.state, instead use states('sensor.temperature'). It is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup).
And to format it, you can have a look at https://www.home-assistant.io/integrations/time_date/ (bottom of the page)
Hi, want to count my tv's that are playing but the template below gives an UndefinedError: 'media_player' is undefined error?
sensor:
- platform: template
sensors:
televisions_playing:
value_template: >
{% set media_players = [
media_player.samsung_tv_remote,
media_player.samsung_tv_slaapkamer,
] %}
{{ media_players | selectattr('state','eq','playing') | list | count }}```
those aren't state objects or entity_ids
hint, if you want entity_id's they need to be in quotes. Then you need to supply the list to the expand method to get them into state objects
Hi, I am trying to feed a light group data in configurations.yaml. I have this https://pastebin.com/nH5BvmXE, where the first one works and was hoping the second should work, but can't seem to get the syntax correct. Can someone point me in the right direction please?
I have a problem with my one of my ESPHOME sensors. HA is recognising the sensor as string and not as numeric, so my numeric state trigger will not work.
If i use {{ states('sensor.gosund4_temperatur') > 0 }} in the developer tools i get TypeError: '>' not supported between instances of 'str' and 'int'
but with {{ states('sensor.gosund4_temperatur')|float > 0 }} the result is true.
Thanks for the answer. Have you any idea why it works perfectly fine for my speakers with a playing state.
I have no idea what you're talking about. That template will always fail no matter what.
It works perfectly fine for my speakers like this.
sensors:
speakers_playing:
value_template: >
{% set media_players = [
states.media_player.sonos_keuken,
states.media_player.badkamer,
states.media_player.living,
] %}
{{ media_players | selectattr('state','eq','playing') | list | count }}```
It now says 1 speaker playing which is correct...
I hope you see your error
look at your other list
and look at the one you posted
they are not the same
it both starts and ends with "s"
Oh cr*p. 😄
That doesn't make sense. All states across home assistant treat states as strings. The error is most likely how you think a numerical trigger should work. They only trigger when you cross the threshold. They will not trigger if already above the theshold and it moves further above the threshold.
you can't template that field.
Oh. Sorry to hear that, but thanks Would have been neat. Is there a reason why its not possible, or just not implemented (yet?)? 🙂
It would be a feature request
Got it, thanks 🙂
You could simulate that with a template light
I knew that the value must cross the threshold. I had tested yesterday very long time with the automation and the developer tools and never the trigger was triggered, although the threshold was crossed. Now I have just deleted the automation completely and created new and then restarted the HA. What should I say, now everything works, no idea what the problem was. Now I feel pretty stupid. Sorry for the stupid question. 😩
Hi! I'm using following line to display a sensor in a markdown card -> {{states('sensor.nasta_buss_mot_lyckeby_0')} , this works fine giving me a time in HH:MM:SS. But is there an easy way to display it directly in the markdown card without the seconds part? Thanks beforehand.
Okay, I've tried like 10 different ways now. Including <code>{{ strptime(states('sensor.nasta_buss_mot_lyckeby_1'), "%H%M") }}</code> but it still shows HH:MM:SS
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://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
probably because the state is a string and not a datetime, so it's just passing it through
@inner mesa , problably, but I tried using strptime now with the same result, shouldn't that fix it?
like you just posted? like I said, it's a string, not a datetime
states('sensor.nasta_buss_mot_lyckeby_1') is a string, like every state
oh, nevermind
I'm an idiot
having this trigger template:```
template:
-
trigger:
- platform: event
event_type: hue_event
event_data:
id: auditorium_tap_switch_button
sensor: - name: Hue tap switch last event
state: >
{{trigger.event.data.subtype}}
- platform: event
what is the state of that sensor?
The state is a time displayed in this format HH:MM:SS
works just fine, except when one taps the same button multiple times. (and the trigger doesnt fire) can I somehow add the event.time_fired to the trigger?
It also has attributes for time, date or tiemdate.
then you need to provide that string to strptime(). you need to provide the format of that string so that it can parse it, not what you eventually want to output
you're doing two things at once
strptime(string, format) parses a string based on a format and returns a datetime object. If that fails, returns the default value, or if omitted the unprocessed input value.
Hm.. But if I have to it another way, is there an easy way to get minutes until that time occurs instead? That would actually be more convinient.
Like "The next bus leaves in x minutes"
Because I'm doing it in a markdown card
{{ ("15:30:01"|regex_findall(".*:(.*):.*"))[0] }}
-> 30
is that what you want?
{{ "15:30:01".split(':')[1] }}
-> 30
oh, I see. you also need to do some math
I'm not doing a very good job of helping here 🙂
Hm.. Sorry if I'm confusing you by changing the question in the middle of the discussion. Anyway, TLDR: Sensor outputs time in a string like eg. "21:16:00". I want to get the number of minutes outputted until that time occours in a markdown card mid sentence.
No problem, @inner mesa , glad you're trying!
I tried this now but with no luck, just getting an int number instead:
'''
{{ ((((states.sensor.nasta_buss_mot_lyckeby_0, "%H:%M:%S") | int)) - ((as_timestamp (now()) | int ))) }}
Oh.. See what I did there, let me try something
you can start with today_at(states('sensor.nasta_buss_mot_lyckeby_0'))
{{ today_at("13:05:01") }} -> 2021-12-06 13:05:01-08:00
UndefinedError: 'today_at' is undefined
you're using an old HA version
Version
core-2021.9.7
Senaste version
core-2021.11.5
that's almost 3 months old
Aight, maybe time for an update then. 🙂
once you do, this might work for you:
{% set parts = ((today_at("13:05:01") - now())|string).split(':') %}
{{ "%s hours, %s minutes" % (parts[0], parts[1]) }}
-> 0 hours, 59 minutes
Just wrapping up startup now after update. Will try!
@inner mesa : Got this now: ValueError: could not convert datetime to datetime: '1900-01-01 21:36:00'
When using the following
{{ "%s hours, %s minutes" % (parts[0], parts[1]) }}```
That makes it seem like it actually is a datetime and not a string or?
I tried yours as well, didn't work
OH
Now it did.
Weird. I must be a dumbass.
And if I just want it in minutes?
Because usually the bus leaves like every 20 min or something. Of course not in the night, but then it ca say like 240 min, doesn't matter.
Got it: {{ ((today_at(states('sensor.nasta_buss_mot_lyckeby_0')) - now()).seconds / 60) |int }}
Thanks, @inner mesa !
Hi, I am trying to create image cards in lovelace, is it possible to create a folder where the images are named the same as the entities' friendly_name and in the image field do something similar to / local / images / {{friendly_name}}. png?
Thanks in advance
posted some more code in the community on this, still looking for a way: https://community.home-assistant.io/t/trigger-template-based-on-hue-switches-need-event-time-fired/364084
@floral shuttle posted a code wall, it is moved here --> https://hastebin.com/redehimafo
darn. sorry. do we need to repeat the - trigger for all sensors per trigger (and have the sensor: at the same indent?
somehow it seems more logical to only state trigger: once and then align the trigger platform and sensor to the same indent..
Does the local file accept template for the file_path? https://www.home-assistant.io/integrations/local_file/ I was trying the below, which works fine in the Dev tools -> Template but reports errors in config validation when I provide the same for the file_path
{{ state_attr('sensor.cam_storage', 'file_list') | reject('search','^\/\w*\/\w*\/\w*\-\w*.mp4$')| sort(reverse=true) | list| first }}
okay. So I would have to do that extraction of the exact filename via this template in automation and pass the exact string.
yes, presumably via local_file.update_file_path
I dont know if this is the correct channel for this, but I want to write a template for a lot of sensors. they will all be the same (only difference is their index). so example: door_code_user_1, door_code_user_2, etc. but it will be very messy writing this 25 times. Is it possible to do a for-loop and write it out like that? Or does anyone know how I would go about making something that will auto-generate a yaml file?
This is the only one I'm aware of but it only works with Lovelace YAML. https://github.com/thomasloven/hass-lovelace_gen
nice! thanks I'll give that a try! 😄
also have a look at decluttering card, which is a last resort before entering the realm of lovelace_gen. throw all repeating stuff in a template and only list a variable name or 2 in the config. very nice. (comp with yaml anchor, but global) https://github.com/custom-cards/decluttering-card
very nice! thanks alot! 😄
Hi all, I have a small question regarding the new entity categories. Is it possible to find the entity_category of a specific entity from within a template? And/or is it possible to find all entities in a category from a specific device? I searched the docs, but it quite limited on this topic. This feature seems to be purely for the configuration page from home assistant, and not really made for custom UI's.
it's not possible
oh 😦 is there any reason to hide this property from the end user? Or is this something that could still come in future updates?
Thx for the information anyway 🙂
it's not a property, it's just an organization in the ui
@mighty roost posted a code wall, it is moved here --> https://hastebin.com/azaginaxut
@mighty roost check the pins 📌
Ah.. I might have been trying to do it wrong by using (foo | default(0)) | int etc. Just replace int with int(0) should do the trick? foo | int(0) that is
yep
hi there! I have a question
I have an entity that is a sensor from mqtt. how is it that I can have history on the sensor, but no current value on the sensor?
if I place the entity in lovelace as a gauge for example, it reports 0 [units] but when I click on the gauge entity it shows the historic values as they should be (non-zero)
#integrations-archived please
Thanks, wasn't sure if it was integrations or templates
Hello, I have an automatioon which I monitor 2 switches, and if they are switched in seconds both of them, then I turn on wled
however, I want now, instead of the second switch to implement last_changed date of my binary_sensor.hallway_ledstrip_button
basically something like this : {{states.binary_sensor.hallway_ledstrip_button.last_changed}}
When I put it in my template editor, I see some datetime value, but its not correct time..so my question is is there an attribute for binary_sensor when it was pressed?
Hi guys
I'm trying to build a light template and im getting a strange error
the error is:
Invalid config for [light.template]: [effect_list_template] is an invalid option for [light.template]. Check: light.template->lights->ambivision->effect_list_template. (See ?, line ?).
@thorny snow I replied to you on the forums
Greetings, so I have a vesync smart switch that comes with energy monitoring. Since this is not directly supported in the HA energy dashboard, I followed a guide to create a sensor template to have the appropriate data. However it doesn't show if I try to add it to the energy configuration. Any guidance would be greatly appreciated
Try the first pinned message in #energy-archived
I can't seem to use state_class in my sensor template
Invalid config for [sensor.template]: [state_class] is an invalid option for [sensor.template]. Check: sensor.template->sensors->heatingwire_today_energy->state_class. (See ?, line ?).
Use customize to add it then
so disregard this part of the pinned message: Keep in mind however it's best to incorporate these attributes in the integration itself and not as customisations! ? 🙂
if it works .. trying
You can't follow that if the integration you are using does not support it. Use customize to get up and running then raise an issue for the integration on github
ok now I can add it .. need to fix this .. statistics_not_defined
sensor.heatingwire_today_energy
nevermind .. I guess it just needed some time to generate some stats for it .. message is gone now
thank you !
Dont forget to raise the issue.
checking for an existing one
weird .. existing closed issue .. someone saying: integration sets the state_class on it's own...
issue opened
template integration already can use state_class
It's not supported in the legacy format
so use the new format
That issue will be closed if you write it against legacy, as it's legacy
struggling to convert to the new format with a sensors.yaml outside configuration.yaml file .. trying ...
if anyone feels like helping with syntax that would be appreciate .. always struggling with the proper intendation: ```- platform: template
- sensor:
- name: "chicken_heatingwire_today_energy"
state: '{{state_attr("switch.chicken_heatwire", "today_energy_kwh")}}'
unit_of_measurement: kWh
state_class: total_increasing
device_class: energy
- name: "chicken_heatingwire_today_energy"
can't find working example of external yaml file using the new template syntax
That’s a mix of the two formats
hence my confusion I guess lol
There’s an example right at the top: https://www.home-assistant.io/integrations/template/#state-based-template-sensors
but that example is within the configuration.yaml file ..
instead of in a included yaml
Do you have template: in configuration.yaml?
I'm putting this in sensors.yaml .. does the new format need me to do this in a template.yaml instead ?
I dont want to overburden my configuration.yaml file if I can help it
template: !include_merge_dir_list templates -> in configuration.yaml
Then put the template in any yaml file inside a folder you create named templates. The file contents will be:
- sensor:
- name: "chicken_heatingwire_today_energy"
state: '{{state_attr("switch.chicken_heatwire", "today_energy_kwh")}}'
unit_of_measurement: kWh
state_class: total_increasing
device_class: energy
- sensor:
- name: "chicken_heatingwire_today_energy"
state: '{{state_attr("switch.chicken_heatwire", "today_energy_kwh")}}'
unit_of_measurement: kWh
state_class: total_increasing
device_class: energy``` works in my configuration.yaml file
@mighty ledge Error loading /config/configuration.yaml: could not determine a constructor for the tag '!include_merge_dir_list'
works fine within the configuration.yaml file, ty
ok it validates now
thanks guys .. just confirming that all is good now .. I believe it is
is there a way to make a subtraction with the templates that only returns positive values?
It's all Jinja: https://jinja.palletsprojects.com/en/3.0.x/templates/
see the first one (abs()): https://jinja.palletsprojects.com/en/3.0.x/templates/#list-of-builtin-filters
Is it possible to use templating when creating a sensor using the Integration platform?
like what?
(how) Are the properties (https://developers.home-assistant.io/docs/core/entity#generic-properties) of an entity available in template? I tried searching but nothing I found works about this.
:( I was hoping I can separate config switches from other switches in auto entities card.
Is there a way to combine dicitionaries into one?
examle
{% set dict1 = {'a': 1, 'b': 2} %}
{% set dict2 = {'d': 3, 'b': 4} %}
Should be combined into: { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
I found the | combine filter online, but that doesn't seem to work in the template editor
dict2 doesn not have a fixed number of keys, so it could be 1, or 2 or whatever number of keys and items
We don't have the ability to do dictionary/list modifications in our Template engine
combine I believe/remember is a specific Ansible feature, not natively to Jinja2 (but is has been a while since I've used Ansible, so things might have changed)
Now you tell me. I've been banging my head against a wall trying to work out how to do this in the template editor 😄
hehe you can't 😄
okay, good to know 🙂
Although we should be able to make such things possible nowadays, I does need to be done with a lot of testing and care. As in, we don't want to create abilities to modify internals
Yes, it is Ansible, but that didn't stop me trying it in the template editor 😉
I seem to recall that you can use templates as well to create conditional attributes in data, but I can't seem to find where I found that. ```
attribute: 1
{% if something %} attribute: 2 {% endif %}```
like that
{% if something %} {"attribute": 2} {% endif %}
and should this work then?
- variables:
extra_data:
language: nl
voice: thefes
- service: tts.google_cloud_say
data:
entity_id: media_player.whatever
message: test
{% if extra_data is defined %} {{ extra_data }} {% endif %}
Hassbot and VSCode do not like it 😉
no that won't work
you could do that, but you'd have to fully template the data part and return a single dictionary string
but honestly, that is stuff that will bite you at some point 🙂
So, maybe not...
okay, I'll just stop with this futile attempt then 🙂
data: >
{% set data = {"message": "xyz", "entity_id": "abc"} %}
{% if something %}
{{ data }}
{% else %}
{{ dict(foo='bar', **data ) }}
{% endif %}
YOu're recalling incorrectly. Luckily, it was added in a recent version of HA, however you need to define the entire dictionary. You can't use yaml
Unless you're in an automation, then you can use yaml.
but you have to use python's dictionary built-in functions like update, which has it's own caveats
One should not be able to use update on a dictionary
I've been using it for sometime
Well in that case, we have to report a security issue with Jinja :S
or maybe I did it differently
hold up, lemme check
I've done dict merging somehow. I assumed it was update
I fixed it above, it wasn't update. It was creating a new dict using other keys
hmm trying that, but vscode doesn't like it, it says incorrect type. expected object. might be a vscode feature though
yeah, it passes ' ha core check' so should be fine
I doubt vscode understands that data can be a template
Either way, that is pseudo code and it has syntax errors. You'll have to take the principles and apply them
well yeah I worked it out in the template editor. should be testing it later
Ah nice petro, will give it a try!
I have multiple trigger-based binary_sensors in a template.yaml
Trying to template the icons based on state in example:
binary_sensor:
- name: Schlaf
icon: >
{{ 'mdi:sleep-off' if is_state('binary_sensor.schlaf','off') else 'mdi:sleep' }}
state: >
{{ trigger.id == "sleep" }}
unique_id: binaryschlaf
After a restart none of the icons show up in Lovelace. After some time, some of them show up and the rest stay on the default binary sensor icon. Am I missing something?
With all my non-trigger-based binary sensors this template works as it should...
Works like a charm!
Nice, I wasn't sure if it would work but I vaguely remember a PR going through that allowed templating the entire data field
Ok found out that the icon doesn't get updated until the binary_sensor is triggered
It makes sense when you output a dictionary. Unfortunately the more common error that I see is outputting key: value as text, and that won’t work
exactly
But you can get around that...
in automations
variables:
my_fake_dict:
key: value
then
service: xyz.ijk
data: "{{ my_fake_dict }}"
I use that quite a bit
This is what I did now using your template:
variables:
tts_service: tts.google_translate_say
service_data:
language: nl
then
- alias: "Send TTS message"
service: "{{ tts_service }}"
target:
entity_id: "{{ tts_target_list }}"
data: >
{% if service_data is defined and service_data != None %}
{{ dict( message = tts_message, **service_data ) }}
{% else %}
{{ dict( message = tts_message ) }}
{% endif %}
Like if I want the source to be a combination of several sensors, but now I have to first create a template sensor with my calculation and then feed the new sensor to the Integration platform as a source.
that's your only option
Alright good to know 😊
Hi there. a dumb question. I want to make a template for my heat pump though and IR blaster.
My IR remote only has a toggle on/off button.
I currently have no way of knowing whether the heat pump is on/off
how do i create an entity that allows me to toggle the on/off
I currently don't mind if home assistant doesn't know the state of the heat pump
Am i correct in saying that I should just write a script?
You can create a template switch. The turn_on and turn_off actions will both be to call the remote command. The state feedback (value_template) is optional so you can leave that out as you dont have any way to determine this.
A good way to add state feedback if you want this in future would be with a power monitoring smart plug. Power > X = ON.
Thanks.
thats awesome.
There's no power plug for my heat pump unfortunately.
its directly hooked up to my house's AC.
Ah ok.
There are other options for controlling heatpumps, like sensibo (cloud 🤮 ) or ESPHome or even a wifi card addon for your particular heatpump (best option). These will create Climate devices. What type of heatpump is it?
its a daikin heat pump
Are you in Australia?
the wifi card isn't available in my country
for some reason
im in new zealand.
how did you guess?
Your message could not be delivered. This is usually because you don't share a server with the recipient or the recipient is only accepting direct messages from friends. You can see the full list of reasons here:
But you're too kind. You don't need to send one to me.
I wont ever use it. I offered it on the forum too. Hang on...
(I got new heatpumps with the card fitted and saved the card from the old one).
oh
do all daikin use the same wifi card?
just in case different models use different cards.
All support the older card I'm looking up the part#
ok, thanks.
BRP072A42. Pretty sure all Daikin heatpumps have the S21 connector needed for this. The 2.0kW – 7.1kW Cora & Alira systems just require a differnt connecting cable.
That's a 2.5kW Cora. It is compatible.
oh, let me sort that out first before you send me anything.
i don't want the part to goto waste because i can't find the cable.
Sidetracking a little, you mentioned using ESPHome. I have ESP32 boards. But how would you hook that up to the heat pump?
That sounds interesting.
Oh
Rod at Peninsula Air (link I posted earlier) is very helpful and can sort you out re: cable. Send them an email.
Yeah. Let's move this to DIY as it is no longer about templates.
@ivory pawn posted a code wall, it is moved here --> https://hastebin.com/tebowixiwa
Hello, Can someone tell me what is wrong in my template?
This works:
command: curl -X https://api.com/test/?period_from={{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:30', True)}}```
This works in developer tools > templates:
{{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:30', True) }}
{%- else -%}
{{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:00', True) }}
{%- endif %}```
BUT this combination doesn't work:
command: curl -X https://api.com/test/?period_from={{
{% if (now().minute) > 30 %}
{{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:30:00Z', True)}}
{%- else -%}
{{(as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:00:00Z', True)}}
{%- endif %}}}```
I'm trying to round down to the nearest half hour and pass this into the curl command. Think its formatting issue but maybe command line template cannot handle conditions.
Any ideas?
you're nesting templates
you've surrounded the whole template with {{ }} with some other template stuff inside
you'll need to play with it, but I would start with something like this:
- platform: command_line
command: >-
curl -X https://api.com/test/?period_from=
{%- set format='%Y-%m-%dT%H:30:00Z' if now().minute > 30 else '%Y-%m-%dT%H:00:00Z' -%}
{{ as_timestamp(now()) | timestamp_custom(format, True) }}
you also had a multiline template, but didn't add the >- to introduce one
that results in
- platform: command_line
command: >-
curl -X https://api.com/test/?period_from=2021-12-09T16:30:00Z
for me
@inner mesa thanks, did realize the nesting issues but didnt try the >- . ill try it all now 🙂
@inner mesa your code works great and neater too. I had simplified what i wanted to make it easier to help, but I also wanted to subtract 24 hours from the result . I had used this in my example period_from={{(as_timestamp(now()) - (24*3600)) | timestamp_custom('%Y-%m-%dT%H:30:00Z', True)}} but not sure how to add that to your code?
Edit: something like this: {{ (now() - timedelta(days=1)).strftime("%H:%M:%S") }}
thanks @inner mesa ill give it a go
Hey, could anybody help me in here? Why am I seeing this message when I try to render the template?
Template:
Test: {{input_datetime.time_bedroom_left_window_opened}}
Error I get:
UndefinedError: 'input_datetime' is undefined
However, I can nicely see that the value is actually populated:
input_datetime.time_bedroom_left_window_opened
time_bedroom_left_window_opened
01:45:24 has_date: false
has_time: true
editable: true
hour: 1
minute: 45
second: 24
timestamp: 6324
friendly_name: time_bedroom_left_window_opened
@ivory pawn I edited it a bit after testing. You can convert to timestamp and use timestamp_custom, or just use strftime() like that
@bitter spindle posted a code wall, it is moved here --> https://hastebin.com/ocujexiras
Ooo, thank you very much! Works like a charm now:
Test: {{states.input_datetime.time_bedroom_left_window_opened.state}}
Test: 01:45:24
better to use {{ states('input_datetime.time_bedroom_left_window_opened') }}. See the warning on that page
is it possible in yaml to evaluate whether the 'abcde' string contains the 'bc' substring?
Not in YAML
But it is possible if the option support templating with Jinja
{% if "bc" in "abcde" %}
sorry, I meant Jinja 🙂
instead of 'in', does 'includes' work in some way?
nevermind... I guess it's just the same
Yes it is 🙂
I have implemented a few single line template if statements. Is it possible to create an else if in the same manner?
{{ 'arrived' if trigger.to_state.state == 'home' else 'left' }}
😄
Basically it'll only allow one statement that evaluates as true or false, and the returns either of the two text variables at the end of the {{ }} template? Thanks for clarifying!
I'm not sure if I follow that question
I think I kind of answered my own question 🤦♂️
it's about using "elseif" in that example without using the long version. If I got it right.
Yeah that's right, trying to keep the code condensed and short. But it sounds like it's not possible with the condensed format I've used as it only allows for a boolean test.
trying to keep the code condensed and short.
I would advise against that btw...
Single line stuff may look condensed, but always harms readability
But... its taste 😄
I wish we had some ternary support in Jinja though
Especially if/else is happening a lot I guess
{{ is_state("device_tracker.frenck", "home") | ternary("yes", "no") }}
Would something like that be useful?
can also be used in expressions
e.g.
{{ (something == "unavailable") | ternary("yes", "no") }}
Yeah that would be handy.
i like that too
A separate question, but is there a way to use jinja to create a grammatically correct list? I.e. I have a jinja list and I want to convert it to:
Item 1, item 2 and item 3.
I don't always know the length of the list, so if it's more than one item the and connector should be used on the final item.
seems it works with nesting: {{ '1' if false else '2' if true else '3' }}
🔥🔥🔥
Done https://github.com/home-assistant/core/pull/61428
Now I really need to continue to work on the state of the open home 😄
hello, I have a wake on lan template set up so that it hibernates a windows pc and also wakes it up
but I've recently noticed the switch isn't working anymore
the turn_off action triggers a service that ssh
I've tried the command in the terminal on the HA server and it works
but then tried the same service in HA gui and it doesn't trigger
shell_command:
turn_off_pc: 'ssh -i /config/id_rsa userr@192.168.100.5 "shutdown /h"'
the bare ssh command works from the terminal meaning it can't be the keys fault
anyone know why the service in HA would act up?
already looking forward to 2022.1 now 🙂
or.. 2022.2? I seem to recall 2022.1 will be skipped
@tranquil eagle posted a code wall, it is moved here --> https://hastebin.com/raronoboxo
Hi Guys! Sorry for this noob question.
I've tried this on the template demo and this works:
sensor:
- platform: template
sensors:
livingroomtemperature:
friendly_name: 'Living Room Temperature'
unit_of_measurement: '?C'
value_template: "{{ states('sensor.living_room_thermometer') | float / 10}}"
However I don't know where I could put in on my configuration.yaml
I would like to seek your assistance in helping me on where I should put it.
I have a LocalTuya Integration.
Thanks!
Hi guys
when doing a dict
is it possible to reduce this:
{"a": "ok", "b": "ok"}
a or b then ok
If the template works, it is not a topic for #templates-archived but in this case for #integrations-archived 🙂 But this should work if you paste it in your configuration.yaml, unless you already have sensor: defined there. Do note that you are using the legacy sensor template format now, there is a new format: https://www.home-assistant.io/integrations/template/
I have no idea what you are trying to ask 🙂
I think you need to add a bit of context to that question
What's the actual objective here?
Sounds like an XY problem now 😄 https://xyproblem.info/
You are asking for a solution without the problem
like {"a/b": "ok"}
I like to learn ...
{% if states('input_select.ambivision_modes') in ['Intelligent (Capture)', 'Manual (Mood)', 'Level (Music)']%}
AmbiVision31
{% elif states('input_select.ambivision_modes') in ['Smooth (Capture)', 'Fireplace (Mood)', 'Mixed (Music)']%}
AmbiVision32
{% elif states('input_select.ambivision_modes') in ['Fast (Capture)', 'Rainbow (Mood)', 'Lamp (Music)']%}
AmbiVision33
{% elif states('input_select.ambivision_modes') in ['Average (Capture)', 'Nature (Mood)', 'Flash (Music)']%}
AmbiVision34
{% elif states('input_select.ambivision_modes') in ['User (Capture)', 'Relax (Mood)', 'Frequency (Music)']%}
AmbiVision35
{% endif %}
I was trying to achieve that with a dict
and some values repeat
Got it. That's why we're asking why: the context is important
that doesn't lend well towards a dictionary
I have a custom component that in its configuration has something like
wait
'{"Spotify": "3201606009684/rJeHak5zRg.Spotify", "Netflix": "RN1MCdNq8t.Netflix", "Rakuten": "vbUQClczfR.Wuakitv", "YouTube":"111299001912/9Ur5IzDKqV.TizenYouTube", "Prime Video": "3201512006785/evKhCgZelL.AmazonIgnitionLauncher2", "Mitele": "BTqpJutesE.Mitele", "Grabaciones": "My Content Browser", "Video USB": "mycontent-video-player", "Navegador": "org.tizen.browser", "Menu": "org.tizen.menu", "Reproduciendo Grabación": "Recoreded TV Player", "TV3 app": "PzkKxRdFT6.TV3", "HBO": "cj37Ni3qXM.HBONow"}'
this: "Spotify": "3201606009684/rJeHak5zRg.Spotify"
it allows one entry or several separated by a "/"
I was wondering whether it was possible to do it the other way around
if it were possible it would look clean in a dict
it's not going to look clean with what you're trying to do
I think it would
if it were possible
something like {'Intelligent (Capture)/Manual (Mood)/Level (Music)': 'AmbiVision31'}
juice is not worth the squeeze
somewhere, you'd have to map AmbiVision31 to each value of ['Intelligent (Capture)', 'Manual (Mood)', 'Level (Music)'] to make a dict work. So it defeats the purpose
either way, you have to write it out somewhere
{% set items = {
"AmbiVision31": ['Intelligent (Capture)', 'Manual (Mood)', 'Level (Music)']
...
} %}
{% set ns = namespace(found=None) %}
{% for k, v in items.items() %}
{% if states('input_select.ambivision_modes') in v %}
{% set ns.found = k %}
{% endif %}
{% endfor %}
{{ ns.found }}
any better? Not really.
mapping the other way...
{% set items = {
'Intelligent (Capture)': "AmbiVision31"
...
} %}
{{ items.get(states('input_select.ambivision_modes')) }}
However you'll run into issues if the modes share a name.
I understand
I mean, I don't understand you last posts but I do understand the issue
it is ok the way it is
how do you not understand the last post? i'ts a one to one
{% set items = {
'Intelligent (Capture)': "AmbiVision31",
'Manual (Mood)': "AmbiVision31",
'Level (Music)': "AmbiVision31",
...
} %}
{{ items.get(states('input_select.ambivision_modes')) }}
it's probably the easiest thing to understand
one more thing
how can I convert hs to rgb?
the formula I mean
I want to do it whithin a template
is it already done somewhere in the forums or whatever?
why don't you search
I have a question about UTC times. I'm trying to format the UTC time for some goal:
- platform: time_date
display_options:- 'date_time_utc'
This:
{{ (as_timestamp(states('sensor.date_time_utc')) | timestamp_custom("%Y-%m-%d", true) ) | string }}
results in None. What do I wrong?
here, I reformatted it to work outside my code. The hue goes from 0 to 255:
{%- set hue = 255 %}
{%- 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] %}
{{ [ r, g, b ] }}
thanks a lot!
maybe it's just 0 to 1
probably is
confirmed, it is zero to 1
soi f your hue value is 255 based...
{% set hue = value /255 %}
or if its 360 based
{% set hue = value /360 %}
what's your actual endgoal here? Do you just want the current date in your TZ?
@plush willow posted a code wall, it is moved here --> https://hastebin.com/ucuxifemor
Just make a trigger template with the sunset...
template:
- trigger:
- platform: time
at: "00:00:00"
sensor:
- name: Today Sunset
device_class: timestamp
state: "{{ state_attr('sun.sun','next_setting') }}"
the value of the sensor will be utc
okay that looks much easier 🙂
it goes in template, not sensor.
thanks I will try it right now
it triggers only at midnight
if you want it to trigger at restart, you can add a restart trigger and a tempalte reload trigger. However realize that if you restarti t after the next_setting, it will be tomorrows time
indeed that was my next question....what about when the system is not running at 00:00:00
it won't trigger
you can trigger it whenever you want
midnight makes the most sense.
either way, your other template wouldn't persist during restart anyways
yes, but that piece of code of somebody else is dummy proof It will always work. I think that it is updated every second?
no, it's updated once every ~3ish minutes
actually, no it would update once a minute
okay, but back to my original question....Do you know why I cant format a utc time?
I'm living in the Netherlands...it is here now before midnight 16:09
and before sunset
ok, so your template on restart will be unavailable until you hit midnight
wait, before sunset
ok, then your template should work
meaning this should work " {{ (as_timestamp(states('sensor.date_time_utc')) | timestamp_custom("%Y-%m-%d", true) ) | string }}"
however it's not really optimized
{{ as_timestamp(states('sensor.date_time_utc')) | timestamp_custom("%Y-%m-%d", true)}}
is all you need
assuming you have sensor.date_time_utc as a sensor in your system
but you could always just not use that sensor
{{ as_timestamp(utcnow()) | timestamp_custom("%Y-%m-%d", true)}}
you don't even need to use utcnow
you could just use now
there's about 389472398473289 ways to solvethat
if the other doesn't that means sensor.date_time_utc doesn't exist
or you miss-spelled the name
or you didn't restart after adding that sensor
or the format is not a useable for as_timestamp
fyi, you can also use this
{{ utcnow().date() }}
This results in None
{{ as_timestamp(states('sensor.date_time_utc')) | timestamp_custom("%Y-%m-%d", true)}}
when I print the sensor value in the developer tools I see this
2021-12-10, 15:17
that's not valid for as_timestamp
it needs to be an iso format timestring
why do you need utc
a fully formatted timestamp is understood by all software usually
regardless of tz
okay good question.. I thought that everything is done with UTC time. My final goal is in Node-RED in a function node compare the current date time with sunset_today datetime
there I use
new Date(Date.now());
according to me that is in UTC time
okay, then I will have to look there to use the ISO dates for comparison
thanks for that petro, you saved me quite a lot of work. Works like a charm
so all you need is...
template:
- trigger:
- platform: time
at: "00:00:00"
sensor:
- name: Today Sunset
device_class: timestamp
state: "{{ state_attr('sun.sun','next_setting') }}"
yes that is a very clean option
and if you want the restarts...
template:
- trigger:
- platform: time
at: "00:00:00"
- platform: homeassistant
event: start
- platform: event
event_type: call_service
event_data:
domain: template
service: reload
sensor:
- name: Today Sunset
device_class: timestamp
state: "{{ state_attr('sun.sun','next_setting') }}"
okay the only problem I see with this version is that (sunset is here at 16:29) so when I reboot after that time.. there is a wrong datetime in the sensor (the sunset of tomorrow so 2021-12-11)
yep
okay clear
okay I will choose something 🙂 But I don't understand why Home Assistant doesn't have both attributes (current_setting and next_setting). Maybe I have to create a feature request to built this native in the framework
anyway thanks for your help!
template:
- trigger:
- platform: time
at: "00:00:00"
- platform: homeassistant
event: start
- platform: event
event_type: call_service
event_data:
domain: template
service: reload
sensor:
- name: Today Sunset
device_class: timestamp
state: >
{%- if is_state('sun.sun', 'above_horizon') %}
{%- set t = (state_attr('sun.sun','next_setting') | as_datetime).time() | string %}
{{ today_at(t.split('.')[0]) }}
{%- else %}
{{ state_attr('sun.sun','next_setting') }}
{%- endif %}
but you'll still be off by 3 minutes.
That won't go through, this was already a discussion 4 years ago.
Why aren't you just using below_horizon and above_horizon anyways
that's the whole point of the sun.sun sensor
okay strange that the team of HA not is willing to build it in......they have both values when they calculate it
what do you mean by "off by 3 minutes"?
they do not have the previous when it's calculated
okay
the sunset changes by about 3 minutes every day
well, maybe it's half of 3 minutes
either way, it's not going to be correct with your timestamp
can you explain why you want todays sunset after it already occured?
My project is:
I have an illumance sensor outside, it meassures ofcourse the lux. when the value is above 40K lux for 5 minutes my covers go down.. when below 40K lux for 25 minutes they go up.
This is the import part: it is allowed to operate for example 08:00-21:00 but when it is dark then that is the maximum operation time
But I think you are completely right.....the time is not import but below_horizon is all I need
okay 🙂
next_setting is only import when you will work with offsets I think. But for my project it is not necessary.
Thanks.
@mighty ledge , regarding the hs to rgb conversion template.. Is it possible to achieve whites with that template? (255,255,255)
A/S/L
I keep getting a template sensor flipping from a valid number to "Unavailable" in my entity card. I have an availability template but clearly it's not working as it should
state in the states database is showing some rows with "Unavailable" as the state. What I want is those to not be accepted as state changes
Trying modifying my availability template to catch is undefined
There’s an issue in the current releases where the availability template will still evaluate the state even if false on startup. It’s fixed in 2021.12
I seem to be having weird issues. Is there any way to really monitor/log the result of a rest api call?
url works fine every time I try manually and get json back. But it seems very temperamental when HA calls it
Yeah, it's working, the data as one big template to choose attributes: https://pastebin.com/LhdaGABs
🎉 you're one of the 5 people using that ability
huraah!
Did you already include me in that number? 😎
ya, you're number 4
Hello all, I have a Command line sensor and wanted to get some nested json values as attributes
- dict1
- dict1[0].value```
in the example, the first attribute (key dict1) works but the second fails. Is my syntax wrong or is this is not supported? Any ideas thanks
Try this:```
json_attributes:
- dict1
- dict1[0][value]
value has a special meaning in the template so you have to use square brackets.
Though I'm not sure if you can put a path in the attributes list.
@fossil venture thanks , i gave it a try but it doesn't work. I also thought it might be that only top level keys can be used
The new Rest sensor format allows you to create multiple sensors from the one resource.
thanks again, I had looked at json_attributes_path but for some reason cannot get my rest sensor to authenticate (maybe because it doesnt need a password but only a username.
which is why i moved to curl via command line
Hi @marble jackal ! Thank you for your response. I will ask this to #integrations-archived instead. Sorry for wrong posting. Will use the new template format. Have a great day!
Hey all, i want to create a sensor with dates from a website, but i don't understand the value_template commands.. Can you help,pls? This is the code of my sensor `sensor:
- platform: scrape
resource: http://widgets.vvo-online.de/abfahrtsmonitor/Abfahrten.do?hst=trachau&vz=0&ort=Dresden&lim=5
name: DVB
select: 'body'
value_template: '{{ value.split("],[")[0] }}'
`
use a rest sensor for that with '{{ value_json[0] }}'
how to check if my variable in the script contains multiple entities or just one?
avr_media_player:
description: "gets the correct zone player for avr"
example: media_player.avr_zone1, media_player.avr_zone2
volume:
description: "sets the volume on the avr"
example: "0.4"
source:
description: 'Correct source for playing audio - amplifier sources - AUX1,AUX2,Blu-ray,Bluetooth,SBB BOX,CD,DVD,Game,HEOS Music,Media Player,TV Audio,Tuner'
example: HEOS Music
sequence:
- choose:
- conditions: "{{not is_state(avr_media_player,'on')}}"
sequence:
avr_media_player as you can see in example: can be for example like this: media_player.avr_zone1, media_player.avr_zone2 or just media_player.avr_zone2
so I want to wait for both entities to turn on, and then to continue with a script
Is there a way to have a template sensor not update its value if a condition isn't met?
{% if states('sensor.roborock_s7_last_clean_area')|int > 10 %}
{{ ((as_timestamp(now()) - as_timestamp(states('sensor.roborock_s7_last_clean_end'))) / 86400)|round }}
{% endif %}
This works except when the template is updated and the if statement criteria isn't met, it's returning no value (None) but I want it to use the previous value it had.
Hm, looks like trigger-based template sensors might be what I need...
Ha, went full circle... ended up creating a input_datetime helper, then made an automation to update that based on a specific trigger, and finally created a template sensor to format it into a single digit days value. I bet there's an easier way but this is the only solution I could figure out 😆
`template:
- sensor:
- name: test
device_class: timestamp
state: '{{ states("input_datetime.testtest") }}'`
- name: test
now after the update I get a sensor.test rendered timestamp without timezone warning in the logs, and the sensor is not updated.
I can't figure out how it is supposed to look now.
yeah can't make it work anymore, giving up for today
I think that's an issue that oughta be reported. If you pass a datetime into an input_datetime with timezone info, it's retained within the entity, but I don't think there's a way to get it back out again. The format used for the datetime state omits the TZ info, rather than presenting it in a proper ISO format that can be parsed back out again
there was a breaking change in 2021.12 regarding formatting timestamp_local and timestamp_utc in ISO format with tz info, and I think there are more places that it needs to be done
This seems relevant: https://github.com/home-assistant/core/issues/43337
Is it possible to update an entity state through templating?
Not without using a python script. But why?
You’re just fighting the integration that provides the entity
I created a template sensor and an input_datetime helper entity. The input_datetime helper is just my way to persist a date/time stamp between HA restarts and it's being updated through an automation. I was wondering if I could just use a template trigger to update the input_datetime state instead of the automation (it would be doing the same thing, just eliminates needing to create a dedicated automation for this).
You can
It doesn't seem like there's a way to persist a template sensor state through an HA reboot without using a custom integration variable... or a helper
The template will be evaluated on startup
Are you saying that you would have a trigger-based sensor with the state being derived from the trigger variable and you want the state to persist between triggers, even across a restart?
That would make sense
This is the template trigger I'd like to use:
template:
- trigger:
- platform: numeric_state
entity_id: sensor.roborock_s7_last_clean_area
above: 100
sensor:
- name: Last Complete Vacuum
unit_of_measurement: "day(s)"
icon: "mdi:calendar-star"
state: "{{ ((as_timestamp(now()) - as_timestamp(states('sensor.roborock_s7_last_clean_end'))) / 86400)|round }}"
It will only update when that trigger hits, which is what I want, but when I restart HA, it sets it back to Unknown. I basically want to persist the state before a restart.
Couldn't figure out a way except for creating a separate helper entity and storing the value there.
I see
The state is a datetime state
Ah, so no way to retain the state other than store it in another entity (like input_datetime helper). Not a huge deal, how I have it set up now works... although I do wonder if I could just update the helper entity from the sensor template (to get rid of the automation).
I don’t think so. It’s not a script
Is there a template button integration
like template switch to create custom entities
No because buttons do not have states. They only generate events.
Anyone know whats wrong with this? 🙂
return (entity.attributes.source) + ' • ' + (Math.round(entity.attributes.volume_level / 0.01) + '%' ;
just a long-shot, but in the last part of it a ending parenthesis seems to be missing
Fixed
[[[
return (entity.attributes.source) + ' • ' + ( Math.round(entity.attributes.volume_level / 0.01)) + '%' ;
]]]```
for solar automation: how to assign a teoretical power number based on sun elevation?
why are states a requirement? i only need the button to generate a custom event that's all
Where do you plan to use this button?
@plush willow posted a code wall, it is moved here --> https://hastebin.com/xoxuyegane
@plush willow could be related to the problem I reported https://github.com/home-assistant/core/issues/61534
Okay
maybe @inner mesa knows more, I'm just a noob 🙂
please don't
sorry
I have this {{ state_attr('sensor.github_zwavejs','latest_release_tag') != states('sensor.zwavejs2mqtt_version') }}
problem is I need to add a "v" to states('sensor.zwavejs2mqtt_version')
‘v’ ~
thanks!
Because templates resolve to a state (true/false, 42, etc...). Buttons don't have a state. Sounds like all you may need is a Lovelace button with a tap action.
those buttons are huge and waste a lot of space, i just want something to put into entities list
you could just write a tiny script
wdym?
i only need the button to generate a custom event that's all
you can do that with a tiny script
it's just one command but how do i put it into entities card
- event: pump_timer
put the script in an entity card
or, as recommended, just use a button card and call the event directly
or whatever
oh that, but is there a service for running shell scripts?
your requirements keep changing
i just need to run a single command to ssh into my machine and do stuff
what exactly are you trying to do?
ok, that's quite a bit more than
i only need the button to generate a custom event that's all
i'm unused to the jargon i suppose, sorry
and i did the worst mistake you can do on support channels - asking something without telling the whole story 😦
it sounds like you want shell_command
and there are several comprehensive threads on the forum about how to ssh to another machine and run stuff
yeah i figured that out a while ago but i think most threads discuss the ssh-ing part and now how to integrate it in the best way
i think most people make a template switch but i don't want that
I don't have any shell_command entities right now, but I'm sure they can be added to an entities card as well
yeah i think shell_command will work, thank you for your help
although an integration to add custom buttons would still be better for these usecases i feel
I think it comes down to what you would actually do with them, and I suspect that there are usually better options
like, use the shell_command by itself, rather than further encapsulating it in a button entity which serves no additional purpose
if you can come up with a compelling case for a manual button entity, I'm sure the devs would appreciate a post in the feature request forum
well, right now, I have this in my configuration.yaml
switch:
- platform: command_line
switches:
pc_power_off:
command_off: "ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no user@ip sudo poweroff"
- platform: wake_on_lan
mac: mymac
name: "pc-power-on"
this creates 2 switches with no state checking which only work partially because each can only do one thing. for these i will need to create scripts, to replicate the functionality of buttons. to me it seems more logical to skip the step with making scripts and just create button entities directly.
and yeah i will make a forum post about it
thanks for the suggestion
and i figured since i have these i don't really need shell command
well, the switch with just a "turn_off" part is a little weird, and a shell_command would be more fitting if you always only want to send one command to turn it off
I think you'll find that it's pretty much the same as any theoretical button entity
I have a rest sensor which gets the serial number of a device in my network. The serial number is 16 digit number. In the entities card it is treated as a rather large number and given thousands separators (e.g. 1,234,567,890,123,456 instead of 1234567890123456). Is there any way to stop this from happening? Can my value template be altered to treat the serial number as a string?
sure but there's nothing like shell_command for wake_on_land is there?
It could expose a button entity, but the docs explain why it’s a switch. I guess you could use a manual button entity for that
Configuration question. What's wrong with this configuration.yaml code:
- sensor:
- name: "power_distri"
device_class: "energy"
unit_of_measurement: "W"
state_class: "measurement"
state: >
{% set delivered = states('sensor.power_delivered') | float) %}
{% set returned = states('sensor.power_returned') | float) %}
{{ (delivered - returned) }}```
It seems I screwed up my configuation.yaml
The configuration check passed with below (shorted) configuration:
- platform: time_date
display_options:
- 'time'
- 'date'
- platform: template
sensors:
date_templated:
value_template: "{{ now().strftime('%d %B %Y') }}"
friendly_name: ''```
This config passes without any problem but I believe I mixed up 2 things. Anyway, I'm not sure. May I use
- platform: template in the sensor section?
I don't understand all the differences...
When I copy/paste the first code I've posted, I get errors when I check my configuration:
Source: config.py:464
First occurred: December 12, 2021, 2:59:50 PM (10 occurrences)
Last logged: 10:17:23 AM
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['power_grid']['value_template']. Got "{% set delivered = states('sensor.power_delivered') | float) %} {% set returned = states('sensor.power_returned') | float) %} {{ (delivered - returned) }}". (See /config/configuration.yaml, line 122). Please check the docs at https://www.home-assistant.io/integrations/template
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][0]['state']. Got "{% set delivered = states('sensor.power_delivered') | float) %} {% set returned = states('sensor.power_returned') | float) %} {{ (delivered - returned) }}\n". (See /config/configuration.yaml, line 278).
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][0]['state']. Got "{% set delivered = states('sensor.power_delivered') | float) %} {% set returned = states('sensor.power_returned') | float) %} {{ delivered - returned }}\n". (See /config/configuration.yaml, line 278).
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][0]['state']. Got "{% set delivered = states('sensor.power_delivered') | float) %} {% set returned = states('sensor.power_returned') | float) %} {{ delivered- returned }}\n". (See /config/configuration.yaml, line 278).
Invalid config for [template]: [date_templated] is an invalid option for [template]. Check: template->sensor->0->date_templated. (See /config/configuration.yaml, line 123).```
@cinder lotus 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://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
@cinder lotus I already responded to your github issue with the solution but just for completion:
There are some opening brackets missing in line 7 and 8.
A slimmer solution would be
template:
- sensor:
- name: 'power_distri'
unit_of_measurement: "W"
state: "{{ (states('sensor.power_delivered') |float) - (states('sensor.power_returned') |float) }}"
Thanks and what about the fact that I use 'template' under the sensor section?
@cinder lotus posted a code wall, it is moved here --> https://hastebin.com/qupalojiji
I had to remove some text but it was send before I was aware of it
Who can clarify for me sections and 'sub-sections', I know this is not the correct word for it but I'm very confused now
@sonic oracle , I've copy/paste your code in the 'root' of configuration.yaml and it worked. But... I've got 0,20 Watt indication, this should be 200 Watt. The value is in kW and should be in Watt so X 1000.
I changed state: "{{ (states('sensor.power_delivered') |float) - (states('sensor.power_returned') |float)
to
state: "{{ (states('sensor.power_delivered') * 1000 |float) - (states('sensor.power_returned') * 1000 |float)
but the sensor doesn't give any data now...
Why is anything so difficult...
I've checked sensor.power_delivered and this sensor gives the value in Watt. Strange that it becomes kW in the template
Struggling to find correct selector for json_attributes on a rest sensor. The JSON that is returned is effectively:
{
"device":{
"State":"running",
"Status":"Up 18 hours"
}
}
so I'd have thought :
json_attributes:
- device.Status
But it doesn't seem to work
I've also tried - status: '{{ value_json.device.Status }}'
@cinder lotus your code should not be placed under sensor: or in sensor.yaml because it is not part of the sensor integration, but the template integration. But as your template itself is correct, this is more a topic for #integrations-archived
yeah, I've figured that you can't do anything but top level attributes with json_attributes. I've moved it to template sensor and just about got that working now
Thanks, I have many templates under my sensor integration, and rarely they all work and no errors when I do a configuration check. So it would be better to move them to the template integration...
sensor:
- platform: template
sensors:
date_templated:
value_template: "{{ now().strftime('%d %B %Y') }}"
friendly_name: '' - platform: template
and so on
But it seems the way you make the code is different
Yes, that will work, but what you posted earlier is the new template sensor format, which is part of the template integration and not of the sensor integration
Will read and try to understand...
ok so i got this automation: https://pastebin.com/p0fB0TTc
but i get error : Template variable error: 'context' is undefined when rendering '{{ 'CONFIRM_' ~ context.id }}'
its based on the actionable notification automation for the companion app
Because you have an extra ) after float in both variables you defined
are all states stored as strings?
Yes
that explains why | int on a value template to store a state into a sensor still means it comes out as a string later then
so - if I history graph a sensor like that and it gives me coloured horizontal bars for every different number - how do I get that to graph properly? For some other sensors I have used unit_of_measurement. But there doesn't appear to be a unit_of_measurement for "just a number"
unit_of_measurement is the answer. It doesn’t matter what you give it
Could be a space, I think
good evening, anyone know how to change it to float?
{{ states('sensor.pv_ac_l3_voltage') }}
i received state like "117.4"
from mqtt sensor.
{{ states('sensor.pv_ac_l3_voltage')|float }}, but I have a feeling that there's more to your question...
@brazen stone posted a code wall, it is moved here --> https://hastebin.com/refofiveku
Hi, I'm struggling with the statistic changes that have come with 2021.12. I've had a sensor monitoring Internet bandwidth working for ages using the change_rate sensor attribute provided through the old statistics module but I can't get it to work under 2021.12
I've added state_characteristics to the sensor (sensor still works providing raw data) but then whenever I try to use it in a template, I get an error of invalid input 'None' when rendering template and when using Developer Tools I don't get any attribute of the sensor for change_second.
extract from my sensor.yaml
https://hastebin.com/refofiveku
plusnet_rx is fine and has the raw data but plusnet_rx_mbps is giving me the error (hence is always 0)
Any thoughts?
Your spacing is incorrect for statistics. name, entity_id, state_char, sampling_size, and max age need to be in-line with platform.
Thanks Petro, yes they are all inline in the actual yaml file - for some reason it's made them look like they aren't when it's pasted into hastebin.
if that's the case, then the template sensor needs to be adjusted to be in line with the other platforms. That only has 2 indents where the rest have 4
Also, as a sidebar, I really doubt your sensor.plusnet_rx_stats sensor is in bytes
Thanks Petro but I think it already is. I’m not a big Discord user, so can’t seem to paste a snip from Studio Code to show you, but I don’t think that’s the issue. It’s how I’m trying to access the statistic since the update. Re-reading it, maybe it’s no longer an attribute but is the state itself (my semantics might be slightly wrong there but hope you get the idea).
It seems to be. I’m getting it from an snmp tree walk and it’s only prosumer kit, so no real snmp dictionary, so it was a bit trial and error but it seemed to match the real-time stats the router dashboard was throwing out.
Hi Johan, I suspect the *1000 should be after the conversion to float:
(states('sensor.power_delivered') | float * 1000)
and then it should work again.
