#templates-archived
1 messages · Page 124 of 1
the thing is this code looks weird because it needs to be written like this:
{ "write" : {"command": "display", "animType": "static", "animData": "1 36776 1 255 255 255 0 20", "loop": false, "palette": [], "colorType": "HSB"}
255 255 255 are the rgb colors
sorry, on phone, give me a sec
if you have more tiles they just come behind the first one. like this:
{ "write" : {"command": "display", "animType": "static", "animData": "2 36776 1 255 255 255 0 20 36666 1 255 255 255 0 20", "loop": false, "palette": [], "colorType": "HSB"}
36776 and 36666 are the id's of the tiles. i just did breakes in them to make it readable in the template.
so you can leave parts out of this code. You can for example leave 36666 1 255 255 255 0 20out of it. but you cant leave it in and not set the rgb numbers. So if i put in all the tiles like this using the {{paneel1_groen}} etc. to set the colors and a tile is not getting the data the code of that tile would be 36666 1 0 20 and this messes up the nanoleaf controller. so the whole line from id until 20 needs to be removed
So i want to check in the restcommand template if a tile is getting the data and if not the whole line needs to be removed. But i understand that this is impossible?
I really dont know how to explain it better... sorry
But i understand that this is impossible?
Can you stop with that? No-one has told you this isn't possible.
But I don't know why you don't just call the REST command multiple times in an automation to save yourself this trouble.
because i dont think the nanoleaf controller likes it to get 18 commands in a split second. its not a very fast thing. but havent tried it yet
Then put in a delay.
but home assistant supports only a seconds delay so the last tile will come up 18 seconds later?
My ESP devices can handle hundreds of messages a second. I don't know why an expensive thing like a Nanoleaf can't..
HA supports delays of under a second just fine
But maybe you should try it rather than making assumptions 😉
I think it's a dot notation for milliseconds. so 00:00:00.100
use this as your put method
nanoleaf:
url: http://192.168.178.54:16021/api/v1/token/effects
method: PUT
payload: >
{ "write" : {"command": "display", "animType": "static", "animData":
{%- set all = [ 36776, 40379, 39889, 47065, 62644, 56943, 44929, 4212, 50749, 42705, 55753, 9801, 2975, 5181, 59276, 33852, 34713, 42845 ] %}
{%- set ns = namespace(panels=[panels | count | string]) %}
{%- for panel in panels %}
{%- set ns.panels = ns.panels + [ '{} 1 {} {} {} 0 20'.format(all[panel.number-1], panel.r, panel.g, panel.b) ] %}
{%- endfor %}
"{{ ns.panels | join(' ') }}",
"loop": false, "palette": [], "colorType": "HSB"}
}
content_type: 'application/json'
then, your service will be:
- service: rest_command.nanoleaf
data:
panels:
- number: 1
r: 0
g: 0
b: 0
- number: 2
r: 0
g: 0
b: 0
- number: 3
r: 0
g: 0
b: 0
that should get you what you want
if this works i will for ever in your debt 🙂
no clue if it will work out of the box
actually, it wont, forgot quotes,
just edited, should work now
1 moment let me put this in and restart
that would be very awsome!
hmm forgot to change the token.... another restart 🤣
Error. Url: http://192.168.178.54:16021/api/v1/token/effects. Status code 400. Payload: b'{ "write" : {"command": "display", "animType": "static", "animData": "3 36776 0 255 0 0 20 40379 0 0 0 0 20 39889 0 0 0 0 20", "loop": false, "palette": [], "colorType": "HSB"} }'
bad request
i guess the b. doesnt need to be in the begining?
or is that short for something else
it's a bad request, so something isn't formatted correctly
I don't have your hardware, so the request looks good to me
but this seems very close though
ill check some more. maybe the id's arent right or something. bad request atleast means that we are close
i see the problem
there needs to be a 1 after the id
its the frame
jsut adjusted
dont ask me why it needs to be in
take a look at the previously posted template
i allready changed it. man i cant wait to see this thing working!
i must be the biggest idiot ever... just copied token back in the config... another restart 🤓
and we have a winner!!!!
@mighty ledge many thanks for your effort and patience!
np
Hi guys, can someone help me with a template code? I have a air quality sensor who is providing all kind of readings in a json format
@viral bolt posted a code wall, it is moved here --> https://paste.ubuntu.com/p/ZgJKbd77Xs/
what I want is to interrogate this sensor every 2-3 minutes and from one reading to extract a number of sensors: temp, pressure etc. If i make a reading for each parameter the sensor gets overloaded and I get many missing readings
i'm trying with this code but i get an error:
@viral bolt posted a code wall, it is moved here --> https://paste.ubuntu.com/p/NtswPxchzk/
Please stop posting code walls...
@viral bolt 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/.
What's the error?
Template variable error: dict object has no element 0 when rendering '{{ value_json[0].temp }}
Right. So that means you're telling it to get the first thing from a list but it doesn't think it's a list.
Is "data" part of the response, as well as all the stuff after it?
yep
You want something more like this:
value_template: "{{ value_json.data }}"
Then what you have for json_attributes will grab all the individual ones.
oky, i'll give it a try, thanks
If you want just the temperature in the state and still to get all the attributes, it'd be more like this:
value_template: "{{ value_json.data.temp }}"```
And keep what you have for the `json_attributes`
I'm trying to track down some warnings in my logs, and I've got a bunch of value_json errors. https://pastebin.ubuntu.com/p/YRB84k8p4g/
Any idea where I should look? I can't even find value_json in any of my configuration files.
it's coming from MQTT discovery
hmm. Okay. It mentioned it was a template variable. so I wan't sure. I'll have to see what I can track down.
Does anyone know how to turn on an entity if one entity in a group is on?
I tried this:
{% if 'on' in [ states.binary_sensor.zoom_eliot, binary_sensor.zoom_eliot_s_school_account ] %}
but the sensor isn't avalible
If one entity in the group is on, isn't the entire group marked as on?
Sorry, the entites aren't grouped.
even if the other entities are off.
Is that just a better way to do that then?
Yeah, because then you could just call a service to turn on the group when it turns on (seems redundant) and it'll turn on the remaining entities. As long as they're controllable entities. Binary_sensors aren't.
I don't actually need to control the group. I'm just trying to monitor the status of two zoom accounts
And if one or both is on. Yeah, try a group then.
Yeah, you could change the friendly_name based upon a template in a customize statement
If > 0 binary sensors are on, the group should get marked as on. I believe it works as an OR statement to determine the group status.
Right, I'm just trying to make the state of the entity readable, so not as a 0 or 1. I'll just use a template entity
Yeah, if you need something immediately human readable, a template sensor will work as well.
I'm trying to read the current value from my shelly smart plug as a float, not an integer... This is what my sensor looks like now:
- platform: mqtt
name: "Fireplace Current"
state_topic: "tele/shelly_smart_plug_fireplace/SENSOR"
value_template: '{{ value_json["ENERGY"]["Current"] }}'
unit_of_measurement: "A"
can I just remove the value_json['ENERGY'] to get the actual float value of current?
this is using tasmota, BTW
MQTT has a value of 0.009 A and I need to read that value, not 0
so, no, you cannot just not parse the JSON
sorry, learning 😦
lemme see if there's documentation on value_json... maybe I can use something other than energy
value_json is just letting you index into the JSON. it doesn't know anything about the structure of that JSON
so value_json.Current would work?
{"Time":"2021-04-14T21:52:37","ENERGY":{"TotalStartTime":"2020-12-26T22:39:32","Total":3.154,"Yesterday":0.225,"Today":2.928,"Period":0,"Power":0,"ApparentPower":1,"ReactivePower":1,"Factor":0.21,"Voltage":121,"Current":0.008}}
ah... I see... current is under energy
ok, so no, you cannot just remove the "ENERGY" part, because "Current" is a child
yes
so why is it returning an integer and not a float?
you can try adding |float
boom... thanks Rob!
Is there a way to use a template to do an If / Then statement for a serial sensor?
I tried doing this:
- platform: template
sensors:
zone_sensor:
friendly_name: NilesZone
value_template: "{% if is_state('{{ states('sensor.file_value').split(';')[0] }}', 'usc') %}
{{ states('sensor.serial_sensor').split(',')[3] | float }}
{% endif %}"
but I obviously have a syntax error somewhere or maybe its not able to do that
you have a multi-line template without formatting it as such
or actually, that might work with the quotes, but it's hard to read
I'll tell you what I am attempting to do and maybe my whole approach is wrong
I am sending commands to a Niles audio zone controller
using command line in HA
you need an {% else %} in there or you'll end up with no value at some point
and that will be a syntax error
and depending on the function it spits out either:
usc,2,1,0,0,32,0,0,0
or something liek this
rznt,12,OK
So I need a sensor to look for the messages that start with USC
that will probably do it, but like I said, you need an else
because you can't have no value
I tried adding {% else %}
still getting syntax error
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token ',', got 'sensor') for dictionary value @ data['sensors']['zone_sensor']['value_template']. Got "{% if is_state('{{ states('sensor.file_value').split(';')[0] }}', 'usc') %} {{ states('sensor.serial_sensor').split(',')[3] | float }} {% else %} {% endif %}". (See ?, line ?).
ah
understand the problemn?
Yes
it's like you wrote value_template:
So what would I say if I want it to do nothing in the else function
but I don't think that's the only problem based on the error
oh, you're nesting {{ }} inside. that's bad
yeah, there's some brokenness in there
SO this nested if statement
{% if is_state('{{ states('sensor.file_value').split(';')[0] }}', 'usc') %}
is probably broken
value_template: >-
{% if states('sensor.file_value').split(';')[0] == 'usc' %}
{{ states('sensor.serial_sensor').split(',')[3] | float }}
{% else %} ""
{% endif %}
something like that
Error loading /config/configuration.yaml: mapping values are not allowed here
in "/config/configuration.yaml", line 183, column 24
Ya, its a weird problem
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.
\\ - platform: template
sensors:
zone_sensor:
friendly_name: NilesZone
value_template: >-
{% if states('sensor.file_value').split(';')[0] == 'usc' %}
{{ states('sensor.serial_sensor').split(',')[3] | float }}
{% endif %}
"proper formatting"
oops
as above
sensors:
zone_sensor:
friendly_name: NilesZone
value_template: >-
{% if states('sensor.file_value').split(';')[0] == 'usc' %}
{{ states('sensor.serial_sensor').split(',')[3] | float }}
{% endif %}
you're still missing the else
Oh ya. Duh
and your spacing is off
I'll try fix
- platform: template
sensors:
zone_sensor:
friendly_name: NilesZone
value_template: >-
{% if states('sensor.file_value').split(';')[0] == 'usc' %}
{{ states('sensor.serial_sensor').split(',')[3] | float }}
{% else %} "foo"
{% endif %}
assuming all that string manipulating is correct for your input
Is there a way to use a template to set the attribute of an entity in customise.yaml?
I... don't know what you're trying to do.
Sounds like a job for a template sensor though 😉
Template sensors could solve the world's problems
Let me rephrase my question: I'm trying to assign an attribute of an entity to the value of a different entity
So... a template sensor 😉
You don't set the values of entities. Let integrations take care of that.
Can't you set them through customize.yaml?
Statically, maybe. Dynamically... template sensor.
Okay, thanks :)
And I don't know if you noticed... but you have red on you.
Anyone have experience with Serial sensor
You may have more chance in #integrations-archived
Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
Hi, untill now I tried the group method which didn't work.
Today I am building an automation based on what you sent. I'll update once finished.
The one mono recommend also didn't work. I kept getting messages from entities without moving.
Bacuse I already created the text entities, I am also testing my idea...
I'll try to sum it up for others to come
Can anyone tell me why that would result in just 0.0 as a value from this output:
serial_port: /dev/ttyUSB0
baudrate: 38400
- platform: template
sensors:
zone_sensor:
friendly_name: NilesZone
value_template: "{{ states('sensor.serial_sensor') | float}}"```
when the serial output is
usc,2,1,0,0,48,0,0,0
because that output is a string and "foo"|float -> 0.0
what's the point of even creating the second sensor?
I need to parse the output
usc,1 is the response code
the rest are all settings
Zone, Input, Mute, Volume, Bass, Treble, Balance
basically, I am trying to get the status of a multizone audio controller
using serial RS232
what do you want this sensor to actually output?
I need a list of these
Zone, Input, Mute, Volume, Bass, Treble, Balance
so that I can set the state of the buttons
the problem with it is it only outputs the active zone at any time
so I need to make a script that will set it to zone 1, output, then zone 2, output, etc through zone 6
And then probably return it to the zone that was active at the start of the script
if its always the same format in the same pattern you can do states(...).split('.')[<pos>] to pull out the individual items
I was trying to do that, but was getting unknowns or 0.0
don't cast to float
so I wanted to simply get the output first so I can see that the serial data is actually making it to HA first
If I remove | float
it just stays as Unknown
and turned on debugging, but dont get any output
from serial
Then your entity_id is wrong in the value_template states() method
how'd you arrive at sensor.serial_sensor?
from this example
Are you saying the variable is wrong
Actually, now testing I think I am going to have to abandon using there serial sensor
It appears to tie up the serial port
so I can't send the outgoing commands I need
going to have to do it a different way
for future referece, don't use examples and assume they will match your configuration. When you create a sensor, the first thing you should check is what the entity_id is by searching your own system.
Will this template retrieve the last state of the entity if the sensor attribute disappears?
{% if state_attr('sensor.orbi_router','WAN In (total)') == None %} {{ states('sensor.orbi_router_wan_in_total') }}
No. If it's disappeared, there's no state to read.
This is a value_template
Templates only know 'now', they have no concept of history. You'll probably want to use an automation to set an input text each time it changes, unless the change is to None/Unavailable.
If things keep going unavailable, the better option would be to fix the underlying problem,.
Gotcha. For a template that has a unit_of_measurement, what happens when it receives a non number? How does the graph react?
I haven't seen it before. I would guess that it just misses that point on the graph.
or it's zero
Ok. There's no way to get the last known state of an entity in a value_template, right?
Ah ok thanks 👍
Can someone point me in the right direction because I'm not sure it's templates that I need. I have a binary_sensor that is misleading. https://ibb.co/WFgLR6M (picture). I want the binary_sensor.game to show "on" if the wattage is over 25 watts meaning that the console is on and being used. How do i accomplish this with an if statement or variable to either change the binary_sensor or make a new one?
That's probably going to be a threshold sensor, which you can ask more about in #integrations-archived
Ok. Thank you @ivory delta
You haven't said what the problem is.
Hi i have question. i am using template sensor for my hot water usage, and i am getting this reading from it ,,daily water 0.8455m3 how do i narrow it down to 0.8 m3 ?
|round(1) will round it, but you may need to do .split('m')[0]|float|round(1)
if the units are really part of the state
and i am also using last week sensor witch shows with this reading 18.9902m3 but i would like get this reading 18.99m3 witch is easy to read.
same answer
here is my value_template: value_template: "{{ (states('sensor.daily_water')|float * (states('input_number.notkunargjald_m3'))|float) | round(3)}}"
i changed it round (1) but no luck
you don't need the parens around the state() call. |float binds tightly
looks like you're just rounding the last value?
you have too many parens in there
so how do i do this ?
value_template: "{{ (states('sensor.daily_water')|float * states('input_number.notkunargjald_m3')|float)|round(1) }}"
sorry if i am mispelling my english writing sometimes comes out messy 
hold on i will check
just put it in
-> Templates
monthly_energy:
friendly_name: Mánaðar orkunotkun
icon_template: mdi:counter
value_template: >-
{{ (states('sensor.monthly_energy_day')|float)|round(1) }}
unit_of_measurement: m³
i get zero reading
check on this tomorow thanks anyway
This is always returning clear?
return entity.state === 'on' ? 'Motion Detected' : 'Clear';
]]]```
Any ideas on what I'm doing wrong? The entity is an input_boolean
This seems to be a problem with either button_card, or browser_mod.
Moving to #frontend-archived
Is there a way to just execute a template in a script to setup some variables?
sequence: >
{% do something %}
- service: domain.whatever
I think that's valid, actually.
damn, okay so i'm trying to basically use a script as a function to create a loop based upon passed variables.
then just call it with data:
- data:
title: "Leak Detector Heartbeat Missed!"
message: "{{ trigger.to_state.name }} heartbeat missed!"
service: script.notify_iphone
and that can be it's own sequence item?
the script?
that came from an automation, but yes, that can be part of a script
scripts can call other scripts
I'm passing data into a script, need to do some quick math on it, and then run a loop. That's pretty much it.
So if I can just do a data block in the script sequence, that's perfect.
Does anyone know how to check a list of sensors for the ones that are enabled, and then report the first one that you see (in a javascript template?) I have this: https://pastebin.ubuntu.com/p/QNWDqD7gvn/ but it's always returning 'Clear'
Ignore the formatting of the first line, pastebin likes to mess with it
read through that doc page, and note the difference between passing variables when calling a script like service: script.xxxx and service: script.turn_on
one requires a variables: block and the other does not
I've always passed by calling as a service, but I've never seen the fields: blocks before. That's actually really nice for documentation.
Ah, my repo is in the cookbook, so I have to make sure my shit's well commented.
It forces me to do so and then I don't go back and wonder wtf I was doing, lol.
var deck = states['input_boolean.deck_motion_sensor'] == 'on' ? 'De' : 'X';
This reads X even though input_boolean.deck_motion_sensor is on. Any ideas what could be causing that?
This piece of code just doesn't like me
Having an issue with variable typing. Is there a way to convert a variable from one type to another, or do I have to use a type() function every time the variable is referenced? Issue at L40. https://pastebin.ubuntu.com/p/B32cmz2qjr/
like set foo = foo|float?
Morning - I'm using Post to get entity states into HA. The problem is they disappear when HA restarts until they get posted in. If I make a template sensor for each with a dummy value woudl that mean the state sticks over restarts?
the post API is only for development purposes afaik
Anyone know how to design and implement a full theme for HomeAssistant?
Please DO NOT cross post. Read the channel description, post it and wait for folks to respond.
If you don't get any responses after an hour or more, and your message is no longer on screen, it is fine to re-post or post a link to it.
Hi all
I have a quick question
I would like to add meteo alarm in my config.yaml file
But after doing those little lines into the config and restarting hassio again
I get a information on my entity binary_sensor meteo alarm that i have no uniqueid for it.
The hassio wiki has no example to set in unique id in the yaml. Can anyone tell me where i have to put unique id and how i have to do it?
binary_sensor:
- platform: meteoalarm
Unique_id: „testmeteo“
country: "NL"
province: "Groningen"
Is that right?
This isn't a template question, next time ask in #integrations-archived . Also, that integration doesn't support unique_id's so there's nothing you can do to fix that.
Made a script for changing my theme manual. Anyone now if it’s possible to use one script to let’s say set theme black and if theme is black set theme white.
Yeah, either using something like float(strVar) or strVar | float. I'm trying to make sure that the data that gets passed into the script is typed correctly so that I can use it to calculate another variable. So, do I need to do that every single time, or can I specify a data type somewhere and have it stick?
Okay, I'm at a point in my script where I'm getting a division by zero error, and I have no idea where it's coming from. None of my divisors should be 0 from what I've given the script as parameters, and the templates all execute correctly in the dev tools page. Does anyone have any ideas? https://pastebin.ubuntu.com/p/fKgN3Dx98D/
Where's it saying the error is?
That's a pretty long script for you to expect someone to read all of and guess.
Saying that... I don't think it does what you think it does. It's doubtful that it knows the value of count at line 49 before it's used on line 54.
If you have something that's dependent on being evaluated in a particular sequence, you'll want to actually template that stuff to be evaluated so.
There's only 2 spots it could come from.
count: >
"{{ ((( ending_brightness | float - starting_brightness | float )
/ interval | float ) | abs | round | int ) }}"
step: >
"{{ ((( ending_brightness | float - starting_brightness | float )
/ count | float ) | round | int ) }}"
if interval_pct is 0, you'll get a divide by zero
if ending_brightness - starting_brightness is zero, you'll get a divide by zero
you don't protect against either of those
That’s what I was thinking, but I’m also not passing it anything that should be erroneous. I’ll try hard coding a value once I get back to my computer.
you set any of the pct values to zero all those others will be dividing by zero.
0 is a valid pct
How can I template a sensor to have the value 0 if it's reported as unavailable?
I have a template that reports the value of another sensor if it is between 0-100, but if that sensor is unavailable, my template sensor also shows as unavailable
If statement checking if the state equals unavailable
or unknown
plenty of examples out there
@mighty ledge Got it working. I think the issue was that I was encapsulating some of the templates in quotes, and it was being interpreted as a string value, which converted to a 0. Now to add in some parameter checks for if a 0 is actually passed. https://pastebin.ubuntu.com/p/ZRX88vXTMS/
Putting this here to celebrate upcoming template fun: https://community.home-assistant.io/t/fyi-new-jinja-tests-coming-soon-search-and-match/300171 🎉
Mmmm, that juicy RegEx goodness.
oh that'll make life much easier
Yes. We'll certainly see fewer questions.
Lol, start sending people to https://regex101.com/
@mighty ledge Why, though? My current statement checks if the value is <= 100 and >= 0, wouldn't that exclude anything that isn't in that range, including, unavailable and unknown?
I still refer to that almost every time I write a regular expression, even as a full time dev. Even if you know RegEx, it's still a great tool to validate a ton of inputs at once.
Quicker than coding a bunch of unit tests 
Hm, alright. Now I changed it to >= 1, but it still shows as unavailable if the sensor in the value template is unavailable?
y tho
{% if ((state_attr('light.sofflampa_vardagsrum', 'brightness')) / 2.54) | float | round (0) <= 100 and ((state_attr('light.sofflampa_vardagsrum', 'brightness')) / 2.54) | float | round (0) >= 1 %}
{{ ((state_attr('light.sofflampa_vardagsrum', 'brightness')) / 2.54) | float | round (0) }}
{% else %}
0
{% endif %}```
Same. I've been using regex for years, but I'll never trust myself to do it blind.
If I have a command line sensor, that outputs in CSV
I know command line sensor can get multiple values via JSON
but can I do the same using csv output?
usc,2,2,0,0,59,0,0,0
Still working on this? 🙂
I would use your command line sensor to pull the payload and a template sensor to populate attributes based on the state of the command line sensor
Yep Sure am
I have made a lot of progress though
Using PySerial command line now
So I run the command, and it outputs to this: usc,2,2,0,0,59,0,0,0
name: NilesCurrentZone
command: "python3 pyserialtest.py znc,5"
value_template: "{{ value.split(',')[2]}}"```
Then I am grabbing the zone using that value templaet
but wondering how I can break out all of the sensor data
instead of just isolating the 1
The template sensor that I mentioned
Ohhh, I see what you mean
Gotcha, so dont do the value split in the command line sensor, have it take in all the data
Right
then do a template sensor to pull it apart
😄
Right on
Thanks
BOOM. That works perfectly
And just like that, after 4 or 5 days I take a old useless zone controller and make it work in Home assistant. Or I could have taken my valuable time and did something else and just bought a fully supported monoprice 🤣
Hello
how can I write this in the Lovelace yaml file?
value_template: >-
{% if not is_state('sensor.asciugatrice_program_progress', 'unavailable') %}true{% endif %}
found! 🙂
- entity: sensor.asciugatrice_program_progress
state_not: 'unavailable'
I have a list which is bascially a list of files in directory, is there a simple filter to display the number of images? for example
[
"/path/image1.jpg",
"/path/test.mp4",
"/path/image2.jpg",
"/path/test1.mp4"
]
The above is the list which is returned for {{ state_attr('sensor.camera1','file_list')}} I can apply length to get the number of files like this
{{ state_attr('sensor.camera1','file_list') | length }}. However, is there a filter to get the length for only the .jpg or .mp4?
You can map the results and use a RegEx to test the extensions, sure.
| map('regex_search','YOUR-REGEX-HERE') | select('true') | list | count
There's a PR open that should make that simpler but that doesn't help you today.
{{states('sensor.valueA') | float|round(2)}} 99.99
{{states('sensor.valueB') | float|round(2)}} 88.88
{{states('sensor.valueA') | float|round(2) + states('sensor.valueB') | float|round(2)}} 188.876462945
Why when adding two floats with two decimal places does it result in an answer longer than 2 decimals?
Looks like i need to watch more videos.. Normally i would bracket the result of the two sums then round that (excel math) but the syntax is new to me and i'm getting errors when doing that
Thanks for pointing me in right direction.
Hello, please, I want set up the temperature sensor with min and max value of the last 24 hours. But the min value which is displayed is not tru value, for example: it display 8°C, but real value was 4.6°C. thank you https://paste.ubuntu.com/p/685SJ7YRys/
You should probably use the statistics sensor instead. You can ask for more information in #integrations-archived if you need more help with it.
since my file_list is just a list - will I be able to do a map? Ah - please ignore, had to pipe to a true and got the results - thanks!
@modern torrent posted a code wall, it is moved here --> https://paste.ubuntu.com/p/n76QjWPx2Q/
Okay that was too long, I hope someone can help me anyway, or should i try posting my question again with some pastes instead of codeblocks?
Yeah, just a little too long, given the rules are 15 lines or less...
@modern torrent 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/.
Is it always the second item in the list that you want or does the order vary?
Yes its always the last one i want, but i hope its always the second one
so if the last one is not possible, i am totally fine with alwys the second one
{{ states.sensor.ping_test_cron.attributes.report.hubs[1].host }}
Use square brackets and a number to pick the item from a list (counting from 0, not from 1).
ohh damn i was so close then, i thought this would work, but it didnt :
{{ states.sensor.ping_test_cron.attributes.report.hubs.host[1] }}
But this works, thank you 😄
I have an additional question, trying to get "Loss%" in that case doesnt work, i assume due to the % in the name, how would i solve that?
i solved it by editing it with tr (and remove "%") and printing it into a file
Then the sensor is using cat and gets the values that way)
you could have just done states.sensor.ping_test_cron.attributes.report.hubs[0]['Loss%']
it pays to look at examples 😉
@raven token posted a code wall, it is moved here --> https://paste.ubuntu.com/p/SFM4brZzjJ/
Hi! Can someone help me with a switch template that calls a service? I had a look at the switch template page but can’t figure it out. When the switch is turned on I want to call the following service: nissan_leaf.start_charge and has the VIN of my car for the data input. The switch should turn off when the binary sensor (binary_sensor.leaf1spre_charging_status) changes to off.
There’s an example of a service call with data here in the docs: https://www.home-assistant.io/integrations/switch.template/#multiple-actions-for-turn_on-or-turn_off
You would need an automation to turn the switch off when the sensor turns off
Hi there,
I'm working on a notification where I want the payload to show who opened the door. I got it working the Developer Tools->Services but once I add it to my automation I'm getting errors. I don't understand why it doesn't work in the automation.
Can this be done from an automation? Thanks fyhelp!
YAML code:
https://paste.ubuntu.com/p/QfH2fkXVGf/
Log errors:
https://paste.ubuntu.com/p/cqPhW6XWhZ/
First, context is only populated from a user if the user interacted with the interface. Otherwise your hardware has no idea who interacted with the hardware.
Second, when pulling an item from the collection, the collection needs to have something in it. Because your id was not found, the collection was empty, causing the first error and subsequent errors
ahh so the automation was "triggered" by a secondary action so the context is not taken from that action?
Hi there has anything changed with templates recently? I had an automation calling a script with template variables and it no longer works.
Dumb idea: can I target a specific device type based on model number?
entity_id: >
{% for device in domain.light %}
{{ if device.model == "value"
- {{ device }}
{{ endif }}
{% end %}
I'm thinking it should be possible, but just not sure where I should look for that value. I know it's in the device information, but I don't know how to probe that instead of an entity.
The idea is to be able to set a z-wave parameter on multiple homogenous devices from a single script call.
My current scenario is changing the lights on all of my inovelli switches to red when the alarm is armed, and green when it's not. Or something like that.
it was triggered by the hardware, 7 people could be logged into home assistant, which person used the hardware?
An error that was ignored is now raised to the user. See the breaking changes.
If you're referring to device in the context of home assistant, no, you cannot do anything in templates with devices at the current time.
Yes, I mean device in the HA context as in "a device has many entities". That's kinda lame. I don't think there's anywhere else to access that information. Perhaps I can just manually define it as a group and pass a service the group entity.
You'll have to just list the entity_id's out
you can't call a zwave.set_param on a group
Boo, lol. Oh well, it was worth a shot.
Hi everyone,
I'm trying to create a template sensor that estimates if my apple tv state is "playing" and the content type is "video". When i use the youtube app the media_content_type attribute is not available. Since I only use youtube to play videos I would like to include the "app_name" attribute "YouTube" to detect video playback.
How do I get my "or" condition to work correctly?
- platform: template
sensors:
apple_tv_state:
friendly_name: A movie is playing
value_template: >-
{{ is_state('media_player.living_room_apple_tv', 'playing') and
is_state_attr('media_player.living_room_apple_tv', 'media_content_type', 'video') }} or
is_state_attr('media_player.living_room_apple_tv', 'app_name', 'YouTube') }}
Use parentheses and get rid of the }} in the middle
Or something like that. The }} doesn’t belong there
I don’t fully understand the logic you’re trying to represent
I need a binary sensor that defaults to true if video content is playing to prevent my motion controlled lights from turning on.
is just checked with template validator and like this it seems to work
{{ is_state('media_player.living_room_apple_tv', 'playing') and
is_state_attr('media_player.living_room_apple_tv', 'media_content_type', 'video') or
is_state_attr('media_player.living_room_apple_tv', 'app_name', 'YouTube') }}
I don't know why but the attribute "media_content_type" is not always available
If it's not playing, it won't have a media type.
not in my case
for e.g its playing video content via youtube right now
https://ibb.co/2tDBBT6
Maybe it just can't tell 🤷♂️
Do you have an atv and does it tell the video state in any case?
I want to link the conditions this way: if is "playing" and (media_content_type is video or app_name is Youtube)
Then write it like that with parens to enforce order of operations
I did see that but don't believe it should be affecting me. I simply can't get any templates variables to work when passed to a script. I also don't see anything in the logs
How are you passing the variables?
I've tried a bunch of methods but this is what I've been trying to get working. I previously had it working but sometime between last year and now, it stopped working. https://paste.ubuntu.com/p/SFM4brZzjJ/
Remove the word variables between data and program
Tried that. Also doesn't work
Then you did it wrong. Try it again
Umm its definitely not working?
I do that all the time
Also, you don’t need to turn on a script. Just call the script as the service
https://hatebin.com/puszdybftr
I've also tried calling it as the service and that also doesn't work oddly enough
So I was able to get this working, but still can't get it working if I template the '1'
service: script.pool_pump_cancel_boolean
data:
program: '1'
If you’re using the script caller you can’t template unless your on 2021.4+
I'm on 2021.4.5
Either way, I tried it with both the old method and the new method. Passing a 1 as a string using {{ '1' }} doesn't work while just doing '1' works fine
Don’t know what to tell you. Check out my automations and scripts. I do this all over the place. You can template those fields.
So weird because I literally had this working last year and sometime between now and then, it stopped working... I tried restarting and doing all kinds of stuff but it just will not work
Always check the errors in your logs
Look at the doorbell automation and script
Hmm well I think that might be right then. I do see errors in the logs when I do {{ '1' }} because it can't concatenate int to str, but when I do {{ '{0:d}'.format(1) }}, it doesn't do anything even though I know that should give 1 as a string
Variables have typing now, numbers will be resolved as a number
Even if you want it to be a string
Well now that might be doing it
I do remember seeing that change a while back
Wept that fixed it. Thanks @mighty ledge! Just needed to convert the int to a string in the script itself
Hi guys, I'm busy integrating a pannel heater which is flashed with Tasmota as an MQTT climate device in to my home assistant setup. The problem that I'm stuck on at the moment is getting HA to send out an MQTT payload with a set string and then the temperature value from the climate entity. e.g. SetTemperature=25 where "SetTemperature=" is a constant string and the 25 is the temperature value. Does snyone know how to achieve this? I've spent at least 12 hours trying to figure it out.
what have you tried?
seems like it would be as simple as payload_template: SetTemperature={{state_attr('climate.xxx', 'temperature')}}
or however you're arriving at your temperature
@carmine crag Otherwise, I'm curious what you arrived at in 12 hours 🙂
much typing going on
I arrived at a lot of frustration and lost sleep! I'm just getting started with home assistant so a lot of it was spent on figuring out how to define entities and link the mqtt topics in the config file. Going from an embedded C programming mindset to this has been a challenge, especially with figuring out the templates. I'll try your suggestion later.
What should I replace the "xxx" with in your example? The entity name?
where is your temperature coming from?
the slider of the climate entity
is it the state of that entity?
to publish via MQTT, you just need to set up the MQTT integration as per: https://www.home-assistant.io/integrations/mqtt/
and then publish as per https://www.home-assistant.io/docs/mqtt/service/
and templates are well-documented here: https://www.home-assistant.io/docs/configuration/templating/
climate.xxx is just the name of the climate entity, whatever yours is
- platform: my_mqtt
name: "Livingroom Heater"
so in this example it would be 'climate.Livingroom Heater'?
unlikely that platform: my_mqtt is a thing
oops, platform: mqtt
what's the rest of it?
I'm at work at the moment so dont have access to my ha server
When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
if you mean something like this (from the docs):
climate:
- platform: mqtt
name: Study
modes:
- "off"
- "heat"
- "auto"
mode_command_topic: "study/ac/mode/set"
mode_state_topic: "study/ac/mode/state"
mode_state_template: "{{ value_json }}"
the entity would be climate.study. Entities are all lowercase, with _ replacing spaces and other puncutation
but you can just find it in
-> States
@carmine crag posted a code wall, it is moved here --> https://paste.ubuntu.com/p/3rVK4JCwyc/
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
so, climate.livingroom_heater
perfect, makes sense that there's no space
just check in
-> States when it's unclear
thanks mate! will test it out tonight. the learning curve is definitely quite steep once you get into the more custom components
yeah, that MQTT climate platform is pretty complicated
one more question while I have your attention, how do I define the modes so that I can switch the heater on and off from the lovelace card? from what I have seen the modes defines what buttons you have on the card but the power button only switches teh unit off so tis only sending the "off" payload to the command topic
usually the "on" state is one of the modes - heat, cool, auto, etc.
but I don't know anything about that platform
fair enough, I do have a switch that does send the correct command but thats something that was added by mqtt auto discovery. the heating button doesnt seem to send anything out an any of the topics. guess that'll be the next thing to figure out.
there are a million config parameters for that, so I gotta believe you can make it do anything you want
finally upgraded HA, and am getting warnings in the logs,
The 'speeds' option near /config/configuration.yaml:17 is deprecated, please remove it from your configuration
The 'speed_template' option near /config/configuration.yaml:17 is deprecated, please remove it from your configuration
The 'set_speed' option near /config/configuration.yaml:17 is deprecated, please remove it from your configuration
I'm trying to find out what the current way is for setting up fans, that appears as lights, as fans in HA, but am coming up empty handed. Anyone able to guide me in the right direction?
i have a template that writes a time value;
- service: input_text.set_value
data:
value: |-
{{ 'Justin East Window -
{}'.format(now().strftime('%a, %b %d at %I:%M %p')) }}
entity_id: input_text.lastusedss
and shows as;
Justin South Window - Sun, Apr 18 at 09:29 PM
but is there a way to get in the UI relative time since this state was last changed?
ex; last changed 2 hours 5 mins ago
ok so 'temperature' doesnt seem to work. it seems to be sending out "SetTemperature=None"
I've tried target_temperature as well and that doesnt work either. cant seem to figure out how to get the value of the slider.
ok so I have managed to get some basic functionality out of my climate entity configuration. I can switch the heater on and off and the temperature and state are displayed properly. what I cant get working ifor some reason is setting the temperature based on the slider value. every time I change the slider a MQTT message is sent out but there's no target temperature in it. Here's my current config if anyone can pont me in the right direction:
@carmine crag posted a code wall, it is moved here --> https://paste.ubuntu.com/p/FcZVm2PVCb/
Test the template first in
-> Templates
How would I take this: https://paste.ubuntu.com/p/hzcsgCZxq6/ (The atributes to sensor.hacs)
And get: "fontawesome, Start Spotify on chromecast"
(A comma separated list of the display names of all the updates available)
{{ state_attr("sensor.hacs", "repositories") | map(attribute="display_name")|join(", ") }}
my list is currently empty, but this works on your sample data in place of state_attr() @oak summit
excuse the seemingly stupid question but what is "
-> Templates" and how do I get there?
You literally find
on the sidebar and click it
I know what I want to do, but I don't know what its called 😄
I'm trying to make a notification automation for a couple of water sensors, and I'm having issues with putting the offending device name in the message body
https://paste.ubuntu.com/p/ZJtqk5w8GC/
ha ha, Developer Tools!
I'm pretty sure its gotta be in yaml, because ui editor throws some error
well there's no errors and the result of the template is what I see eing published on the mqtt topic:
temperature_command_template: SetTemperature=None
then you need to identify the attribute you want
"some error"?
Visual editor is not supported for this configuration:
Templates not supported in visual editorYou can still edit your config in YAML.
that's not an error
trigger.state isn't a thing
you just need trigger.to_state.name for the name, and trigger.to_state.state for the state
so still no idea how to get the target temperature from the climate slider. I've tried these and more:
temperature_command_template: SetTemperature={{state_attr("climate.toma_heater","desired_temperature")}}
temperature_command_template: SetTemperature={{state_attr("climate.toma_heater","target_temperature")}}
also, interestingly enough "current_temperature" does give me the format that I want but the value is obviously not the one that I want.
How on earth do I identify the attribute of the temperature slider? according to the documentation ist targe_temperature but that gives me "None" as well. fml
-> States
seems like I'm catching up, just set "temperature: 25" and it set the target temperature of my heater. this is great but there's still a disconnect between the slider and the temperature variable
so whenever I move the temperature slider it sets the climate entity's mode to "off" which then sets the temperature to "null"
hello, I jsut wanted to check following code with you guys if I need to convert to string
data_template:
entity_id: input_text.vacation_lights
value: "{{ state_attr('group.simulation_lights','entity_id') | random }}"```
Im getting correct value in my templates editor
switch.livingroom_coridor_main_light but I think I need to convert it into string in order to add to my input_text ?
Templates return strings anyway 🤷♂️
Unless they don’t
Fairly certain they always do and HA just knows when to attempt to cast them to another data type.
I tried just this to read from input_text
and I got an error
I think the problem is in reading the input_text.vacation_lights entity either in writing to it
okay so I got trigger.entity_id to return something, but I'd like the friendly name, but I can't find that in the document, google makes me think that maybe I'm trying to find an attribute?
trigger.to_state.name
Error: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'
is that because run action is a poor way of testing?
go to developer and just enter low battery values into state and wait?
That’s one way
im happy to learn another
No, that’s fine
how to escape f.e. "current_temperature_template":"{{value_json['TuyaSNS']['Temperature']}}" that needs to be in an automation mqtt publish payload field? currently its trying to parse value_json when triggered
You're aresome! thanks!
Is anyone able to tell me what this warning relates to? https://www.dropbox.com/s/p5yrf4a7swcimud/Screenshot 2021-04-20 at 11.24.14.png?dl=0
I've been having some stability issues with HA and it may correlate with https://www.dropbox.com/s/vh89pawcb5zsnw7/Screenshot 2021-04-20 at 11.25.55.png?dl=0
Pictures of text 🤢
I've just found a thread with the same pictures! https://community.home-assistant.io/t/help-needed-with-automation-and-json-template-warning/297258/12
No solution tho!
That's just means there's another person out there sharing text in a sub-optimal form 🤷♂️
To answer your original question though... it's pretty self-explanatory. At the time of rendering those templates, value_json didn't have the properties your templates are trying to read.
Unless you share your config (as text and using a sharing tool if it's over 15 lines), it's hard to say more.
Could that cause the out of memory issue?
Almost definitely not...
That's usually going to be because people run way too much on kids toys like the Raspberry Pi.
I'm running on a VM...Its been quite happy with 2GB of RAM until now....I've added a further 2GB to it and still it happens
Hi eveyone, new to this place!
Really having troubles with templating; and i should continu with templating or AppDaemon.
From an email i get a date in Dutch "1 mei 2021" (English 1th May 2021). I can get this string from the mail, but i can't use this date as it's Dutch.
i can extract the day, year; but the month is difficult: Mei = May = 05.
Any ideas how to achieve this?
You want the number of the month based on the Dutch name for the month?
Just use an array of the names and find their index (add one at the end, since computers count from zero):
{{ months.index('mei') + 1 }}```
ok that is something i'm looking for.
But can i do all of this in the value template of a sensor?
Sure, why not? You can do multi-line templates 😉
ok first i use this:
{{ state_attr('sensor.boekingen_imap_sensor','body') | regex_findall_index("Datum:\s\d+\s(\w+)\s") }}
to get written month name; I need to store this first in a variable i guess?
or i can put this directly in to the ('mei') part i guess!
If it were me, I'd track the different date components as variables just to make it easier to read. But yes, you can do it in-line if you prefer.
awesome!
{% set months = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli','augustus','september','oktober','november','december'] %}
{{ months.index(state_attr('sensor.boekingen_imap_sensor','body') | regex_findall_index("Datum:\s\d+\s(\w+)\s")) + 1 }}
This just works! love Hass
- platform: scrape
name: 'Ethereum Exodus balans'
resource: "https://etherscan.io/address/0x82fbed465c16679c6dc8e4d8c2dfecd097175fb8"
select: ".col-md-8"
I was told. If I wanted this output to be a float instead of a string. I had to use a value_template. Could somebody help me setup this template?
Im trying to get just the number from my eth balance and not the extra Ether part at the end.
Show what the data looks like, what you want it to look like and what you've tried so far...
Thanks a lot!
Awesome, got all the date/time correct and sent the extracted data to my Google Calendar! awesome awesome.
Maybe you have a solution to sent this data to a MySql table INSERT?
All i could find about this is using the AppDaemon, but i rather prefer to do this in an automation. Possible?
- platform: scrape
name: 'Ethereum Exodus balans'
resource: "https://etherscan.io/address/0xc9ff4626a871d8355bf6877abe1f5a1e19fedd8d"
select: ".col-md-8"
For this code the output is:
0.080919784866627016 Ether
I just want to get rid of the 'Ether' part so it's a float instead of a string. Do you know how?
Did a search on this Discord, but seems only 1 person asked about this, and was in May 2021 and didnt get any help with it... 🤣 So will be a challenge i guess!
May 2018 🙂 lol
I'm trying to set up an automation to take the incoming caller ID as per https://www.sipgate.io/push-api/api-references
It sends the POST request using application/x-www-form-urlencoded
Has anyone got an example of how this should be parsed?
From what I read it should use a filter and 'urlencode' but I'm not sure exactly what this means
This is the data
data: __type: <class 'multidict._multidict.MultiDictProxy'> repr: >- <MultiDictProxy('event': 'newCall', 'direction': 'in', 'from': '447976002117', 'to': '441416111332', 'callId': '54566B150B0C0D3A5D53435F57597E57525B575D535E515A785E515B45524252434747585A57', 'origCallId': '54566B150B0C0D3A5D53435F57597E57525B575D535E515A785E515B45524252434747585A57', 'user[]': 'A8ree', 'userId[]': 'w0', 'fullUserId[]': '1631325w0', 'xcid': '92de953efcecfc7a')>
If it always looks like that, you just need to 'split' the string at the space and take the first part:
{{ value.split(' ')[0] }}
If what you're doing next with it needs a float, you can cast it to a float - but templates will return strings anyway.
This is giving me an error:
can not read an implicit mapping pair; a colon is missed at line 46, column 48:
... ate: '{{ value.split(' ')[0] }}'
^
The arrow points at the blank space between the ' '
You need to mix quotes. If you're using single quotes inside a template, wrap the template with double quotes.
Which way round doesn't matter but you can't use the same inside and around.
Aha, the Ether part is now gone, which is great. Although it seems like the next template:
- platform: template
sensors:
ethereum_waarde:
friendly_name: 'Ethereum waarde'
value_template: "{{ (((states('sensor.Ethereum_Exodus_balans') | float) + (states('sensor.Ethereum_Bitvavo_balans') | float)) * (states('sensor.cryptoinfo_ethereum_ethereum_eur') | float)) | round(2) }}"
unit_of_measurement: '€'
Isn't able to add the 2 values together and multiply it by the worth of ethereum.
I know for sure the Ethereum sensor for the ethereum worth (which is: sensor.cryptoinfo_ethereum_ethereum_eur) is outputet correctly. Do you know how to work around this problem?
The output I get from the template is 0.0
Test the template at Dev Tools > Templates. Substitute in values in place of the states() functions if you want to experiment with different values.
I forgot to put the sensor.cryptoinfo_ethereum_ethereum_eur into the code since I was working in my test instance. Thanks anyway! It works now 🙂
I am trying to include a criteria for a template sensor that will be used in an occupancy sensor. My issue is only with the last line of this code. I know it is wrong as it wont pass the config check at all.
sensors:
living_room_occupied:
value_template: >-
{{ is_state('binary_sensor.front_door', 'on')
or is_state('binary_sensor.living_room_mot_n', 'on')
or is_state('binary_sensor.living_room_mot_s', 'on')
or is_state ('sensor.living_room_grideye_occu_count'| float > 1') }}```
The idea is that it basically "or grideye has a value of less than 1"
BTW just fixed the space after is_state and took the ' out
It now passes but I'll see if it works.
your parens are in the wrong place
actually, it's just wrong 🙂
states('sensor.living_room_grideye_occu_count')|float > 1
Yeah I figured as much no offence taken I'm still trying to figure out this template stuff.
see this whole page, and this section in particular: https://www.home-assistant.io/docs/configuration/templating/#states-examples
it has exactly that
Ok cool thanks that is a much better doc than I was trying to learn from
You could simplify that template a lot by putting the 3 sensor sensors into a group.
@ivory delta how would that look?
Even better... wrap the Grideye sensor in a template binary sensor (same logic, count > 1) and include that in the group.
Groups allow the user to combine multiple entities into one.
Cool I'll take a look at that
Templates can be really powerful and do stuff that wouldn't normally be possible otherwise - but for some things, it's simpler to use the built-in tools.
@silver basin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/MrjtM3CYxm/
Hey folks!
I am trying to create a sensor using API that I can make automations with, based on zones.
My problem is that I cannot get my sensor to act as a tracker.
So far I have this - any ideas?
https://paste.ubuntu.com/p/MrjtM3CYxm/
give the sensor a state and attach it to a person. That's the only way you can get home assistant to perform the calc. Otherwise you have to do it yourself in the state.
Thank you Petro.
Do I do this even though it is a vessel i'm tracking and not a person?
I am trying to parse some data from an API, but cant get the value. all the attributes are parsed except the value.
- platform: rest
name: Covid19 München Total Cases
resource: https://api.corona-zahlen.org/districts/09162
value_template: "{{ value_json.data.09162.cases}}"
json_attributes_path: "$.data.09162"
json_attributes:
- deaths
- weekIncidence
- casesPer100k
- delta
scan_interval: 3600
Your template is invalid. You should use square braces to access keys whose names start with numbers.
{{ value_json.data['09162'].cases }}
thanks. it's working now.
yep
I have have the attributes in the attached link for sensor.grocy_chores (from the custom component). Is there a way to extract, for example, "next_estimated_execution_time" for "id: 2" ? https://paste.ubuntu.com/p/7YzKbVw43h/
I got it. For reference: {{ states.sensor.grocy_chores.attributes.chores.2.next_estimated_execution_time }}
FYI, the correct way to access an item in a list is like this: chores[2]. The fact that yours works is just down to a quirk of Jinja/HA and doesn't reflect how you'd normally access list items.
good to know, thanks
This attribute is coming across as a string so as_timestamp is not reading it correctly. Is there a way to convert this? next_estimated_execution_time: '2022-04-01T00:00:00+00:00'
Look into strptime
as_timestamp should work fine with that string
The attribute for {{ (states.sensor.grocy_chores.attributes.chores[1].next_estimated_execution_time) }} is "2021-05-01T00:00:00+00:00". For {{ as_timestamp(states.sensor.grocy_chores.attributes.chores[1].next_estimated_execution_time) | timestamp_custom ('%b %-d, %Y')}} it is "Apr 30, 2021"
timestamp_custom ('%b %-d, %Y', false)
ok, that worked but why? What does "false" do?
treats it as utc
I just realized it is still not pulling the correct date. The attached is pasted from the HA Attributes in Developer Tools. The attribute should be '2022-04-01T00:00:00+00:00' but {{ (states.sensor.grocy_chores.attributes.chores[1].next_estimated_execution_time) }} is returning "2021-05-01T00:00:00+00:00". https://paste.ubuntu.com/p/7YzKbVw43h/
figured it out, I was assuming that [1] corresponded to the ID:1. I realize now that it is positional and if I change [1] to [0] it is pulling the correct date
Hi guys, can someone provide any help with Rest sensor templating? I believe JSON format...but not being an expert
In case someone has a couple of minutes...here are details of the issue I have
replace value_json.value with value_json ?
then sensors are no more published
Can anyone help me out with setting up a template binary sensor? I have tuya contact sensors which I’ve “integrated” by setting up switches based on them connecting to my router (they connect for 2 mins every time their state changes). I set it to turn on a switch when they connect and turn it off when they connect again but I’d rather have it as a sensor. I know I could have the sensor based on the switch but it feels like a long route, so want to remove the switch.
Tl;dr: How do I make my template binary sensor to show as open when a device_tracker is home and then show as closed next time that device_tracker is home?
you can put whatever logic you want for the value_template: for your sensor
Tl;dr: How do I make my template binary sensor to show as open when a device_tracker is home and then show as closed next time that device_tracker is home?
You don't. Templates have no concept of history.
I know I could have the sensor based on the switch
This is how you should do it...
nevermind. misread that curious requirement 🙂
Hi Does anyone have any thoughts as to why "{{ state_attr('weather.home_hourly', 'condition') }}" does not work for the met.no integration? It just returns "none"? I would very much like to use the met.no integration to populate "condition_template:" in the weather template (the rest I populate with my own rain and wind sensors
If there is a way to "grep" the condition from the forecast array string you get by passing "{{ state_attr('weather.home_hourly', 'forecast') }}" I am welcome to suggestion. Applogize if these are noob questions, but I’m only a few days into HA converting from OHAB
@stiff summit posted a code wall, it is moved here --> https://paste.ubuntu.com/p/4fxsyPj2kB/
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
so the 0 is the first index of the array forecast
and you ask for the value condition?
{{ state_attr('weather.home_hourly', 'forecast')[0]['condition'] }}
trying to grasp the syntax here : )
[] is indexing into something. in this case, I'm both indexing into a list ("[0]") to get the first element and into a dict to get the value associated with a key (["condition"])
Hi, I tried a few but always had the log spammed
if you need to retain a state over a period of time, then the template sensor itself isn't enough
I have a custom sensor that gives the beaufort name + meters per second as a string, I recon it would be quite a lot of work to strongarm this into the wind speed section of the weather template?
it is not clear if you are replying to this: https://community.home-assistant.io/t/rpi-ha-monitor-and-issue-with-rest-template-sensor/301670
your value_template is accessing value inside the json
does value exist inside the json?
Thanks.. Just seemed like an extra step I could maybe do away with but will do that 👍
Also, as an FYI, you put your post in the hardware section on the forums but you're asking a question about your configuration. That question should have gone in configuration, you probably would have gotten a response quickly if you did that.
See in the post the json example: some values exists...
does value exist in your json?
spoiler: No
🙂 so what I should put in the config there?
Ok, I will try
If I put like “cpu_free” will it anyway create a sensor for each json attribute field?
no, you'll get 1 sensor with 7 attributes
Mmm i see, ok tomorrow I will do some test: thank you very much in the meanwhile
I am trying again. Anyone who can see what I am doing wrong? This is my sensor:
- platform: rest
name: 'Qnap TS-410 version'
resource: http://update.qnap.com/FirmwareRelease.xml
json_attributes_path: "$.[docRoot].[storage].[model].[?(@.modelName == TS-410)].[firmware]"
json_attributes:- version
value_template: '{{ value_json.version }}'
- version
And I get this error: Template variable warning: 'dict object' has no attribute 'version' when rendering '{{ value_json.version }}'
Can somebody maybe help me with a template, or tell me what I want to do is even possible?
I have a list with items, e.g. a, b, c, d, e, f, g
I have an input_text which has some of these items (comma seperated) e.g. b, e, g
I now want to take a random item from the list, but not if it is mentioned in the input text.
I found something like this:
{% for i in range(11) %}
{{ i }}
{% endfor %}
But if I use that, it gives me Invalid config for [automation]: invalid template (TemplateSyntaxError: expected token 'in', got '|') for dictionary value @ data['action'][1]['choose'][0]['sequence'][0]['variables']['song']. Got None. (See ?, line ?).
More background. I have a tag scanner, and want to play a song when the card is scanned. But not one of the last 3 played songs.
This is my full code I have now: https://paste.ubuntu.com/p/qwTWm7bk7x/
It tells you the error: expected token 'in', got '|'. You have for songs | random in last_played, which is invalid syntax.
You can't just put random stuff in the middle or the for...in and hope it'll work.
There's also no need for loops when you can use filters (see the pinned message):
{% set songs = ['a', 'b', 'c', 'd', 'e', 'f'] %}
{{ songs | reject('in', input_text) | list | random }}```
I haven't tested whether that behaves correctly with different data types. 'a, b, c' isn't the same as ['a', 'b', 'c'].
@marble jackal ☝️
That template returns a random element of songs that isn't present in input_text. You can update it to actually use entities, that's just a demo that'll work in
> Templates
Thanks a lot! I will give it a try
My code for the change of the input_text was not correct, but after adding ,1 in the split it works like a charm. Had to change the max of the input_text to 255 as it could not contain 5 items.
Any idea how I can get this API sensor data in to home assistant? I have it configured on an excel spreadsheet to scrape data from Vanguard's API
but can't seem to figure out how to get it thru HA
You'd use a RESTful sensor, which is an #integrations-archived
that's what I thought - I'm putting it in to template editor in the dev tools but guessing it doesn't actually update it and I'd have to just add it as a sensor and reboot?
sensor:
- platform: rest
resource: https://api.vanguard.com/rs/gre/gra/1.7.0/datasets/urd-product-details?path=[id=vanguard-ftse-global-all-cap-index-fund-gbp-acc][0].navPrice.value
does that look right?
oh I see, haha, thanks 😄
ok so if the above works and yields the result I kind of want but with "168" and not just 168, do I need a template sensor in ADDITION to the restful sensor or instead?
You should define a value_template to manipulate the response: https://www.home-assistant.io/integrations/sensor.rest#value_template
If you just want everything between the quotes, use split() and pick the element you want from the resulting list. This should do the trick:
{{ value.split('"')[1] }}
Breaks your value into a list of values that were separated by double quotes. Takes the second part (not the empty value before the first quotes or after the last one).
Sorry, I'm relatively new to this and trying to hobble things together. You're saying then that I need:
sensor:
- platform: rest
resource: https://api.vanguard.com/rs/gre/gra/1.7.0/datasets/urd-product-details?path=[id=vanguard-ftse-global-all-cap-index-fund-gbp-acc][0].navPrice.value
value_template: {{ value.split('"')[1] }}
?
Sure, except you need to either wrap your template in quotes or make it a multi-line template.
In this case, despite it being a simple one-liner, I'd go with the latter... you already have a mix of single and double quotes, so you can't wrap it with either without escape characters 😄
{{ value.split('"')[1] }}```
template editor is saying: "UndefinedError: 'value' is undefined"
but I wonder if that's because it doesn't show restful sensors properly?
Where? Dev Tools? It doesn't know about the integration there.
yeah, that's what I thought. I'll just chuck it in and reload
I appreciate the help. I always feel like I've got 80% of the picture with HA and that last little bit seems impossible to me 😄
There's a lot to learn. I've been doing this for a year and I'm a software engineer, yet there's still stuff I take a while to pick up.
haha as an English teacher that makes me feel a bit better about my lack of expertise 😄
It's all just syntax. You just have a different corpus to pick up now 😉
and learn new words like "elif"
That's just 'file' backwards 
haha yeah exactly...I've got that one in the ol' bank already
I have a collection of various different formatting language and ways of doing things but when I have to do something new it's a bit of a wall, especially if nobody has tried to do the thing I'm doing before
your suggestion worked a charm, btw, I've got two sensors now using that API and formatted without the " "
thanks so much!
another completely useless thing in my HA instance 😄
im trying to create a date +64 days from a input_datetime. I was trying to use a templaye sensor for the date value (not sure if thats best), but i dont know what im doing. I thought something like this could work?
- platform: template
sensors:
room2_end:
value_template: '{{ ((states.input_datetime.room2_start_day.state) + (64) ) }}'
unit_of_measurement: 'Date'
you want timedelta: https://www.home-assistant.io/docs/configuration/templating/#time
states('input_datetime.room2_start_day') + timedelta(days=64)
awsome! let me try that
I'm not sure you want this though:
unit_of_measurement: 'Date'
It's not a graphable number if it's just a date.
I also think that the state needs to be turned into a datetime
and as tom_l says in that thread:
timedelta() has turned out to be much less useful than I thought it would be because my datetime helpers aren’t datetime objects.
timedelta is getting me on the right track
that thread has a solution
i really green here
it would be cool if an input_datetime had an attribute that was equal to its state, but retained the datetime type
should be easy enough to add here:
https://github.com/home-assistant/core/blob/dev/homeassistant/components/input_datetime/__init__.py#L358
attrs["native_type"] = self._current_datetime
something like that could work
right, I think it would be trivial to add
I'm still struggling with how to format this
room2_end:
value_template: '{{ strptime(states("input_datetime.room2_start_day"), "%Y-%m-%d %H:%M:%S") + timedelta(days=64) }}'
unit_of_measurement: 'Date'
TemplateError('TypeError: can only concatenate str (not "datetime.timedelta") to str') while processing template 'Template("{{ strptime(states("input_datetime.room2_start_day"), "%Y-%m-%d %H:%M:%S") + timedelta(days=64) }}")' for attribute '_state' in entity 'sensor.room2_end'
5:02:10 PM – (ERROR) Template
Error while processing template: Template("{{ strptime(states("input_datetime.room2_start_day"), "%Y-%m-%d %H:%M:%S") + timedelta(days=64) }}")
5:02:10 PM – (ERROR) helpers/template.py
now, we're basically undoing what the integration is doing for the state: https://github.com/home-assistant/core/blob/686c92097fb1ab44c6d9d377c54d70d987412adf/homeassistant/components/input_datetime/__init__.py#L308
seems like your strptime failed to parse so it returned the original string
lol, case in point 🙂
@sour acorn make sure to vote: https://community.home-assistant.io/t/make-typed-states-available-for-entities/301996
I voted it
any idea whats wrong with my formatting, or is there a different approach?
what is the output of {{ states("input_datetime.room2_start_day") }} ?
this alternative (using the timestamp) may be easier to handle:
`{{ state_attr('input_datetime.fridge_1_filter_changedate', 'timestamp')
- timedelta(days=change_days).seconds | timestamp_local() }}`
it always takes me a bunch of trial-and-error to get the date/time formatting right
hmm, that should be right. this is what its using for datetime '%Y-%m-%d %H:%M:%S'
gotta verify against the actual output though
editable: true
has_date: true
has_time: false
year: 2021
month: 3
day: 15
timestamp: 1615791600
friendly_name: Room2 Start Day
can try it
ok rebooting now, i think i tried that before, but maybe i had something else incorrect
that worked!
thanks @inner mesa & @dreamy sinew
states.sun.sun.attributes.next_setting returns a string value of the time in UTC, I want to do time operations on it, do I really need to strptime on it and construct the format to parse it with?
There has to be an easier way to do this?
as_timestamp() converts datetime object or string to UNIX timestamp. This function also be used as a filter.
Yes but that causes me another issue, I'm trying to do datetime operations and that returns a float.
{{ as_timestamp(states.sun.sun.attributes.next_setting) - now()}} causes TypeError: unsupported operand type(s) for -: 'float' and 'datetime.datetime' instead of a string error.
could make now() a timestamp but then I still have to convert back, just seems like a big back and forth. I just want to make sure I"m not missing the simple way.
I’m happy to use strptime. I just don’t want to miss a simpler way possibly
It seems silly and in my humble opinion you should file an issue. There’s no reason for it to be a string
Nah, just upvote the existing feature request. It's not a bug.
timedelta 😉
Yeah I’ll poke and maybe just send a patch.
It's even listed in the section of the page I linked you to.
But does timedelta take strings :p
I’ll poke. Just seems silly. I’ll see how hard it is to just patch the sun object and send a PR
If you’re taking about the one I filed, that’s more for the state. This one is already an attribute, just lacking useful type info. Boo
Gotcha
I'll bring it up in the dev channel but to round this off it does call a string type return return { <snip> STATE_ATTR_NEXT_RISING: self.next_rising.isoformat(), STATE_ATTR_NEXT_SETTING: self.next_setting.isoformat(), <snip> }
Fix should be simple but it'll break LOTS
so possibly just add additional attributes.
Since datetime types are displayed properly, I don’t know why it would be converted to a string
isoformat seems to return a string to me looking at the python builtin function itself. Anywho, I'll dig further.
definitely returns a string 😦 >>> type(datetime.now().isoformat()) <class 'str'>
taking this over to #devs_core-archived
hi is there an way to do math calu. for json_attribute in command line sensor template here my current template https://ghostbin.co/paste/qov4hmj
hi my friends! im struggleing with yaml i guess. this script: https://www.codepile.net/pile/JKbyYrZV
results in this error: Error. Url: http://192.168.1.220/light/0?brightness=0. Status code 400. Payload: None
as variables are involved its tricky to debug the yaml synatx with the dev tool. can you help me ?
400 is "bad request", so what happens if you send that via POST with curl or Postman or some other tool?
is that what you expect ti to send?
The Script is based on this automatoin, which is working just fine: https://www.codepile.net/pile/MvLaAYrP
it is almost what i expect. the value for brightness should be different from zero
Share the REST command.
you can't nest {{ }} like that
they're just variables
rather than '{{ min_bright }}' | float, just do min_bright|float
you can just set the variables in
-> Templates and test your template
how to set variables in dev tools ?
{% set ip_address=xxxx %}
ok thx
there's an example right in the demo template text
What am I missing? I don't see nested templates.
I don't see an answer to Rob's earlier question either: #templates-archived message
brightness_value: >
{{ (('{{ min_bright }}' | float) +
(state_attr('switch.adaptive_lighting_general', 'brightness_pct') |
float )*0.01*(('{{ max_bright }}' | float) - ('{{ min_bright }}' |
float) )) | int }}
The HTTP method is important. It defaults to GET and you likely need POST. But since you haven't tested that... 🤷♂️
no i havent tested to use post with curl or postman, i guess im rather a rookie
first step is to test the command and get it working, second is to integrate it into HA
curl is quite straightforward
Built things incrementally. Don't throw 10 things together at once and hope it works.
Postman is even more straightforward 😄
i appreaciate your help guys thx
its working with, as no more nested {{}} are used ... now i will try (once again) to dig intu GET and POST 😀
I just figured out that a decimal number in a value_template: requires a leading zero to parse successfully. Version: core-2021.4.4 The log message was that somewhere in the 1,202 line automations.yaml file a value_template: had an unexpected "." Yes, I'd made several changes at once...
This is invalid in an automation template condition:
value_template: "{{ (states('sensor.sample') | float) >= .15 }}"
But this is valid:
value_template: "{{ (states('sensor.sample') | float) >= 0.15 }}"
Got a few questions on FB about conversions (Metric > Imperial) maybe a good idea to put some examples on the HA intergration page ?
@zinc leaf To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.
Also, feel free to delete the duplicate 😉
yeah I know i ff-ed up
``sensor:
- platform: template
sensors:
bimmer_range:
friendly_name: "Bimmer Range"
unit_of_measurement: "miles"
value_template: "{{ (states('sensor.i3_rex_remaining_range_electric') | float / 1.6) | round(2) }}"
``
It's okay. Just tidy up after yourself. You can right click your posts to edit instead of removing them completely.
3 backticks at each end, not one 🙂
i forgot it was backticks... thought it was''
Single backticks are good for inline code but multiline code is better with triple backticks:
some:
yaml: thing```
But what I said ... would be a nice addition
Som people have something to base there conversions on
some*
This information is all over the forums and anyone can edit the docs.
@nocturne chasm : but somehow people are not finding it
There are many, many things that could be written about templates. It's impossible to document every variation for such a versatile templating engine.
If you think an example is worth including in the docs, include it.
anyone can edit the docs.
Note that HA allows you to pick your measurement choice for the whole system. If you try to change it for a one off sensor it'll just get converted back
There's that too 😄
A google search produced this as the first hit, not sure what else you can do
https://community.home-assistant.io/t/how-to-convert-km-h-to-mph/215825
Are there any better tools for pulling json values from a restful sensor that don't include restart home assistant every time I make the slightest change?
Not really. Changes to integrations usually require a restart - unless it's one of the categories listed in the config page.
Is there a way to parse multiple lists? My JSON is formatted [{"val1":"value1","val2":"value2"},{"val1":"value1","val2":"value2"}] and I haven't found a way to have a rest sensor bring that data onboard in a usable form. The rest of my sensors work, but the JSON is formatted differently than this one.
That’s one list containing 2 dicts. What are you trying to get out of it?
Would like to pull value2 from each dict. Below is how I've tried to access it:
- platform: rest
resource: #api url
name: data
scan_interval: 60
value_template: "{{ value_json.state }}"
# json_attributes_path: "$"
json_attributes:
- 0
- 1
I thought I would access them by $.0.val1, but the data doesn't show up in the sensor for me to access attributes
I don’t have much experience with it, but you should be able to experiment with jq
I have tried so many variations of the value template to get something out of this. I'm not even sure I can access data from different dicts in one restful sensor
Maybe not. A sensor can only return a single value
Kind of. Typically you'll pull in a dict and that restful sensor will have mulitple attributes that can be accessed, from which you can create more sensors or reference that data directly.
Ah, ok
I'm trying to create a template sensor that will check if it is between the hours of 8am and 10pm and also that a user is home and has been home for at least 10 minutes. I'm hoping to check the value of this sensor for sending reminders of things that need to be done around the house. I only want the notifications during these hours and I don't want them right when I walk in the door.
I've got now().hour > 7 and now().hour < 22. I'm wondering how I would make it's only true if person.name is home for x minutes
That sounds like it could be done a lot easier with an automation than a sensor.
and just update a binary_sensor?
(as_timestamp(now()) - as_timestamp(states.person.person_name.last_changed)) / 60 > 10 and now().hour > 7 and now().hour < 22
I could use some help templating the max temp forecast out of the weather home entety.
when I do {{ state_attr('weather.home', 'forecast' ) }} I get the json formated data like
[{'condition': 'cloudy', ...., 'temperature': 13.0, 'templow': 2.4,}]
``` but I have a hard time to filter out the `forecast[0].temperature` value
A hard time how? What have you tried?
things like this {{ state_attr('weather.home', 'forecast[0].temperature') }}
here is something!
#templates-archived message
I tryed it that way already but it failed me 😆 probably added a filter.
this works now
{{state_attr('weather.home', 'forecast')[0].temperature }}
Thaks for jumping in mono
Is it possible to get the in-/external_url of homeassistant to show in a template? I couldn't find something like {{ homeassistant.external_url }}
Not that I know of. Templates are usually used for things that change though - how often are you expecting your URL's to change? 🤔
Not at all. But was curious if it was possible. I was looking into sending the correct url if you are home/not-home
You can get the public ip with the myip integration "{{ states('sensor.myip') }}"
Thanks Tom for the idea
My problem is a non-issue, as I'm always using Wireguard. so it's always local...
Ah, ok.
I have a bunch of sensors from my washing machine, on for each program avilable, indicating which program is active. Can I create a template sensor to check which of these sensors are on? Only one sensor can be on at any given time....
What do you want the sensor’s state to be?
But yes, you can use a template to change the state based on which sensor is active
Are they all binary sensors?
If so, you don't even need a template... just make a group.
Actually, I just noticed they are not sensors, but switches...
But I suppose the general rule still applies?
I was hoping the state could be (part of) the entity_id of the single switch that has state on...
Entity IDs are not dynamic
No. I was hoping the state of the template sensor could be the entity_id of the switch that was currently on?
I was thinking the template could iterate over the switches and return only the one that had state on...?
How do I approach filtering the switches based on state?
They all have predictable entity_ids, like switch.wau28p_program_<program_name>.
{% for i in states.switch if i.object_id.startswith('family_room') %}
{{ i.entity_id if is_state(i.entity_id, 'on') }}
{% endfor %}
it will get easier in the next HA release with search/match Jinja tests
test_sensor:
value_template: >-
{%- for i in states.switch if i.object_id.startswith('family_room') -%}
{{ i.entity_id if is_state(i.entity_id, 'on') }}
{%- endfor -%}
Perfect! Just the thing I was hoping to acheive! 😘
you probably need to guard it for when none are on
{{ states.switch | selectattr('entity_id', 'in', ['switch.family_room_watch_roku', 'switch.family_room_watch_shield'])|selectattr('state', '==', 'on')|map(attribute='entity_id')|first}}
The only time that will happen is when the washer is off....
What are the consequences?
it will fail because the template will be empty
boo. "None" is now a special case
test_sensor:
value_template: >-
{% set entities=states.switch | selectattr('entity_id', 'in', ['switch.family_room_watch_roku', 'switch.family_room_watch_shield'])|selectattr('state', '==', 'on')|map(attribute='entity_id')|list%}
{{ entities|first if entities|length != 0 else "Not Running" }}
works
Let me try to adapt that! 🙂
filtering based on entity_id will get much easier in 2021.5 and you won't need to list all the entities individually. Or you can adapt the for loop from earlier
You know what... I will wait for the beta and try this then. I have a basic working thing, thanks to you! Guarding it for edge-cases can wait...
🙂
I have what I need for now:
How do I display a timestamp as a time in hh:mm am/pm format? I'm trying to display the time my shades will close which is sunset + 15 minutes so this gets me the correct timestamp, I just can't figure out how to display it: {{ as_timestamp(state_attr('sun.sun', 'next_setting')) + 900 }}
I've tried | datetimeformat, | timestamp_to_time, and |strftime with no luck
thank you!
{{ as_timestamp(now())|timestamp_custom("%I:%M %p") }}
oh that's perfect, I'm so happy I'm finally getting my frontend cleaned up for tablets after months of putting it off
Hi y'all! Anyone able to help me figuring out the right template for a condition for which user scanned a NFC-tag?
I have the path syntax to the user_ID as $.context.user_id, but can't figure out how to point to that in a template. I was thinking this would be right: {% if trigger.event.data["context"]["user_id"] == f644f45672e54aaf93d4d504c7baf9cf %}
Nevermind, got it, the template was trigger.event.context["user_id"] instead, the new automation tracer is great
So I've got a template on a markdown card to display "Lights:" + the name of any rooms with lights on. The way I have it now I have to iterate states.light twice: once to get a count of rooms with lights on since I don't display the "Lights:" header if there are none, and again to list the rooms. Is there a cleaner way to do this? This is my first real stab at templating: https://zerobin.net/?c2b2b1b7dea2d409#tGz5HElQDfS6tGzm6UlqL+uIPu4BgecM/2bMDVj+8uM=
oh, I thought about adding them all to a list, then using the list's count to decide if the header should show, then finally displaying the list, but I couldn't figure out how to append items to the list
You might get some inspiration from this: #templates-archived message
Yeah, you can’t append like that
I did get inspiration from that, but unfortunately I needed to filter my light entities on those with entity_ids ending in "all" and afaik I can't do that with selectattr
Or selectattr, but yeah. Next HA build
kk, I'll make a cleanup pass then, thanks again
hi guys, based on my limited googling skills, templates seems to be the place if want to store a variable?
Not really
Look at the input_* helpers, like input_number
Templates have variables, and scripts can define variables for use within the script, but they all have limited scope
i want to store a variable for use as a conditional in automations
where can i find input_ helpers?
i just add it myself?
You follow the instructions for what you need
okay. cant be done via UI right?
Is there a way to set a backup value if the sensor is unavailable in this template? I thought default() was the answer but doesn't seem to work as expected
as_timestamp(states(''sensor.master_bedroom_clock_alarms''))|timestamp_custom(''%H:%M'')
{{ as_timestamp('unavailable')|timestamp_custom('%H:%M')|default('07:10') }}
This is what I thought should work, but the template returns None
Scrap that, I worked it out:
{{ as_timestamp(states('sensor.master_bedroom_clock_alarms'))|timestamp_custom('%H:%M') or '07:10' }}
Can someone tell me why:
{% set live = states('sensor.opwekken_live') | float %}
{% set usage = states('sensor.verbruik_kw') | float %}
{% set kw = 1000 %}
{{ (live - usage) * kw | round(0) }}
sometimes still gives a value of XXXX,9999999998 While its rounded to 0?
{{ ((live - usage) * kw ) |round() }}?
howdy 🙂
is there an easy way to get time spent in a previous state w/o saving that data to an input field?
for example: trigger: door sensor closes, and the condition for the action would need to be "if it was open for less than 10 minutes"
I keep doing a dumb if != none and != unavailable and != unknown. Not nice, but never lets down 🙂
@unreal merlin thanks that fixed it!
I have a sensor that has a timestamp as state. This is the estimated time when the washing machine is finished. How do I calculate the time between now and that state?
Currently the sensor has the state 2021-04-26T11:02:57.515786+00:00
Would using ... or #your default variable not work in your instance as well?
Hi all I was wondering if someone can help me with a template (if it is possible to create a template to achieve what I want to achieve). Basically my goal is to broadcast messages dinamically, based on media_player status (!= playing) and binary_sensor status (only for device_class = motion). I found a way to greate a group for media players what are not playing and of course the same can be done for binary_sensor in on status. But how to combine them? Can somehow area_id be useful? Every media_player and binary_sensor have a area_id attribute in my config. I'm not that good in templating so I definitely ask your support to understand if this is possible and how to do that. Thank you in advance
I got a template sensor for an esp32 with a co2-sensor, rewriting the value with changing ppm levels works fine but if the sensor is offline the last value is still displayed.. is the else statement not valid when the esp is offline (== the sensor value is unavailable)? --> https://nopaste.ml/?l=yaml#XQAAAQDaAQAAAAAAAAAQapmMJu4e3iJbP3A2mxXTBWnOwH7gw2TDJqdwlA9QkUIQQFPf7lMhaKPDyk6B4LgvuB4q1dQ4Gkc119tSIlpygAveQG9Hzzh73qvIdA7sEW4b68TXiooFouOZQGjN/p7/iQSMpQgyljdgBJANNBjNBQIKQzOzgFXYK8s1ahoQKC8W3Bxz1Ztd83c/QHVUBlAiiZH4ZT//w3I7Zw==
dang what a huge nopaste url, sry
ah and the value above 1000 does not work too :/
ah this one works: https://pastebin.com/HbqMVTw8
I have a template fan (Inovelli LZW36 Light+Fan controller shows up as 2 light levels, so I use a template fan to create an actual fan and map speeds) that I need to convert from the old 'Speed' templates to the new 'Percentage' templates. Anyone here have a working example of a template fan that I can reference? Thanks.
I am doing a template sensor, is there a way to make sure the system sees the state parameter as Fahrenheit degrees?
ground_floor_zone_temperature:
friendly_name: "Ground Floor Temperature"
unit_of_measurement: "??????"
value_template: "{{ state_attr('climate.ground_floor', 'current_temperature') }}" ``` whatever i put in the unit of measurement just seems to be a text label? i think i have done something wrong?
I'd start by giving it a proper device class: https://www.home-assistant.io/integrations/sensor/#device-class
cool that sets the icon however the text in the template docs says "Sets the class of the device, changing the device state and icon that is displayed on the UI (see below). It does not set the unit_of_measurement."
is unit of measurement just temperature?
problem is when i set 'temperature' i just get this displayed https://imgur.com/hHZK0Iq
The unit of measurement is whatever unit you want displayed...
If you want '°F', then use that.
oh, lol, i didn't think it could be arbitrary unit
I have another sensor that reports in deg C but displays in deg F - so i assumed there was way to make sure the system could cope with tmperature display units being diff from underlying data, i can live with this solution 🙂
im having trouble formating this, im just trying to subtract 200 from a input_number for a trigger and condition
trigger:
- platform: numeric_state
entity_id: sensor.2_co2_sensor
below: "{{ states('input_number.2_co2_on') | float - 200 }}"
condition:
- condition: numeric_state
entity_id: sensor.2_co2_sensor
below: "{{ states('input_number.2_co2_on') | float - 200 }}"
You can’t use templates there
You could use template triggers to accomplish that
What’s the point of the trigger and the condition?
I puzzled over that for a while trying to figure out what value it added 🙂
You could probably also use a value_template to adjust the sensor value prior to the comparison with the input_number
i have a input set point for a co2 sensor.
i would like to it turn on a fan at -200 set point, and turn off at set point
OMG, i was having nothing but issues
i thing maybe it should be noted somewhere, but preferable not allowed to happen ot fixed
you can NOT have a input_number start with a number.. ie "input_number.2_coxx_on"
the "2" becomes a problem
well if you make a helper with the name "1 myinputnumber" it males the id with the number
not your fault
i just could not for the life of me figure out what i had wrong
3 hrs for one line of code
lol
i was trying to set a variables within... evey which way didnt work until i changed the input id... and me being a hack at best didnt help
but thanks for your help rob
for the below dict, I need to retrieve the key and value which has 'tracked' in key. What filters I could use?
"22": "Just Missed - 6 min, 44 sec - 20 min, 31 sec",
"24_tracked": "9 min, 6 sec - 17 min, 53 sec - 29 min, 53 sec",
"43": "5 min, 47 sec - 10 min, 54 sec - 39 min, 18 sec"
}```
I tried the following so far {{ states.sensor.bus_stop.attributes.items() }} and it returns me
dict_items( [('22', 'Just Missed - 6 min, 44 sec - 20 min, 31 sec'), ('24_tracked', '9 min, 6 sec - 17 min, 53 sec - 29 min, 53 sec'), ('43', '5 min, 47 sec - 10 min, 54 sec - 39 min, 18 sec')] )
How can I use the filters to retrieve the key "24_tracked" and its value "9 min, ...." ?
Does the number in front of 'tracked' change?
If not: {{ state_att('sensor.bus_stop', 'items()')["24_tracked"] }}
yes it changes, and thatswhy was looking to see what best we can use to filter out all "*tracked" values
btw the {{ state_attr('sensor.bus_stop', 'items()') }} returns None...so adding ["24... does not work
How can I convert a list ['Item1', 'Item2'] into somethin like Item1, Item2?
I guess I need to use a for-loop but I can't seem to access the variable outside of the loop.
Ugh. Sorry I thought that was the attribute.
Hi all I was wondering if someone can help me with a template (if it is possible to create a template to achieve what I want to achieve). Basically my goal is to broadcast messages dinamically, based on media_player status (!= playing) and binary_sensor status (only for device_class = motion). I found a way to greate a group for media players what are not playing and of course the same can be done for binary_sensor in on status. But how to combine them? Can somehow area_id be useful? Every media_player and binary_sensor have a area_id attribute in my config. I'm not that good in templating so I definitely ask your support to understand if this is possible and how to do that. Thank you in advance
Hello, I am trying to create a binary sensor where the sensor will turn on or off if one of the windows is opened. This worked when I had two devices but when I added a third it stopped working. Does anyone know what is wrong with this?```binary_sensor:
- platform: template
sensors:
windows:
friendly_name: "Windows Status"
device_class: window
value_template: >-
{{ is_state('binary_sensor.office_window_south_status', 'on')
or is_state('binary_sensor.office_window_north_status', 'on')
or is_state('binary_sensor.porch_door_status', 'on')
}}
thanks. However, my requirement is that all the attribute which has 'tracked' in them, I need to retrieve their values
I know the supplied data from source is a mess, but this is what I need to work with. Had it been a proper Json, it would be so easy
{% set windows = ['binary_sensor.office_window_south_status', 'binary_sensor.office_window_north_status', 'binary_sensor.porch_door_status'] %}
{{ states.binary_sensor |selectattr('entity_id', 'in', windows)|selectattr('state', 'eq', 'on')|list > 0 }}```
@rare panther if its that arbitrary you'll need to wait for the regex filters