#templates-archived
1 messages ยท Page 92 of 1
@mental cedar posted a code wall, it is moved here --> https://paste.ubuntu.com/p/8SdMZXgvfH/
~codewall @mental cedar
@mental cedar Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
I'd use
{{ state_attr('camera.portailwebcam','faces') }}
``` etc
Overall looks about right, though sensor.a is an odd choice ๐
hello guys... I need a little bit of help. I want to create e new entity with a template out of "weather.beta" temperature attribute
"{{ states.weather.beta.temperature.state|round }}" -> does not work. what I am missing here?
{{ state_attr('weather.beta','temperature')|round }}
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
See the docs ๐
I am, my code is based on that page
`sensor:
- platform: template
sensors:
weather_current_temp:
value_template: "{{ states.weather.beta.temperature.state|round }}"`
See what I posted - that's not based on that page ๐
ty Tinkerer, I will try it right now
You're trying to get an attribute not a state
@arctic sorrel i'm making progress between state and attribute ... Thanks to u
The states works but not the attributes yet. And i'm wondering faces is a lit how to display a list ?
sensors:
a:
value_template: '{{ state_attr(camera.portailwebcam,faces) }}'
friendly_name: Faces
b:
value_template: '{{ state_attr(camera.portailwebcam,total_faces) }}'
friendly_name: Faces2
c:
value_template: '{{ states.camera.portailwebcam.last_changed }}'
friendly_name: Faces3
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
That's... not what I showed
{{ state_attr('camera.portailwebcam','faces') }}
``` Those `'` are quite important ๐
Test your templates in
-> Templates
losing my mind - in dev tools > templates this shows false {{ is_state('sensor.iphone_room', 'raspberrypi') or is_state('sensor.iphone_room', 'bedroom') or is_state('sensor.iphone_room', 'garage') or is_state('sensor.iphone_room', 'guestroom')}}
but when used as a binary_sensor it shows as 'on' (the state of iphone_room = unavailable)
am i missing something really obvious? been trying to solve this way too long lol
Thanks i will check later with the states ๐
might just need to add another check for unav
or not is_state('sensor.iphone_room', 'unavailable')
ah ok - i would use 'not' but its also 'not_home' that is important too
(actually had not_home until i realised unavailable was incorrectly reporting the sensor as on)
should i add for both?
just not sure why it works correctly in the dev tools template but not here
hmmm - something isnt quite right - or not is_state('sensor.iphone_room', 'unavailable') is not working - giving the same result as without the not or is_state('sensor.iphone_room', 'unavailable')
or not ( is_state('sensor.iphone_room', 'unavailable') or is_state('sensor.iphone_room', 'not_home')) seems to work
this doesn't solve the problem, but one tip... you can just do this:
{{ states('sensor.iphone_room') in ['raspberrypi', 'bedroom', 'garage', 'guestroom'] }}
add more items to the list as needed
also note that the template tool doesn't update in real time. you'll need to type a space or whatever for it to refresh @spark mantle
awesome - didnt know that either ๐ epic
and i was updating, but jsut didnt like my template ๐ฆ thanks for the info @buoyant pine & @dreamy sinew appreciate the help
hey guys i have this template
- platform: template
sensors:
wandownload:
friendly_name: "WAN Download"
value_template: "{{ '%.2f'%(state_attr('binary_sensor.edgeos_interface_eth5', 'MBytes/ps (Received)') * 8 | float) }}"
unit_of_measurement: Mbps
but on HA startup i get an error in the logs
what's the error?
Logger: homeassistant.helpers.entity
Source: helpers/template.py:222
First occurred: 9:57:29 PM (4 occurrences)
Last logged: 9:57:33 PM
Update for sensor.wandownload fails
Update for sensor.wanupload fails
sorry was grabbing it from the logs
definitely going to have an order of operations problem
binary_sensor.edgeos_interface_eth5 is coming from an edgeOS intergration
Yup, put the float on the states method not the number 8
try it in
> templates
thanks guys! the template it self is outputting the correct value
i will change the order of float and reboot now
Youโre probably getting a startup error. Putting the float on the method would remove startup errors when the result is nonnumeric
lol 2 4char names that start with p and are both green. that's not going to get confusing at all ๐
though i guess we already had that when we were both blue
This whole thing is overwhelming
I could change my name to petr to really throw you off ๐คฃ
heh
i removed float and i still get this error on startup
@worn cloud posted a code wall, it is moved here --> https://paste.ubuntu.com/p/sWpkR6Rmch/
value_template: "{{ '%.2f'%(state_attr('binary_sensor.edgeos_interface_eth5', 'MBytes/ps (Received)') * 8 ) }}"
so if I have a rest sensor resource set to http://my-ip/cgi-bin/configManager.cgi?action=getConfig&name=CallInfo and it dumps a return as table.CallInfo.CallID=7 wouldn't my value template not be value_json.table.CallInfo.CallID?
what's the actual response?
table.CallInfo.CallID=7
just like that?
yea
so it wouldn't be json
i thought the rest converted it
only if the response header is content_type: Application/JSON
otherwise you'll get .text
so you probably want {{value.split('=')[-1]}}
same, just blank
ok, i think the call isn't working
if I use {{ value_json }} it returns Unknown but yea anything else is just blank
I wonder if the doorbell banned my ha ip lol
hah
this is what it looks like in the dump
"CallInfo" : {
"CallID" : "7"
but when i access it through the api url it returns what i posted above
the full dump? there is nothing higher than CalllInfo
should be more {} in there. i just want to make sure
if I access http://my-ip/cgi-bin/configManager.cgi?action=getConfig&name=CallInfo or even http://my-ip/cgi-bin/configManager.cgi?action=getConfig&name=CallInfo.CallID they both return the same thing
that probably means i'm up s creek without a paddle?
lol not very but my google fu is pretty strong haha
hmm, is there a shell sensor? ๐ฆ
a ha!
got it
ok so i got results, had to change my authentication type to digest lol
so now i get table.CallInfo.CallID=7 as a result from '{{value}}'
so would i now go back to value_json.table.CallInfo.CallID?
nope that isn't correct lol
is that even json
i did and that was the correct way. it works I get 7 now as the result
nice!
my next question is
so that 7 increases by 1 everytime the button is pushed. what would be the best way to template a binary sensor off this rest sensor to switch from on/off when it goes up by 1?
so the next time someone rings my bell it will be 8
then 9 and so forth
probably need to poll it and then do an automation on when it increases
doesn't sound like a binary sensor thing
more like reacting to the state changes and setting an input_datetime, calling an event, or just immediately reacting to it in the action:s
well binary would give me a history i can follow easier
could have an automation trigger an input bool
make a binary sensor whose value is true if it's been less than 30 seconds since the button was pressed
"30 seconds since the button was pressed" ~= (now - input_datetime).total_seconds() < 30 seconds
(this persists through restarts which is something I care a lot about but you can probably eliminate the input_datetime by using a buffered template binary sensor that therein has an off delay)
let me see what i can cobble together here lol
What's the correct way to add multiple entities to turn_on?
Getting duplicate key warnings here:
turn_on:
- service: switch.turn_on
entity_id: switch.internal_mount_1tb
entity_id: switch.internal_mount_1tb2
entity_id: switch.internal_mount_1tb3
entity_id: switch.internal_mount_4tb
entity_id: switch.internal_mount_merged
entity_id:
- switch.1
- switch.2
- switch.3
...
dangit the woman is asleep i cannot test this!
XD
The RSSI show "-62"... Why I don't get the "fair" in this Template?..
{% if (states.sensor.shelly_shem_d3b358_rssi.state) | float > -50 %}
Excellent
{% elif (states.sensor.shelly_shem_d3b358_rssi.state) | float < -50 and
(states.sensor.shelly_shem_d3b358_rssi.state) | float > -60 %}
fair
{% endif %}
Yeah I know about the "else".. Want to make a few more elif..
Right as always... So sleepy.. the minus got me totally confused.. Thanks!
Hello. I have an MQTT sensor which sends HA some float values, this works fine. When I try to use the "statistics"-module on this sensor the front end crashes and the log says "Unable to serialize to JSON: Out of range float values are not JSON compliant"... any idea what might be going on or how I can do some work around?
how did you defined the sensor in yaml?
The statistics one or the mqtt-one?
mqtt first
- platform: mqtt
name: "The box"
state_topic: "sensor/temperature"
unit_of_measurement: "ยฐC"
you might have to take the value of the topic and transform it into float {{ value_json | float }} or maybe | int
Would I do that by making some template sensor which looks at the mqtt sensor, and then using statistics on that new sensor instead? I'm not too familiar with programming hehe, but I can google
... and thanks for the tip by the way. ๐
just add a state value in the mqtt sensor to import the temperature properly
Ah, I think I understand. Using this "value_template" function for MQTT?
How do you query last time a switch as in 'on' state?
would be nice with states.switch.<id>.last_on or somthing similar
like {{ as_timestamp(now()) - as_timestamp(states(switch.sensor.garage_door_control.last_updated)) < 10 }}
@fallen dagger posted a code wall, it is moved here --> https://paste.ubuntu.com/p/jz6HGdMRmp/
@fallen dagger posted a code wall, it is moved here --> https://paste.ubuntu.com/p/2GhwFKNd7y/
Anyone got any experience with sending notafications to a discord channel?
Trying to send a notication when my 3D printer has finished with images of the print, but I'm unable to attach the pictures to the discord notification. I'm able to send images without the templated timestamp (for example just "test.jpg")
Here you can see the yaml:
- service: notify.discord
data:
message: >
Print finished {{ now ().hour }}:{{ now ().minute }}, {{ now ().day }}.{{ now ().month }}.{{ now ().year }}
target: ["710134391640162364"]
data:
images:
- /config/www/captures/octoprint/octoprint_{{ now ().year }}_{{ now ().month }}_{{ now ().day }}_{{ now ().hour }}_{{ now ().minute }}_left.jpg
Using this kind of path works when I'm using the mobile app notification
and you need to use data_template:
also rule 1 of templating
Sorry๐ And thanks!
and {{ now().strftime('%H:%M, %d.%m.%Y') }}
-> 11:03, 13.05.2020
re-arrange that for your 2nd one
Works perfect!
nice!
value_json, simply refer to "the value that is sent by this sensor"?
value_json is the json response from whatever integration you are using
it's not limited to a domain
I'm not seeing it: voluptuous.error.MultipleInvalid: extra keys not allowed @ data['value']
- service: input_select.select_option
data_template:
entity_id: input_select.source_bureau
value: >-
{% if state_attr('media_player.snapcast_client_xgin', 'source').startswith('Spotify') %}
Spotify
{% elif state_attr('media_player.snapcast_client_xgin', 'source') == 'Mopidy' %}
Radio
{% else %}
Mute
{% endif %}
oh great
value should be option
Can I do it in a oneliner like this:
{{ if (states('input_number.volume_bureau') | float) > 0 else 1 }}
where's the other value you want if the condition is met?
it should be the states value
I have done it in a multi line
it's ok now
Need some help on this:
@small rock posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Cn6FqmyRb3/
Invalid data for call_service at pos 1: expected float for dictionary value @ data['value']
Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
What do you get if you paste it into Templates?
@arctic sorrel it's a different piece of template that goes wrong
Found it out, it happens when the template results nothing
So I have build a condition above it to caputure it
input_select expects option, not value, by the way
Thanks
{{ dict((states|selectattr('entity_id', 'in', state_attr('group.my_lights', 'entity_id'))|list)|groupby('state'))['on']|map(attribute='name')|list|join(', ') }}
``` That lists the members of `group.my_lights` that are in the state of `on`
{{ dict(states|selectattr('entity_id', 'in', state_attr('group.my_exterior_doors', 'entity_id')|list)|groupby('state'))['on']|length }}
``` That returns the number of members in group.my_exterior_doors that are on @true otter
There's a lot of other things, but you need to be clear about your goal
The XY problem is asking about your attempted solution rather than your actual problem. This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
@arctic sorrel So the problem is my alarm will arm even if a entity is in the incorrect state. I don't want the alarm to change state if a sensor is in the incorrect state. does this make sense?
Right, so ... write an automation to detect that and deal with it ๐คท
Personally I'd prefer an alarm that still worked on everything else, rather than one that refused to arm because a sensor was stuck
Hey how can i get this to be an mqtt gps is there a way to use a template? # this is what i get of the mqtt payload
{latitude=50.101916;longitude=10.110403}
it returns like that? That would be odd
{{ states.sensor.consumption_96 }} gives <template state sensor.consumption_96=6.56; on=True, power=None, unit_of_measurement=kWh, friendly_name=Consumption 96 @ 2020-05-15T21:27:35.193686+02:00>. But how do I get only the value '6.56' ? ๐ฎ
Sorry what do you mean its how the code printout https://github.com/JLFN/ESP32-MQTT-GPS/blob/master/publish_gps.ino
@nocturne kiln {{ states('sensor.consumption_96') }}
@dreamy sinew i also tried this code for esp8266 but owntrack mqtt its not showing https://github.com/tubalainen/esp8266_gps_tracker_home_assistant/blob/master/gpstracker.ino
so that response is not a valid json payload. it'll make it obnoxious to work with
korrekt its not json
phnx is there a way to to this easy with json ? ```if (gps.location.isValid()) {
double latitude = (gps.location.lat());
double longitude = (gps.location.lng());
Serial.println("********** Publish MQTT data");
char mqtt_payload[50] = "";
snprintf (mqtt_payload, 50, "{latitude=%lf;longitude=%lf}", latitude, longitude);
Serial.print("Publish message: ");
Serial.println(mqtt_payload);
client.publish(pubTopic, mqtt_payload);
Serial.println("> MQTT data published");```
Thanks @dreamy sinew, I feel dumb now. ๐
if you return whatever is there as json, you can easily access it in a template
like that, you're going to have to do a bunch of dumb stuff to make it work
Does anyone know how to get rid of a 0 in a custom time sensor? I've been searching the forums and can't find anything. I've gotten a template for converting 24h time to 12h time, but my times are formatted as 02:50PM vs 2:50PM
what's your current template?
- platform: template
sensors:
time_12h:
icon_template: mdi:clock
friendly_name_template: >
{% set time = states('sensor.time') %}
{% set hour = time[:2]|int %}
{{ '{:02d}:{}'.format(hour if hour == 12 else hour % 12, time[3:5]) }}
value_template: whocares
attribute_templates:
am_pm: >
{% set time = states('sensor.time') %}
{% set hour = time[:2]|int %}
{{ 'PM' if hour>11 else 'AM' }}
strptime it then take the .hour or whatever attribute
those manipulations you're doing would all be easy with datetime operations e.x. am_pm using time_parsed_as_a_datetime.strftime("%p") to get AM or PM
Is this something I'd put in my current template or a new one?
could you please show me an example of what sensor.time looks like
take the 0 out of {:02d}
or the 02 for that matter
it means "2-wide, 0-prefixed to fill"
does anyone know if there's a way to use a value template with 'unit_of_measure'? I'm basically trying to get HA to not display the unit of measure with a certain value.
Your graphing is tied to unit of measure, if you adjust the units, you'll screw up your history. The units for graphing are not dynamic.
not trying to graph but you're saying that holds true regardless? makes sense but just confirming that's true in an entities card as well?
I have made a template sensor to display minutes until my next Alexa timer expires (code: https://hastebin.com/salehusape.cs). The sensor does not update automatically (0.81 breaking change?). What I should do to update the sensor each minute?
For example, after I set a 60 minute timer, the sensor state will remain at 59 minutes, even when time passes
Is using "entity_id: sensor.time" in the template sensor a good workaround for the issue?
Yes, that's the point of the entity_id field. To update the sensor. If you want to update it minutely, use sensor.time.
has anyone had experience with Cover templates?
Is it possible to invert "position_template" so 0 is open and 100 is closed?
just invert the value being used in position template
position_template: "{{ 100 - whatever_value_is_inverted }}"
position_template: "{{ 100 - states('sensor.bedroom_curtain_position') }}"
is this supposed to work?
Add | int to the end (right before }}") @graceful needle
Ahh cheers!
Hi there can anyone help me add a date with uk formating please
have this - platform: time_date
display_options:
- 'time'
- 'date'
- 'date_time'
- 'date_time_iso'
- 'time_date'
- 'time_utc'
- 'beat'
have a basic clock with date at the bottom and its currently showing yyyy/mm/dd
https://www.home-assistant.io/docs/configuration/templating/#time for all your date/time formatting needs
{{ now().year }}/{{ now().month }}/{{now().day}}``` for a quick hack
{{ as_timestamp(now())|timestamp_custom("%Y/%m/%d") }}``` for something closer to what you're after
thank the problem is i dont really understand how to enter it in the config
I've tried things like ```
- platform: template
sensors:
simple_time_date:
friendly_name: "Simple Time Date"
value_template: "{{ now().strftime('%H:%M %d/%m') }}"
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
Back ticks - next to 1๏ธโฃ
Things is, if you just want a date, you've got it
{{ states('sensor.date') }}```
YYYY-mm-dd
Just displaying sensor.date will give you that
@fair vessel posted a code wall, it is moved here --> https://paste.ubuntu.com/p/wmTNyWGfWR/
~codewall @fair vessel
@fair vessel Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
sorry
Is all you're after turning - into /?
{{ states('sensor.date')|replace("-", "/") }}
no currently its show as 2020/05/16, i need it to be 16/5/2020
{{ as_timestamp(strptime(states('sensor.date_time'), "%Y-%m-%d, %H:%M"))|timestamp_custom("%d/%m/%Y") }}
You can test all this in
-> Templates
thank you. so did i need to do anything in the config? or just somehow use this in the card for the clock
Put that in a template sensor
- platform: template
sensors:
simple_time_date:
friendly_name: "Simple Time Date"
value_template: >
{{ as_timestamp(strptime(states('sensor.date_time'), "%Y-%m-%d, %H:%M"))|timestamp_custom("%d/%m/%Y") }}
Pfft, it's unhappy I didn't open with sensor:
Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got None
extra keys not allowed @ data['simple_time_date']. Got OrderedDict([('friendly_name', 'Simple Time Date'), ('value_template', '{{ as_timestamp(strptime(states('sensor.date_time'), "%Y-%m-%d, %H:%M"))|timestamp_custom("%d/%m/%Y") }}\n')]). (See ?, line ?).
Formatting may be off, I copy/pasted your blob
sensor:
- platform: template
sensors:
simple_time_date:
friendly_name: "Simple Time Date"
value_template: >
{{ as_timestamp(strptime(states('sensor.date_time'), "%Y-%m-%d, %H:%M"))|timestamp_custom("%d/%m/%Y") }}
There we go, that's formatted correctly, just don't include the sensor: line
Thank you, i've not managed to get the config checker to tell me its okay. i never realised that the indentations made so much of a difference as i've had the same code in it about 6 times already
I am correct in thinking if i now use "Simple Time Date" it will display in that format?
Thank you again Tinkerer i've just restarted HA and its now working perfectly
Hi, I am trying to figure out how to implement something like this https://imgur.com/a/aAGUHY4 into my home assistant setup. I got the toggle switch setup and working by using an input boolean using this code https://paste.ubuntu.com/p/R2B3RRv64y/
I can't figure out how to get the text showing the state of the switch. I could get it to show "on/off" using a binary sensor, however, I couldn't get it to show "bins are outside/bins are inside". Would anyone be able to help me?
For reference this is my binary sensor code: https://paste.ubuntu.com/p/b3sbC82jkm/
value_template: >-
{%- if is_state('input_boolean.bin_status','on') -%}
Outside
{%- else -%}
Inside
{%- endif -%}
``` (long form)
hmm strange. I put that in my config, and now the binary sensor is just stuck at "off" regardless of the switch position
Well, you add that to a template sensor ๐
The binary sensor is only ever on/off
This is what it is looking like https://paste.ubuntu.com/p/hbjMQHKXJ3/
did I do something wrong there?
Setting a template sensor is "- platform: template" right?
ohh ok I see what you're saying now. imma fix that up
Got it all working how I wanted it to. Thanks mate.
@outer reef posted a code wall, it is moved here --> https://paste.ubuntu.com/p/2h7wcRrS5s/
Hello. Could your please point me section to a documentation or example how to make own template for my shutters? I have configured my shutter, which could be applied to all my shutters. Here is the config, just mqtt based 20 or so lines
https://paste.ubuntu.com/p/bprJr3yGJ6/
so The idea is to have this snippet with variable, so I can just pass the device name , in this case
rollowaschkueche
to avoid copy paste this code
I can't get this to trigger for some reason {{ as_timestamp(now()) - as_timestamp(states.binary_sensor.amcrest_camera_motion_detected.last_changed) == 10.0 }} I know the state changes by viewing it in the template editor but for whatever reason when tie this to a template sensor it does not fire 10 seconds after the entity's state changes
@bitter atlas that template would only be evaluated when the binary sensor's state changes
yea
the binary in the template is seperate than the sensor
I may havve found my problem aside from lack of sleep, checking something
No like, that will always return False if used in a template trigger
?
now() doesn't cause the trigger to be evaluated
It only updates when the binary sensor's state changes
So, when the last_changed and now() are the same ๐
I guess I don't follow. the binary being evaluated is a separate entity from the template sensor.
I'm talking about the trigger
Template triggers are only evaluated when the entities in the template change state
(this is, curiously, mentioned in the docs)
The only entity in your trigger is binary_sensor.amcrest_camera_motion_detected
when you assign the entity_id to an entity where the state does change, it should work?
If that's in a template sensor it would also only update when the binary sensor's state changes
Why not just use https://www.home-assistant.io/integrations/time_date in the comparison?
front_door_knock:
friendly_name: Door Knock
entity_id: binary_sensor.front_doorbell_motion
value_template: >
{% if (as_timestamp(now()) - as_timestamp(states.binary_sensor.front_doorbell_motion.last_changed) === 10.0) %}
on
{% else %}
off
{% endif %}
That also would only be valid exactly 10 seconds later
That will always be off
Then, move to a time and date sensor instead of now
yea none of this likes me lol
apparently you can't use sensor.time in the template editor
Well, if it exists, you can use it
I have to be doing something wrong and missing something, it only return None
i'll mess with it after I've had some sleep lol
yea
I have it set up
So, when the
last_changedandnow()are the same ๐
@arctic sorrel haha this just clicked for me, makes perfect sense.
way too tired to be doing this lol
Time for a nap ๐
also just realized i can use an automation to do what the sensor was suppose to do. derp. @buoyant pine all your fault.
also anyone else notice there is like 10 Ted's in this server
lol 5 second automation did exactly what I wanted the sensor to do
still going to figure out that sensor.time thing tho later cause yea that was not working in the template editor
Likely a PEBCAK
well i can show the state of it, just couldn't use it to compare time
i have no doubt it was user error with that lol
Is it possible to reference the last changed/last updated value for a person using a template?
What the hell timezone is {{ states.person.xxx.last_changed }} stored in? Doesn't look like UTC, and definitely not local.
epoc seconds I thought
It's a datetime object, it just doesn't seem to line up with either local or UTC. Have tried | timestamp_local and it returns the same value, so it seems to think that it's in local timestamp, but the person state has definitely changed since the last_changed state attribute.
looks local to me
strange... how do you view those hidden attributes like last_changed?
states page doesn't show them
No looks UTC.. I just creatd a person and it's +5 for me, which is UTC @hexed galleon
Hi all, trying to set up a template that will keep a 3d printer enclosure within a certain temperature, i have a temperature sensor in the enclosure called sensor.garage_temperature as well as a heat lamp on a switched called switch.photon_enclosure_heat_lamp
I would like to keep the temperature between 22 and 26 degrees, turning the heat lamp on and off as required
i am i on the right track?
if sensor.garage_temperature < 22
switch.photon_enclosure_heat_lamp turn on
elif sensor.garage_temperature > 26
switch.photon_enclosure_heat_lamp turn off
@thorny snow: you access the states through the state object which I found in this thread: https://community.home-assistant.io/t/last-updated-state-and-last-changed-in-lovelave/101701/2
also, can a template be a entity? I woul;d like a button so i can enable and disable the entity
It says in there that it should be UTC, but the last_changed for my person entity is definitely not UTC-accurate.
It's claiming 2020-05-18 00:06:30.132245+00:00 as the last changed, which would be in the future
what's your time zone? Some people are in the future
UTC+10
Well, not in the future any more, but the last change was definitely before 10:06am local.
silly questionm, but how are you sure it didn't change?
Unless it's considering any attribute for the last_changed, rather than just the state.
are what are you using to track the person?
As my GPS might have changed at 10:06am.
yeah, I am saying that's possible it dropped out for a sec
Not according to the state history. Solid state since 8:08.
that litle graph????? a split second couldn't show up on that!
If you hover over it, it shows timestamps between states. For the state to change, the graph would have had to change.
Guess I'll move around a bit at lunch and try and confirm if a change in GPS coords will trigger a last_changed or not. Logically it shouldn't, because the docs say its "Time the state changed. This is not updated when there are only updated attributes."
@thick barn posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Hb5c9m8rZB/
@thick barn why don't you do this in the automation editor? It sounds easy to accomplish
they suggested a template
this may be way over blown, but have you though of an mqtt hvac? https://www.home-assistant.io/integrations/climate.mqtt/
I haven't look at that, i need the ability to turn the automation on and off with a button on the dashboard
it seems like i can do this in the automations part, i'm just unsure of how to combine my two automations into one. It seems like I need a template, and i need to put that in as a automation?
It seems like this might work?
{% if states('sensor.garage_temperature') | float < 22 %}
switch.turn_on
{% elif states('sensor.garage_temperature') | float > 26 %}
switch.turn_off
{% endif %}
entity_id: switch.photon_enclosure_heat_lamp
I'm just unsure of how or where to put it in automations
@thick barn Make 2 automations: https://pastebin.com/aGyHSskB
change names of course
and then make a binary_input and use it as a condition for those to work
That's one of the reasons I avoided using YAML automations to start with. Decided to go straight for something a bit more flexible/re-usable with AppDaemon.
I like the granularity and the specificity of the built in automations. for intelligence, you need a different tool
this is simple enough for if/then
Hey @thorny snow, thanks for that, I'll see if I am able to do it
I'm not quite sure how to make automations with just text, so far I've used the automations tool built into hass
that's what I did, just to make sure you could.
I couldn't use your real entities though
sorry for the dumb questions, where do you put the text version of the automation?
automations.yaml by default
thanks @buoyant pine, sorry for all the dumb questions, I'm still just trying to learn how to do all of this, I'll change the names of the entities in the above text file, and put it in my automations.yaml file
not quite sure on the binary_input and use it as a condition though...
looks like the automations I made with the wizard were added into the yaml file
https://imgur.com/a/mrAvzL6
yes
I think stolid means "input_boolean"
But I'm also not sure what the purpose of that is
he wants a button on his dashboardthat can turn them both off
I know you can turn each off though
enable/disable
This can be done in one automation with templating which I think he was trying to do
there's usually more than one way to do it, and I assure you, mine is the dumbest
Lol I'm not saying that
yeah, I was trying to do it in one automation, so I can turn both of them off at once
if there is a way to turn them both off with a single button i would be stoked!
I know.. I am.. I don't know how to get those templates right yet
With one automation you could just turn the automation on and off without making a boolean
yeah i don't mind which way, im just happy to learn (even if i have to be spoon fed a bit)
Well, I try to make it work, then make it pretty
here's an example of one automation with templating that'll do what you want: https://paste.ubuntu.com/p/MxDM2W3phf/
you had the right idea with your template, i just adapted it to a one-liner
making a minor correction, hang on
https://paste.ubuntu.com/p/h5sxRJBQnd/ @thick barn
Really confused as to how the HA state machine handles the last_changed state object field. What constitutes a "change" for the purposes of the state machine? My person entity state has "changed" significantly more frequently than my actual state has, so not sure what's registering as a change.
@hexed galleon updated and changed kinda confused me too
attributes register changes too
in the case of person which device_tracker source is probably responsible
oh awesome @buoyant pine
how do I go about using that? Do I make a new automation and set the trigger type as template?
that's a complete automation
you can drop it in and reload automations at configuration > server controls
oh awesome!
add whatever conditions you want, if any
@candid valve, @buoyant pine: According to the docs, attributes changing does not register a change to last_changed - "Time the state changed in the state machine in UTC time. This is not updated when there are only updated attributes."
I apologize
damn I need pictures of these things to understand them
thanks @buoyant pine, i added it to my automations.yaml, reloaded, and turned it on (i turned the old ones off), i'll wait until the temperature drops below 22 and see if it turns the heat lamp back on ๐
That's why I'm so confused. I understand last_updated changing when any attribute changes, but the state itself hasn't changed, but is registering as having changed.
No, solidly "work" the whole time.
definitely weird then
Unless the UI ignores state changes of a very small period.
@thick barn if you want to test it, go to developer tools > states, change the state of the garage temp sensor to something below 22 and see if the automation triggers
the state will go back to the actual state the next time the sensor updates
hi all, good day,
Can somebody help me out with a basic template for converting time format please? I've got sensor.time_date that brings back format
YYYY-MM-DD, HH:MM
and want to display like
HH:MM - DDD, DD/MM
See https://www.home-assistant.io/docs/configuration/templating/#time and https://docs.python.org/3/library/time.html#time.strftime for formatting options
uau, your fast, sppedy gonzales. Thx for this swift reaction.
No worries, it was easy because somebody asked yesterday ๐
n1, worked out of the box, here what I've implemented
sensor:
- platform: template
sensors:
data_e_hora:
friendly_name: "Data e hora"
value_template: >
{{ as_timestamp(strptime(states('sensor.date_time'), "%Y-%m-%d, %H:%M"))|timestamp_custom("%Hh%M - %a, %d/%m") }}
good morning ladies and gents, need someone to help out with a sensor/template
i have this as a "average" temp sensor example
friendly_name: "Downstairs Average Temp"
device_class: 'temperature'
unit_of_measurement: 'ยฐF'
value_template: >-
{% set sensors = [
states('sensor.living_room_temperature')|float,
states('sensor.office_temperature')|float,
states('sensor.thermostat_temperature')|float
]
%}
{{(sensors|sum / sensors|length)|round(1)}}```
im looking to build a sensor that shows the temperature spread between two entities
As in the difference between them?
maybe sensors|max - sensors|min ?
not sure
im very new to building them
someone gave me the average sensor exampel and i can barely read/understand that
looking for a carry here lol
If it's just two entities you can just do
{{ states('sensor.foo') | float - states('sensor.bar') | float }}
ok so in .conf it would look like this?
{{ sensors|max - sensors|min }}
use the same set sensors block from your first one
meaning copy-paste
ok yeah
so the average temp sensor example i sent
the bottom of it is the "argument"
or whatever you wanna call it
{{}} is a "print statement"
the "rule"
And the set part is you creating a variable
alright i think im following
what is %} {{(sensors|sum / sensors|length)|round(1)}}
on the average example
o thats the actual average math being done
The sum filter adds the values of the sensors in the variable, the length filter counts how many items are in the variable (which is a list)
o was it you who shared it with me?
haha
what did you change
feel free to share ๐ i havnt utilized it yet.
but was about to today
{{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}
thats what changed at the bottom
unav/unknown -> 0.0
very noobish when it comes to this stuff sorry
i had a battery die on one of my sensors and it tanked my averages
friendly_name: "Downstairs Average Temp"
device_class: 'temperature'
unit_of_measurement: 'ยฐF'
value_template: >-
{% set sensors = [
states('sensor.living_room_temperature')|float,
states('sensor.office_temperature')|float,
states('sensor.thermostat_temperature')|float
]
%}
{{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}```
so thats the new one
friendly_name: "Gun Safe Temperature Spread"
device_class: 'temperature'
unit_of_measurement: 'ยฐF'
value_template: >-
{% set sensors = [
states('sensor.living_room_temperature')|float,
states('sensor.office_temperature')|float,
states('sensor.thermostat_temperature')|float
]
%}
{{ sensors|max - sensors|min }}```
am i close there? lol
yup, looks good
adding your reject argument might not be needed here because im technically only gonna be looking at two different entities
so it would just show an error or something i guess
or i guess it would show the value of which ever one is working
hmm
nah, it's just show the value of the sensor that is working
yeah weird lol
that's why i added it ๐
the 0.0 isn't helpful
but with the reject as is, it'll show 0.0
so just something to think about
maybe an if block if you care
but its a numeric sensor so ยฏ_(ใ)_/ยฏ
sensors|reject("eq", 0.0)|list|min
you want to reject the bad item out of the list (and turn it back in to a list for reasons) before you do your "operation"
{{ sensors|max - sensors|reject("eq", 0.0)|list|min}}
ahh ok
thanks!
if i were to add a second which would be humidity
i would only change unit_of_measurement: 'ยฐF'
to %
yep, should work
ok awesome
is there an easy way to test a value_template other than having to restart each time
-> Templates
<template state sensor.json_vejr=[{"200000555":{"temperature":"12.8","humidity":"79"}},{"200005523":{"temperature":"13.3","humidity":"74"}},{"300000555":{"rain":0}},{"400000555":{"wind-speed":"0.5","wind-gust":"1.9","wind-direction":"WSW"}},{"100000555":{"barometer":"1008"}}]; friendly_name=JSON vejr @ 2020-05-18T15:57:04.458654+02:00>
No matter how i try, i can't seem to get the first temperature from that
Which one though ๐คท
{{ state('sensor.thing')[0].temperature }}
``` (probably)
not likely with that structure
how do i round to a a whole number
friendly_name: "Liberty Safe Temperature Spread"
device_class: 'temperature'
unit_of_measurement: 'ยฐF'
value_template: >-
{% set sensors = [
states('sensor.liberty_gun_safe_temperature')|float,
states('sensor.garage_temperature_1')|float
]
%}
{{ sensors|max - sensors|reject("eq", 0.0)|list|min}}```
gave me 5.199999999999989
lol
@frail hawk {% set value = [{"200000555":{"temperature":"12.8","humidity":"79"}},{"200005523":{"temperature":"13.3","humidity":"74"}},{"300000555":{"rain":0}},{"400000555":{"wind-speed":"0.5","wind-gust":"1.9","wind-direction":"WSW"}},{"100000555":{"barometer":"1008"}}] %} {{ value[0].get("200000555").temperature }}
@topaz walrus oh, we forgot the round
wrap that whole sucker in () and then add a round|(1)
@dreamy sinew nice... now i just need to get it from sensor.json_vejr instead
yup, drop that whole first section and replace value with states('sensor.json_vejr')
Error rendering template: UndefinedError: 'str object' has no attribute 'get'
im a tard
value_json
cant get the template editor to accept
{{(sensors|max - sensors|reject("eq", 0.0)|list|min) round|(1)}}
|round(1)
ahh nice!
thanks again!
alright even weirder question
or have i ran out for today lol
friendly_name: "Liberty Safe Humidity Spread"
device_class: 'temperature'
unit_of_measurement: '%'
value_template: >-
{% set sensors = [
states('sensor.liberty_gun_safe_humidity')|float,
states('sensor.garage_humidity')|float
]
%}
{{(sensors|max - sensors|reject("eq", 0.0)|list|min)|round(1)}}```
gives me 29.6
how can i make that say -29.6
@dreamy sinew where do you want me to add that ?
flip the math?
basically
min - max
smh..
what is device_class
i changed it to "humidity" and the math is wrong now lol
disregard.. guess the sensor just updated.. and it changed by that much.
Hello, in light.template, can I mix service_template and services like this :
turn_on: - service_template: > {% if is_state('binary_sensor.dilightdressing', 'off') %} switch.turn_on {% else %} switch.turn_off {% endif %} entity_id: switch.dolightdressing - delay: milliseconds: 100 - service: switch.turn_off data: entity_id: switch.dolightdressing
When I do this, I have strange behavior, config validator is turning around long long time
no
@dreamy sinew i can't seem to get it to work with the value_json .. where do you want me to add this to make it work
not something i've really dealt with ยฏ_(ใ)_/ยฏ
@frail hawk "{{ value_json[0]['200000555'].temperature }}"
@mighty ledge works on the - platform: rest but not on the - platform: template element
maybe {{ states('sensor.whatever')|tojson[0]...}}
will test ๐
but the real answer might be to just do it in the rest sensor directly
yes but do i then have to do one rest per value i want to pick out of it ? thats what i was trying to avoid to make fewer queries
{% set value = states('sensor.json_vejr')|from_json %}
{{ value }}
[{'200000555': {'temperature': '11.9', 'humidity': '84'}}, {'200005523': {'temperature': '11.6', 'humidity': '83'}}, {'300000555': {'rain': 0}}, {'400000555': {'wind-speed': '2.9', 'wind-gust': '5.6', 'wind-direction': 'ESE'}}, {'100000555': {'barometer': '1008'}}]
but then i get stuck
add all the other bits i sent you
worked this time... didn't before... nice ๐
Put the value in attributes for rest
now i just need to find out how to do the {% set value = states('sensor.json_vejr')|from_json %} part in the sensor
you get stuck because it's not JSON, it's not converting it because it has invalid json characters'
json does not use single quotes at all.
thats home assistant that gives it '... cause the source is with "
then whats the problem? You've been given the correct syntax if it's been converted [0]['200000555'].temperature
{% set value = states('sensor.json_vejr')|from_json %}
{{ value[0]['200000555'].temperature }}
yes that works in the testing.... now i just need that down into my config ๐
thanx @mighty ledge and @dreamy sinew ๐ now i just need to get all the devices added ans showed in the frontend ๐
Need some help getting some nested attributes out of this rest sensor I made..
I'd like to have the grass part of AirAndPollen ..
{{ states.sensor.accuweather.attributes.DailyForecasts.AirAndPollen.grass }}
doesnt seem to work
Grass is capitalized
daily forecasts is also a list
{{ states.sensor.accuweather.attributes.DailyForecasts{10}.Grass }}
isnt working either, forgive my ignorance, its all new to me ..
{%set a=(state_attr('sensor.accuweather', 'DailyForecasts')[0].AirAndPollen | selectattr('Name', 'in', 'Grass') | list)[0]%}{{a.Category}}
{%set a=(state_attr('sensor.accuweather', 'DailyForecasts')[0].AirAndPollen | selectattr('Name', 'in', 'Grass') | list)[0]%}{{a.Category}}
throws
Error rendering template: UndefinedError: None has no element 0
@dreamy sinew yes
I was wondering how to add a switch to the lovelace ui that can trigger one flow when it is on and another flow when it is turned off how would I do that?
Works for me ๐คทโโ๏ธ
so a) You pasted wrong, b) You are not using the correct entity Id, c) the data you pasted is not correct
take your pick
it also has this at the end of the sensor data
friendly_name: accuweather
i accidentally left it out with the personal info ๐คฆโโ๏ธ
I'll make a new paste, hang on
thats it in full, replaced the info with x's as I should have done in the first place
@quiet creek Use templates https://www.home-assistant.io/integrations/switch.template/
Whats wrong here?
{{ (states('sensor.internal_media_used') | float / 1024) | round(2) }}
Looks fine, what issue are you having
2020-05-19 00:50:00 ERROR (SyncWorker_0) [homeassistant.util.yaml.loader] invalid key: "OrderedDict([("(states('sensor.internal_media_used') | float / 1024) | round(2)", None)])" in "/home/homeassistant/.homeassistant/configuration.yaml", line 42, column 0 2020-05-19 00:50:00 ERROR (MainThread) [homeassistant.bootstrap] Failed to parse configuration.yaml: invalid key: "OrderedDict([("(states('sensor.internal_media_used') | float / 1024) | round(2)", None)])" in "/home/homeassistant/.homeassistant/configuration.yaml", line 42, column 0. Activating safe mode
Wrap it in double quotes
It is
Include the whole thing that this is part of
value_template: {{ (states('sensor.internal_media_used') | float / 1024) | round(2) }}
No, wrap the template in double quotes
"{{ (states('sensor.internal_media_used') | float / 1024) | round(2) }}"
oh ok
Otherwise it's interpreted as a dictionary
Gotcha. Thanks ๐
Fun fact, that's not invalid because you are trying to use a dict as a key, but because it has no value.
{{ (states('sensor.internal_media_used') | float / 1024) | round(2) : something}: whatever} is valid yaml.
No sane person would use a dict as a key, but you can.
Inb4 "bUt PyThOn": Python is a programming language, it could make sense there. Yaml is a data storage format.
๐คฃ
As long as your repr is unique you can use any object as a key for a dict
Unique and hashable.
I need a little help for with this template is this the proper format? I see the data in the graph but its not Calculating the total
round(2) maybe?
heh
๐
might need |float and |round(2)
i think that's one of those that doesn't matter until it does
no, make the places where you're using those and make them look like that
you made some changes, what does it look like now?
you didn't fix the first float, you didn't fix the round
now try it in the template tester
still 0
0 or 0.0 ?
0.0
in the tester just output both your sensors individually
{{ states('sensor.sensor2') }}```
are either of those 0?
or unav/unk?
checking
value_template: "0" "0.097
welp
now i need to figure out why its rounding it to 0 when its .020 on the graph
ty @dreamy sinew
@pine wigeon posted a code wall, it is moved here --> https://paste.ubuntu.com/p/w3QSDvnB2m/
Hello, little problem with a template. I want the difference (in 23:45 format) between now and the alarm for turning on my hue bulbs slowly before I wake up.
The template is working, but doesn't update as the minutes go by. Even with a browser refresh (F5). The only way to have the calculation correct again is to modify the alarm hour or minute.
For the substraction, I use
sensor:
- platform: template
state_attr('input_datetime.reveil_h_min','hour')
state_attr('input_datetime.reveil_h_min','minute')
now().hour
now().minute
Any idea ?
You need to update the sensor based on an entity that's constantly updating ie a time sensor. now() only renders once
https://www.home-assistant.io/integrations/time_date/ here are the docs for adding a time sensor
In my config, I've
- platform: time_date
display_options:
- 'time'
But the hours and the minutes are not separed, it's why I used now()...
You can use now(), but you have to list sensor.time under entity_id
in the template sensor config
sensor:
- platform: template
...
entity_id: sensor.time
...
This is telling the template sensor to refresh the template render each time sensor.time updates, which is every minute
I've edited, restart takes several minutes even with the Ryzen 5, I will see. Thank you Villhellm, you helped me a lot today. ๐
Do you have a Zwave network tied to HA?
We have the answer : with "entity_id: sensor.time", the calculation does not update by itself, but no more when I edit the alarm hour/min ๐
You need to add those under entity_id as well
Do you have a Zwave network tied to HA?
@hollow bramble Nope, only 10+ NodeMCU
entity_id:
- input_datetime.reveil_h_min
- input_datetime.reveil_h_min
- sensor.time
Or you could just wait a minute ๐
Configuration invalide
Invalid config for [sensor.template]: [entity_id] is an invalid option for [sensor.template]. Check: sensor.template->entity_id. (See ?, line ?).
I wanted to add my RF-Link USB gateway but FreeNAS is a little fickle
So I keep my MQTT Wi-Fi sensors
What does your sensor config look like now?
sensor:
- platform: template
entity_id: sensor.time
entity_id: input_datetime.reveil_h_min
sensors:
sommeil_restant:
value_template: >-
I also tried
sensor:
- platform: template
sensors:
sommeil_restant:
entity_id: sensor.time
value_template: >-
The second one doesn't work?
Nope, sadly
You can only list the key once, so the first will never work. You need to add it as a list like I showed here https://discordapp.com/channels/330944238910963714/672223497736421388/712387969452867715
sensor:
- platform: template
sensors:
sommeil_restant:
entity_id:
- input_datetime.reveil_h_min
- sensor.time
value_template: >-
Just realized I duplicated the input for no reason ๐
- input_datetime.reveil_h_min two times, one for the mours attribute and one for the minutes attribute ?
It answers
Just realized I duplicated the input for no reason ๐
@hollow bramble ๐
No, sorry I thought your template had two entities. I wasn't paying close enough attention
No problem, I use input_datetime with the https://github.com/GeorgeSG/lovelace-time-picker-card , one entity and two attributes
Perfect, it updates instantly, thanks again!
Do you know if every minute, python read the binaries in the storage, generating i/o, or if all necessary items are fully loaded in RAM ?
For turning a lamp on I don't really care, but with our template an io traffic every minute is not very optimized
That I'm not sure of. Either way performance impact would be minimal
Yeah, sure.
@pine wigeon if you just make a sensor using the datetime in a sensor with the device_class: timestamp it will update and you don't need to perform math. Also, you wont' need to attach a sensor.time to it.
I have a question about the binary sensor platform: I'd like to track if the Raspi running the Home Assistant has a internet connection by pinging to the outside world. How do I turn that into a binary sensor with the connectivity class?
PONG!
thanks. found a way
Hey everyone. How can I display the time that has expired since a windows contact (on/off) was triggered the last time?
You can do that in the #frontend-archived with an entities card
Set the secondary_info value
I have seen that, but I want to show this info on the right side instead of the "open / closed" state
That then would require a template sensor
Are there any examples?
You have to build the logic you want into the template, for all of it
Possibly something like {{ states.binary_sensor.window.last_updated }}
Okay i will try, thank you !
So this might be the right place for this. Basically, I am using the REST platform to call the onecall api from Open Weather Map. My issue, is that because I am creating sensors for forecasted information, the sensors represent data that is relative to today eg: the first sensor is todays high, the next is tomorrows high, and the next is the high for the day after next and so on. I want to be able to represent that in a card as the correct day of the week it is forecasting. Meaning I need it so that the name or by some other means understands today is X therefore I am X+2days=Friday. I am using an entity card with a multiple entity row to display each day, and the days are currently labeled today, tomorrow, the day after tomorrow, the day after that and so on. I would like to replace those values with the days of the week relative to today.
Anyone have any ideas?
I guess the shorter version would be how do I make a template or template sensor that would allow me to take today's day of the week and add a day or two, so that the end result would be the name of the day of the week X number of days from today?
@hollow ocean I don't know how to do the full thing but you'd start with something like now().weekday() to get a number representing the current day of the week (0=Monday, 6=Sunday). Do some math to add your X days, then map it back to a friendly name (this part will probably be a long series of if/else statements)
An example of mapping values to your preferred display names: https://community.home-assistant.io/t/example-of-if-statement-for-template-sensor/24010
@hollow ocean post the entity you are pulling the info from. Take a screenshot of it on the
-> states page.
@mighty ledge apparently I can't post photos?
use something like imgur
So each of those sensors are the information you're outputting?
@hollow ocean hastebin the code for each of those, the solution will be complicated
@timber locust posted a code wall, it is moved here --> https://paste.ubuntu.com/p/wrhZhcxTcJ/
~codewall @timber locust
@timber locust Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
Whoops. Too much code I see. Just the message without the code:
Hey everyone! I'm trying to create an automation for my Xiaomi Roborock to clean the rooms in my house in sequence. I want to do that in such a way, that when I stop the vacuum before it's finished with a specific room, and then continue it, it will continue the cleaning from that room onwards. To do so, I have created this code in the codewall.
So basically I have found the room numbers that my vacuum uses (tested and they work using call service in dev tools). I then have a script that calls the clean_next_area as long as the whole house has not been done yet (I just noticed an oversight here, but nevermind this for now). The clean_next_area script should then clean the room selected in the input_select, wait until the vacuum is done, and then call the first script again, which loops again. However it does not work, as I get the error below:
2020-05-20 17:52:25 ERROR (MainThread) [homeassistant.components.xiaomi_miio.vacuum] Unable to send command to the vacuum: {'code': -10000, 'message': 'data for segment is not a number'}
Possibly
params: {{states('input_select.vacuum_room_numbers')|int}}
The quotes turn it into a string
I think the code fails to verify when I do that. Let me check!
The service should be parsing it anyway. Might be considered a bug
- wait_template: "{{ states.vacuum.xiaomi_vacuum_cleaner.attributes.status == 'Returning home'}}"
Could be written as
- wait_template: "{{ is_state_attr('vacuum.xiaomi_vacuum_cleaner','status','Returning home') }}"
Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states('input_select.vacuum_room_numbers')|int", None)])" in "/config/packages/misc/test.yaml", line 158, column 0
Need to wrap it in quotes
params: >-
{{states('input_select.vacuum_room_numbers')|int}}
``` should work then, but I suspect will suffer the same problem
or that
Yeah, I was wondering if the quotes was turning it into a string, and causing the original issue
I did Tinkerer's suggestion, and now it validates.
The real question is, does it work
About the suggestions that you made earlier, using is_state_attr(), why use that instead of what I have? Is it better practice, or?
See the templating docs ๐
Better practice (basically)
There are times you'll want to use the approach you've got though
Why not just send all the rooms at once instead of waiting for return? https://www.home-assistant.io/integrations/vacuum.xiaomi_miio/#example-on-how-to-clean-a-specific-room it should do them in sequence
Okay thanks!
@hollow bramble I could do that, but how can I then detect which rooms were already done?
Restarting HA now. Let's see
Oh okay now I see what you're getting at
Yeah, same error:
2020-05-21 18:22:12 ERROR (MainThread) [homeassistant.components.xiaomi_miio.vacuum] Unable to send command to the vacuum: {'code': -10000, 'message': 'data for segment is not a number'}
It could be you're not giving it an array
When I use the call service dev tool, I can feed it a number or an array and it is fine.
params: ["{{states('input_select.vacuum_room_numbers')|int}}"]
I tried to give it an array before, that doesn't work.
It works if you wrap the number in quotes?
Good point! Let me check! ๐
When I feed it:
entity_id: vacuum.xiaomi_vacuum_cleaner command: app_segment_clean params: key: '[1]'
, it gives me:
2020-05-21 18:24:05 ERROR (MainThread) [homeassistant.components.xiaomi_miio.vacuum] Unable to send command to the vacuum: {'code': -10000, 'message': 'Param is not an array'}
Ah okay. One more thing, when I feed it:
entity_id: vacuum.xiaomi_vacuum_cleaner command: app_segment_clean params: key: 1
It throws the same error.
where is key: coming from?
Oooh yeah. I filled the example data. Let me remove it.
When I removed the key, and put it immediately after params:, it throws a different error:
2020-05-21 18:26:51 ERROR (MainThread) [homeassistant.components.xiaomi_miio.vacuum] Unable to send command to the vacuum: {'code': -10000, 'message': 'data for segment is not a number'}
That is with: params: ['1']
This does work:
entity_id: vacuum.xiaomi_vacuum_cleaner command: app_segment_clean params: 1
The vacuum is now cleaning room 1.
I would open a bug report. The service should at least attempt to parse an int if it's given a string or an array of strings
Thank you guys so much for your help!
Sorry it's not actually solved
Is it a bug in the component or with home assistant itself?
The component is part of home assistant
But I mean is it with how home assistant handles templates, or with this specific component?
It's with this specific component. The send_command service specifically
Ah okay. Thanks for the heads-up! I'll file a bug report!
Is this a good title for the issue: vacuum send_command does not parse non-integer in template
I mean the template isn't necessary, but it does give context to how the bug affects users
Either way they'll figure it out
Am I missing any important info here? https://github.com/home-assistant/core/issues/35934
I realise how important good documentation/logging is to solve these problems.
I would probably mention that a simple service call with
entity_id: vacuum.xiaomi_vacuum_cleaner
command: app_segment_clean
params: '1'
fails with that error
Just to make it clear there are not errors in your template
Very good point! Thanks. Updated!
Hey @hollow bramble thanks so much for your quick support. I really appreciate it! ๐
No problem, glad to help
How long does it usually take for an issue to get picked up?
Yeah it totally depends on who is in charge of the integration. Seeing as how this is a core integration issue you might have better luck
So days to weeks?
Or longer
Like Tediore said, heat death of the universe is not out of the realm of possibility
If no one picks it up soon I'll try to look into fixing it myself. Usually if you post an incorrect pull request you get help a lot faster ๐
Haha
Put considering the backlog of 1000+ issues and 250+ PRs idk
To me, it sounds like a relatively simple issue to fix. If params == string, params = str2num(params) endif.
There is loads of red tape when it comes to "simple" fixes. Style guides, best practices, random required library uses, etc
It has to be done the "right โข๏ธ " way
Sounds understandable. I'm only used to cooking home-made spaghetti in Matlab ๐
I don't know if this is the right place, but here goes. I have an mqtt sensor call maintank_color whose values are colors in hex format(including the #) i.e #aabbcc. I'm trying to use that sensor to set the background color of a card. If I specify the color explicitly it works, but if I try to use states('sensor.maintank_color') it doesn't. I've checked the the state of the sensor using the developer tools and the values look correct.
Do you get an error in the logs?
So in the integration tab i added my modem, now i can see my network speed. But its in KIB/s.. whats the best way to convert it? just add a template sensor? or are there other solutions for UOM conversions?
@mighty ledge sorry it took so long - i was travelling - did you mean this ? https://pastebin.com/qX9EFv13
@hollow ocean yes, the good news is, you already have the complicated part complete
thats encouraging
@hollow ocean All you need now is friendly_name templates
What's in the JSON?
if there's nothing, and all you know is that [0] index is the day... Then this will work:
friendly_name_template: "{{ now().timestamp() | timestamp_custom("%A") }}"
for each additional day you need to do this
friendly_name_template: "{{ (now().timestamp() + 1 * 86400) | timestamp_custom("%A") }}"
then just change the 1 with the index value
I dont know where the JSON is?
But, I can just put this into the sensor and it will work?
so a full example for today and tomorrow would be:
openweather_temp_max_today:
friendly_name_template: "{{ now().timestamp() | timestamp_custom("%A") }}"
value_template: "{{ state_attr('sensor.openweather_report', 'daily')[0].temp.max }}"
unit_of_measurement: "ยฐF"
openweather_temp_max_tomorrow:
friendly_name_template: "{{ (now().timestamp() + 1 * 86400) | timestamp_custom("%A") }}"
value_template: "{{ state_attr('sensor.openweather_report', 'daily')[1].temp.max }}"
unit_of_measurement: "ยฐF"
openweather_temp_max_3:
friendly_name_template: "{{ (now().timestamp() + 2 * 86400) | timestamp_custom("%A") }}"
value_template: "{{ state_attr('sensor.openweather_report', 'daily')[2].temp.max }}"
unit_of_measurement: "ยฐF"
Yes, you can. See https://www.home-assistant.io/integrations/template/#friendly_name_template for template sensors
That is incredibly helpful
Im going to try this now!!
sensors:
openweather_temp_max_today:
friendly_name_template: "{{ now().timestamp() | timestamp_custom("%A") }}"
value_template: "{{ state_attr('sensor.openweather_report', 'daily')[0].temp.max }}"
unit_of_measurement: "ยฐF"
its saying invalid, bad indentation of a mapping entry at line 73, column 75:
... timestamp() | timestamp_custom("%A") }}"
everything prior to the % is green, everything ater is black
switch now().timestamp() to as_timestamp(now())
try it in template editor first
It could have typos, going off memory
Oh, nevermind, typo
change the outerquotes to single quotes
friendly_name_template: '{{ now().timestamp() | timestamp_custom("%A") }}'
in all cases.
that seems to do the trik
trick*
Log Details (ERROR)
Logger: homeassistant.components.hassio
Source: components/hassio/init.py:277
Integration: Hass.io (documentation, issues)
First occurred: 8:48:38 AM (1 occurrences)
Last logged: 8:48:38 AM
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['openweather_temp_max_3']['friendly_name_template']. Got '{{ now().timestamp() + 2 * 86400) | timestamp_custom("%A") }}' invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['openweather_temp_max_4']['friendly_name_template']. Got '{{ now().timestamp() + 3 * 86400) | timestamp_custom("%A") }}' invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['openweather_temp_max_5']['friendly_name_template']. Got '{{ now().timestamp() + 4 * 86400) | timestamp_custom("%A") }}' invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['openweather_temp_max_tomorrow']['friendly_name_template']. Got '{{ now().timestamp() + 1 * 86400) | timestamp_custom("%A") }}' invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['openweather_temp_min_3']['friendly_name_template']. Got '{{ now().timestamp() + 2 * 86400) | timestamp_custom("%A") }}' invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['openweather_temp_min_4']['friendly_name_template']. Got '{{ now().timestamp() + 3 * 86400) | timestamp_custom("%A") }}' invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['openweather_temp_min_5']['friendly_name_template']. Got '{{ now().timestamp() + 4 * 86400) | timestamp_custom("%A") }}' invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['openweather_temp_min_tomorrow']['friendly_name_template']. Got '{{ now().timestamp() + 1 * 86400) | timestamp_custom("%A") }}'. (See ?, line ?).
@mighty ledge just got this error
Youโre missing the leading ( in the template. Check my previous post and compare it to yours. Try it in the template editor
oh its unny how sometimes I just dont see those little things
you can't put conditions in a command_line sensor right? I want to run the command only if a ping sensor is showing the remote device is up
@mighty ledge I dont think Im seeing the missining (
you have an ending ) after the 86400s but not a beginning (
so it goes ahead o 1
i assume you want it infront of now()
{{ (now().timestamp() + 1 * 86400) | timestamp_custom("%A") }}
that also led to an erro
did you change the outside quotes as well?
'{{ (now().timestamp() + 1 * 86400) | timestamp_custom("%A") }}'
are you trying this in the template editor?
@hollow ocean I'm not getting any errors with that in the editor, therefore it has to do with your formatting, not the template itself.
@hollow ocean posted a code wall, it is moved here --> https://paste.ubuntu.com/p/qwK8YNYjfR/
~codewall @hollow ocean
@hollow ocean Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
sorry about that
I don't know how that's possible because the template is correct and your format is correct.
post the error
You have double quotes inside single quotes
might be an issue
Oh and all your friendly_name templates have an extra ( at the beginning
'{{ (now().timestamp() | timestamp_custom("%A") }}' to "{{ now().timestamp() | timestamp_custom('%A') }}"
double quotes donโt work inside single quotes?
removing the double quotes caused a red exclamation mark
it is an error
What is the error
bad indentation of a mapping entry at line 73, column 76:
... timestamp() | timestamp_custom('%A') }}'
... you need double quotes on the outside, like I posted
will try
@hollow bramble I thought those docs were just the HA house style for people writing documentation, not a syntax requirement
im still getting errors in the log
Post the errors
@marble sun it's possible, but I feel like in the past people have had issues when trying it the other way. I could just be misremembering though
Did you read the error? And are you testing your templates in the dev templates tool?
TemplateSyntaxError: unexpected ')'
Some of your templates are doing math, some aren't. If you have ) it needs a ( in front. I thought they were the same
I always try to read the error to see what I can make o it but, not the templates tool
So I was trying to put a ( , but could quite think where
Test each one in the templates tool
ok
openweather_temp_max_tomorrow:
friendly_name_template: "{{ (now().timestamp() + 1* 86400) | timestamp_custom('%A') }}"
value_template: "{{ state_attr('sensor.openweather_report', 'daily')[1].temp.max }}"
unit_of_measurement: "ยฐF"
this one worked in the template too
tool*
Now do that for all of them
It worked! This was awesome and super helpul
much appreciated
I will use the template tool way more too
Yes, always test templates before using them in a configuration
makes total sense
how do I get this list of media players into an input_select? {% for state in states.media_player -%} {{ state.entity_id }}, {% endfor %}
I know it's "set_options" service, but I can't seem to find the right format
@hollow bramble you can interchange doulbe and single quotes for inside/outside. That doesn't matter.
though, single outside/double inside looks weird IMO
yah, but it's easier to replace 2 double quote outsides than 27424 double quote insides
#lazy
replace all " with ', then replace all '{{ and }}' with "{{ and }}"
options: "{{states.media_player | map(attribute='entity_id') |list }}"
then watch everything break when you had random spaces ๐
Oh dang, ninja promotion ๐
i'm not sure if that'll work though because you'd get a stringified list
yeah... one can hope ๐คทโโ๏ธ
maybe |list|tojson?
haha
replace all
"with', then replace all'{{and}}'with"{{and}}"
@hollow bramble that's 1 extra step i'm willing to skip
maybe a multiline could solve it
{%- for player in states.media_player | map(attribute='entity_id') |list %}
- {{ player }}
{%- endfor -%}```
Wouldn't that just give:
"- entity"
"- entity"
sure, but the template engine will mangle it?
ยฏ_(ใ)_/ยฏ
I don't think it would. I use it in lovelace_gen which uses the built in template engine
doesn't mangle any of the spacing
M A L F O R M E D
mine?
nah, seeing "mangled" made me think of the "db disk image is malformed" error
malformed just makes me laugh for some reason
H O R R I B L Y M A N G L E D
Is there a good way to measure how long an entity has been in a certain state? Like the for: key in the state trigger.
I'm trying to get something to run every day, and check a couple of entities for how long they've been in a certain state, and perform an action if they have been.
My other option is to do separate automations for each entity, but I'd rather put it all in a template, if possible.
and then pass that timestamp to something relative_time or something to measure how long it's been.
if you make it a template sensor, you can add the timestamp device class, and the UI makes it human readable
Good point
also, hacs 1.0 looks awesome. thanks for your work.
This is the automation I'm working on. Roughed out the initial automation, but I need to get it to actually work, lol. https://github.com/Apocrathia/home-assistant-config/blob/master/packages/integrations/vacuum.yaml#L179
What's wrong with that?
the service call is wrong, should be start but it currently triggers at whenever it last ran +24 hours. Trying to get it to check every morning. I'll try the last_changed in a couple of if statements for each entity
yeah, I tried that, but then the trigger.entity_id would be invalid, because it wasn't an entity that triggered the automation, but the time.
You have 2 vacuums, why not just make 2 automations?
it's either that or a template. probably easiest to just make 2 automations.
That would be a very complicated template if your trigger is going to be time regardless
relative_time(state.last_changed) >= 24 in a couple of if statements ๐คท
Yeah, that's probably easiest over a template.
Thanks for talking some sense into me ๐
I like writing stuff in templates because the structure feels more "standard" (if statements, loops, etc), but the HA automation format works if you build everything individually. I'm just irked for no logical reason by having a million automations, lol.
Hello I was curious I put a script in to turn on netflix on my fire tv, which is com.netflix.ninja. I was curious to know what does .ninja mean? I tried googling but couldn't find anything
That probably depends on the integration
its a quirk with how apps are named in the android os
ah ok
Is there a way to test the value_template of a json without having to make a change reboot, rinse, repeat?
well it's a command line sensor reading a file that has the json to try and pass into HA
i should have started with that
{% set value_template = 'paste your json here' |from_json %}
{{value_template.value_you_are_looking_for}}
or whatever you want to call the object
can someone help me with a mqtt template for this data? I would like the last piece "notification - timeout", the json looks like this: {"data":[13,1,"Notification - TimeOut"]}
nvm got it. Thanks @hollow bramble for the technique. {{value_template.data[2]}}
Hello everyone. I'm stuck trying to get the last changed value of a script. I want to see how long a script has been running (it includes a delay). But my problem is that I can't find a way to query the last_changed property of a script.
I can run: {% for state in states.script -%} {%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%} {{ state.entity_id | lower }} is {{state.last_changed}} {%- endfor %}.
and it shows all scripts and the last time they changed... but I can not get the last change state of a single script
That's not really how scipts work. They never change state
They do have a last_triggered attribute
I see.. why the loop above shows a value..
It probably shows the value of the last time you restarted HA
or the last time the attribute was updated
Nop.. actually the last time the script was activated
They actually change state for a while. If a script have a delay.. yt change to ON.. and can be stopped.
Oh maybe I'm misremembering. What information are you trying to get?
But you are right... they have a last_triggered also.. but how can I get that value?
I just ran a script and last_changed stayed the same
It has to have a delya in it
{% for state in states.script -%}
{{state_attr(state.entity_id, 'last_triggered')}}
{%- endfor %}
if I try {{ states.script.1590120819845.last_triggered }} it trhows an error
It's an attribute
ah OK.. let me try
So you'd have to do script.script_name.attributes.last_triggered
but it's better to use the state_attr function
{{state_attr(state.script.1590120819845, 'last_triggered')}} does not work
You need to give it an entity_id. You're mixing up syntax {{state_attr('script.1590120819845', 'last_triggered')}}
in the loop state.entity_id is a string. The function needs a string as the first argument
Hi again.. OK, I found something about this. Your solution shows when the script was triggered... but not when the state changed. I mean, when I start (turn ON) the script, both last_triggered and last_changed are the same. When I stop the script, the last_triggered is unchanged, but last_changed is affected reflecting the OFF state.
So my problem is still there. How can I query the last_changed for a script. For now, I can do a loop and filter the script.. like
{% for state in states.script -%} {%- if state.entity_id == 'script.1590120819845' %} {{as_timestamp(state.last_changed) | timestamp_local}} {% endif -%} {%- endfor %}
But that's... ugly. ๐
Hmm, this is kind of what i'm looking for. I have managed to setup a heap of scripts for my xiaomi robo vacuum, but i've got some scripts which move it out of its location and drive directly over to where it needs to go, rather than it finding its way there. So i'd love to be able to script run script 1, then run script 2, then script 3. Obviously if they're all in the same script they try to trigger at once. The only way i've worked out how to do it with my limited knowledge is adding delays, to time each section of the script. Is there some way to trigger a script, then the next script not start until the previous one has finished? I've searched around but I think im either missing the key word or it's not making sense
You can find if the script is running asking for it's state. {{is_state("script.1590120819845", "on")}}
scripts with delays stay on until they finish
My problem is how to check when the script ended. Last_triggered shows when it started.. but only Last_changed reveals when it stopped.
For sensors can ask for {{ states.sensor.xxx.last_changed }} ...works. But {{ states.script.xxx.last_changed }} fails. I do not know how to directly query that without the loop workaround
EUREKA! I found the solution. The problem was the scripts beginning with a number. The correct sintax is : {{ states.script['1555205828137'].last_changed }}
Events in local time: Last triggered : {{ (as_timestamp(states.script['1590120819845'].attributes["last_triggered"])) | timestamp_local }} Last Changed : {{ (as_timestamp(states.script['1590120819845'].last_changed)) | timestamp_local }}
Nest
Is anybody able to look at this and suggest why everything is going to state and not attributes?
@brisk temple what value are you trying to parse for the state?
https://github.com/home-assistant/core/blob/dev/homeassistant/components/command_line/sensor.py#L108 I'm not sure the attributes work the way you think it works (or work in a way that is at all clear from the docs)
It's trying to find the attributes from the root json object, it doesn't use the value from the value_template. And it has to be a dictionary to extract values. So you'd probably have to take the entire json object in an attribute and then make template sensors to extract the values for each color
if i could somehow get it into HA i would have no problem with that, but it's over 255 characters
which is why i was hoping to write it to the attributes
I'm having hard time finding the right doc. How do I enter the regex .+(?=\.) in a value template which uses regex_match?
I need to extract filenames for a sensor and this was the simplest regex I was able to write
@brisk temple youโll just have to split the colors into their own sensors it seems
