#templates-archived

1 messages ยท Page 92 of 1

visual aspen
#

But thanks for the script tip

silent barnBOT
arctic sorrel
#

~codewall @mental cedar

silent barnBOT
#

@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.

arctic sorrel
#

I'd use

{{ state_attr('camera.portailwebcam','faces') }}
``` etc
#

Overall looks about right, though sensor.a is an odd choice ๐Ÿ˜‰

thorny snow
#

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?

arctic sorrel
#
{{ state_attr('weather.beta','temperature')|round }}
silent barnBOT
arctic sorrel
#

See the docs ๐Ÿ˜‰

thorny snow
#

I am, my code is based on that page

#

`sensor:

  • platform: template
    sensors:
    weather_current_temp:
    value_template: "{{ states.weather.beta.temperature.state|round }}"`
arctic sorrel
#

See what I posted - that's not based on that page ๐Ÿ˜‰

thorny snow
#

ty Tinkerer, I will try it right now

arctic sorrel
#

You're trying to get an attribute not a state

thorny snow
#

I am a newcomer ๐Ÿ™‚

#

ty @arctic sorrel it works ๐Ÿ˜„

mental cedar
#

@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

silent barnBOT
#

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

arctic sorrel
#

That's... not what I showed

#
{{ state_attr('camera.portailwebcam','faces') }}
``` Those `'` are quite important ๐Ÿ˜‰
#

Test your templates in devtools -> Templates

spark mantle
#

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

mental cedar
#

Thanks i will check later with the states ๐Ÿ™‚

dreamy sinew
#

might just need to add another check for unav

#

or not is_state('sensor.iphone_room', 'unavailable')

spark mantle
#

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

buoyant pine
#

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

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

worn cloud
#

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

dreamy sinew
#

what's the error?

worn cloud
#

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

dreamy sinew
#

definitely going to have an order of operations problem

worn cloud
#

binary_sensor.edgeos_interface_eth5 is coming from an edgeOS intergration

mighty ledge
#

Yup, put the float on the states method not the number 8

dreamy sinew
#

try it in devtools > templates

worn cloud
#

thanks guys! the template it self is outputting the correct value

#

i will change the order of float and reboot now

mighty ledge
#

Youโ€™re probably getting a startup error. Putting the float on the method would remove startup errors when the result is nonnumeric

dreamy sinew
#

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

mighty ledge
#

This whole thing is overwhelming

#

I could change my name to petr to really throw you off ๐Ÿคฃ

dreamy sinew
#

heh

worn cloud
#

i removed float and i still get this error on startup

silent barnBOT
worn cloud
#
value_template: "{{ '%.2f'%(state_attr('binary_sensor.edgeos_interface_eth5', 'MBytes/ps (Received)') * 8 ) }}" 
dreamy sinew
worn cloud
#

thank you!

bitter atlas
#

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?

dreamy sinew
#

what's the actual response?

bitter atlas
#

table.CallInfo.CallID=7

dreamy sinew
#

just like that?

bitter atlas
#

yea

dreamy sinew
#

so it wouldn't be json

bitter atlas
#

i thought the rest converted it

dreamy sinew
#

only if the response header is content_type: Application/JSON

#

otherwise you'll get .text

#

so you probably want {{value.split('=')[-1]}}

bitter atlas
#

hmm

#

so if the sensor shows nothing not even Unknown that means brokerd? lol

dreamy sinew
#

hm

#

try just {{value}}

bitter atlas
#

same, just blank

dreamy sinew
#

ok, i think the call isn't working

bitter atlas
#

if I use {{ value_json }} it returns Unknown but yea anything else is just blank

dreamy sinew
#

i wonder if there's a header you can set

#

do you know how to use python requests?

bitter atlas
#

I wonder if the doorbell banned my ha ip lol

dreamy sinew
#

hah

bitter atlas
#

this is what it looks like in the dump

   "CallInfo" : {
      "CallID" : "7"
dreamy sinew
#

that's more like it

#

can you pastebin the full thing?

bitter atlas
#

but when i access it through the api url it returns what i posted above

#

the full dump? there is nothing higher than CalllInfo

dreamy sinew
#

should be more {} in there. i just want to make sure

bitter atlas
#

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

dreamy sinew
#

just the string?

#

hmm, probably because this is cgi and not rest

bitter atlas
#

that probably means i'm up s creek without a paddle?

dreamy sinew
#

might just have to use a shell command

#

how good are you with curl? ๐Ÿ˜›

bitter atlas
#

lol not very but my google fu is pretty strong haha

dreamy sinew
#

hmm, is there a shell sensor? ๐Ÿ˜ฆ

bitter atlas
#

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

candid valve
#

is that even json

dreamy sinew
#

nope it isn't json

#

do the split thing i did

bitter atlas
#

i did and that was the correct way. it works I get 7 now as the result

dreamy sinew
#

nice!

bitter atlas
#

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

dreamy sinew
#

probably need to poll it and then do an automation on when it increases

candid valve
#

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

bitter atlas
#

well binary would give me a history i can follow easier

dreamy sinew
#

could have an automation trigger an input bool

candid valve
#

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)

bitter atlas
#

let me see what i can cobble together here lol

little gale
#

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
candid valve
#
entity_id:
  - switch.1
  - switch.2
  - switch.3
  ...
bitter atlas
#

dangit the woman is asleep i cannot test this!

dreamy sinew
#

XD

fringe leaf
#

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 %}
arctic sorrel
#

Because it's > -60

#

And you have no else

fringe leaf
#

Yeah I know about the "else".. Want to make a few more elif..

arctic sorrel
#

Yeah, but -62 is less than -60

#

So, clearly it's not "fair"

fringe leaf
#

Right as always... So sleepy.. the minus got me totally confused.. Thanks!

analog plover
#

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?

jagged obsidian
#

how did you defined the sensor in yaml?

analog plover
#

The statistics one or the mqtt-one?

jagged obsidian
#

mqtt first

analog plover
#
  • platform: mqtt
    name: "The box"
    state_topic: "sensor/temperature"
    unit_of_measurement: "ยฐC"
jagged obsidian
#

you might have to take the value of the topic and transform it into float {{ value_json | float }} or maybe | int

analog plover
#

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. ๐Ÿ™‚

jagged obsidian
#

just add a state value in the mqtt sensor to import the temperature properly

analog plover
#

Ah, I think I understand. Using this "value_template" function for MQTT?

warped hornet
#

How do you query last time a switch as in 'on' state?

#

would be nice with states.switch.<id>.last_on or somthing similar

jagged obsidian
#

like {{ as_timestamp(now()) - as_timestamp(states(switch.sensor.garage_door_control.last_updated)) < 10 }}

silent barnBOT
fallen dagger
#

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

arctic sorrel
#

Yes, though see #rules ๐Ÿ˜‰

buoyant pine
#

and you need to use data_template:

dreamy sinew
#

also rule 1 of templating

fallen dagger
#

Sorry๐Ÿ˜… And thanks!

dreamy sinew
#

and {{ now().strftime('%H:%M, %d.%m.%Y') }}

#

-> 11:03, 13.05.2020

#

re-arrange that for your 2nd one

fallen dagger
dreamy sinew
#

nice!

analog plover
#

value_json, simply refer to "the value that is sent by this sensor"?

mighty ledge
#

value_json is the json response from whatever integration you are using

#

it's not limited to a domain

small rock
#

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

small rock
#

Can I do it in a oneliner like this:

{{ if (states('input_number.volume_bureau') | float) > 0 else 1  }}
candid valve
#

where's the other value you want if the condition is met?

small rock
#

it should be the states value

#

I have done it in a multi line

#

it's ok now

#

Need some help on this:

silent barnBOT
small rock
#

Invalid data for call_service at pos 1: expected float for dictionary value @ data['value']

silent barnBOT
#

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.

arctic sorrel
#

What do you get if you paste it into Templates?

small rock
#

@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

candid valve
#

input_select expects option, not value, by the way

small rock
#

Thanks

arctic sorrel
#
{{ 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

silent barnBOT
#

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.

true otter
#

@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?

arctic sorrel
#

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

lethal tapir
#

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}

dreamy sinew
#

it returns like that? That would be odd

nocturne kiln
#

{{ 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' ? ๐Ÿ˜ฎ

lethal tapir
dreamy sinew
#

@nocturne kiln {{ states('sensor.consumption_96') }}

lethal tapir
dreamy sinew
#

so that response is not a valid json payload. it'll make it obnoxious to work with

lethal tapir
#

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");```

nocturne kiln
#

Thanks @dreamy sinew, I feel dumb now. ๐Ÿ˜›

dreamy sinew
#

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

edgy gorge
#

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

marble sun
#

what's your current template?

edgy gorge
#
  • 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' }}
candid valve
#

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

edgy gorge
#

Is this something I'd put in my current template or a new one?

candid valve
#

could you please show me an example of what sensor.time looks like

marble sun
#

take the 0 out of {:02d}

#

or the 02 for that matter

#

it means "2-wide, 0-prefixed to fill"

edgy gorge
#

Gotcha

#

Lets see

valid silo
#

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.

mighty ledge
#

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.

valid silo
#

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?

solid storm
#

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?

mighty ledge
#

Yes, that's the point of the entity_id field. To update the sensor. If you want to update it minutely, use sensor.time.

graceful needle
#

has anyone had experience with Cover templates?

#

Is it possible to invert "position_template" so 0 is open and 100 is closed?

mighty ledge
#

just invert the value being used in position template

#
position_template: "{{ 100 - whatever_value_is_inverted }}"
graceful needle
#

position_template: "{{ 100 - states('sensor.bedroom_curtain_position') }}"

#

is this supposed to work?

buoyant pine
#

Add | int to the end (right before }}") @graceful needle

graceful needle
#

Ahh cheers!

fair vessel
#

Hi there can anyone help me add a date with uk formating please

arctic sorrel
#

Do you already have the date/time/whatever in an existing entity?

fair vessel
#

have this - platform: time_date
display_options:
- 'time'
- 'date'
- 'date_time'
- 'date_time_iso'
- 'time_date'
- 'time_utc'
- 'beat'

arctic sorrel
#

Ok, and what are you trying to achieve?

#

Just a date, a date and time, a...?

fair vessel
#

have a basic clock with date at the bottom and its currently showing yyyy/mm/dd

arctic sorrel
#
{{ 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
fair vessel
#

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') }}"
silent barnBOT
#

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

arctic sorrel
#

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

silent barnBOT
arctic sorrel
#

~codewall @fair vessel

silent barnBOT
#

@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.

fair vessel
#

sorry

arctic sorrel
#

Is all you're after turning - into /?

#
{{ states('sensor.date')|replace("-", "/") }}
fair vessel
#

no currently its show as 2020/05/16, i need it to be 16/5/2020

arctic sorrel
#
{{ as_timestamp(strptime(states('sensor.date_time'), "%Y-%m-%d, %H:%M"))|timestamp_custom("%d/%m/%Y") }}
#

You can test all this in devtools -> Templates

fair vessel
#

thank you. so did i need to do anything in the config? or just somehow use this in the card for the clock

arctic sorrel
#

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:

fair vessel
#

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 ?).

arctic sorrel
#

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

fair vessel
#

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

arctic sorrel
#

No worries

#

The sensor is a string, so the format is fixed

long sequoia
#

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/

arctic sorrel
#
value_template: >-
  {%- if is_state('input_boolean.bin_status','on') -%}
    Outside
  {%- else -%}
    Inside
  {%- endif -%}
``` (long form)
long sequoia
#

hmm strange. I put that in my config, and now the binary sensor is just stuck at "off" regardless of the switch position

arctic sorrel
#

Well, you add that to a template sensor ๐Ÿ˜‰

#

The binary sensor is only ever on/off

long sequoia
#

did I do something wrong there?

arctic sorrel
#

Yes

#

A binary sensor, by definition, is only on or off

long sequoia
#

Setting a template sensor is "- platform: template" right?

long sequoia
#

ohh ok I see what you're saying now. imma fix that up

#

Got it all working how I wanted it to. Thanks mate.

silent barnBOT
thorny snow
#

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

bitter atlas
#

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

buoyant pine
#

@bitter atlas that template would only be evaluated when the binary sensor's state changes

bitter atlas
#

yea

#

the binary in the template is seperate than the sensor

#

I may havve found my problem aside from lack of sleep, checking something

buoyant pine
#

No like, that will always return False if used in a template trigger

bitter atlas
#

?

arctic sorrel
#

now() doesn't cause the trigger to be evaluated

buoyant pine
#

It only updates when the binary sensor's state changes

arctic sorrel
#

So, when the last_changed and now() are the same ๐Ÿ˜‰

bitter atlas
#

I guess I don't follow. the binary being evaluated is a separate entity from the template sensor.

buoyant pine
#

I'm talking about the trigger

#

Template triggers are only evaluated when the entities in the template change state

arctic sorrel
#

(this is, curiously, mentioned in the docs)

#

The only entity in your trigger is binary_sensor.amcrest_camera_motion_detected

bitter atlas
#

when you assign the entity_id to an entity where the state does change, it should work?

buoyant pine
#

If that's in a template sensor it would also only update when the binary sensor's state changes

arctic sorrel
bitter atlas
#
    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 %}
arctic sorrel
#

That also would only be valid exactly 10 seconds later

bitter atlas
#

yea

#

I want it to only be vaild at 10 seconds

buoyant pine
#

That will always be off

arctic sorrel
#

Then, move to a time and date sensor instead of now

bitter atlas
#

yea none of this likes me lol

arctic sorrel
bitter atlas
#

apparently you can't use sensor.time in the template editor

arctic sorrel
#

Well, if it exists, you can use it

bitter atlas
#

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

arctic sorrel
#

Does it exist?

#

Have you actually checked that?

bitter atlas
#

yea

#

I have it set up

#

So, when the last_changed and now() are the same ๐Ÿ˜‰
@arctic sorrel haha this just clicked for me, makes perfect sense.

#

way too tired to be doing this lol

arctic sorrel
#

Time for a nap ๐Ÿ˜‰

bitter atlas
#

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

bitter atlas
#

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

arctic sorrel
#

Likely a PEBCAK

bitter atlas
#

well i can show the state of it, just couldn't use it to compare time

arctic sorrel
#

I use them in various places...

#

So, something wrong with your template

bitter atlas
#

i have no doubt it was user error with that lol

hexed galleon
#

Is it possible to reference the last changed/last updated value for a person using a template?

hexed galleon
#

What the hell timezone is {{ states.person.xxx.last_changed }} stored in? Doesn't look like UTC, and definitely not local.

thorny snow
#

epoc seconds I thought

hexed galleon
#

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.

thorny snow
#

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

thick barn
#

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

hexed galleon
thick barn
#

also, can a template be a entity? I woul;d like a button so i can enable and disable the entity

hexed galleon
#

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

thorny snow
#

what's your time zone? Some people are in the future

hexed galleon
#

UTC+10

#

Well, not in the future any more, but the last change was definitely before 10:06am local.

thorny snow
#

silly questionm, but how are you sure it didn't change?

hexed galleon
#

Unless it's considering any attribute for the last_changed, rather than just the state.

thorny snow
#

are what are you using to track the person?

hexed galleon
#

As my GPS might have changed at 10:06am.

thorny snow
#

yeah, I am saying that's possible it dropped out for a sec

hexed galleon
#

Not according to the state history. Solid state since 8:08.

thorny snow
#

that litle graph????? a split second couldn't show up on that!

hexed galleon
#

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."

silent barnBOT
thorny snow
#

@thick barn why don't you do this in the automation editor? It sounds easy to accomplish

thick barn
#

they suggested a template

thorny snow
thick barn
#

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

thorny snow
#

change names of course

#

and then make a binary_input and use it as a condition for those to work

hexed galleon
#

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.

thorny snow
#

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

thick barn
#

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

thorny snow
#

that's what I did, just to make sure you could.

#

I couldn't use your real entities though

thick barn
#

sorry for the dumb questions, where do you put the text version of the automation?

buoyant pine
#

automations.yaml by default

thick barn
#

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...

thorny snow
#

yes

buoyant pine
#

I think stolid means "input_boolean"

thorny snow
#

If you edit manually, make sure you reload autos in config

#

I did mean bool

buoyant pine
#

But I'm also not sure what the purpose of that is

thorny snow
#

he wants a button on his dashboardthat can turn them both off

#

I know you can turn each off though

#

enable/disable

buoyant pine
#

This can be done in one automation with templating which I think he was trying to do

thorny snow
#

there's usually more than one way to do it, and I assure you, mine is the dumbest

buoyant pine
#

Lol I'm not saying that

thick barn
#

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!

thorny snow
#

I know.. I am.. I don't know how to get those templates right yet

buoyant pine
#

With one automation you could just turn the automation on and off without making a boolean

thick barn
#

yeah i don't mind which way, im just happy to learn (even if i have to be spoon fed a bit)

thorny snow
#

Well, I try to make it work, then make it pretty

buoyant pine
#

you had the right idea with your template, i just adapted it to a one-liner

#

making a minor correction, hang on

hexed galleon
#

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.

thorny snow
#

@hexed galleon updated and changed kinda confused me too

candid valve
#

attributes register changes too

candid valve
#

in the case of person which device_tracker source is probably responsible

thick barn
#

oh awesome @buoyant pine
how do I go about using that? Do I make a new automation and set the trigger type as template?

buoyant pine
#

that's a complete automation

#

you can drop it in and reload automations at configuration > server controls

thick barn
#

oh awesome!

buoyant pine
#

add whatever conditions you want, if any

hexed galleon
#

@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."

candid valve
#

I apologize

thorny snow
#

damn I need pictures of these things to understand them

thick barn
#

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 ๐Ÿ™‚

hexed galleon
#

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.

buoyant pine
#

weird. not even something like home to unavailable to home?

#

or unknown, etc

hexed galleon
#

No, solidly "work" the whole time.

buoyant pine
#

definitely weird then

hexed galleon
#

Unless the UI ignores state changes of a very small period.

buoyant pine
#

@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

pastel haven
#

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

pastel haven
#

uau, your fast, sppedy gonzales. Thx for this swift reaction.

arctic sorrel
#

No worries, it was easy because somebody asked yesterday ๐Ÿ˜‰

pastel haven
#

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") }}
topaz walrus
#

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

buoyant pine
#

As in the difference between them?

topaz walrus
#

so entity 1 is 80* and entity 2 is 100*

#

the sensor we build would show 20*

#

yeah

dreamy sinew
#

maybe sensors|max - sensors|min ?

topaz walrus
#

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

buoyant pine
#

If it's just two entities you can just do

{{ states('sensor.foo') | float - states('sensor.bar') | float }}
topaz walrus
#

ok so in .conf it would look like this?

dreamy sinew
#

{{ sensors|max - sensors|min }}

#

use the same set sensors block from your first one

#

meaning copy-paste

topaz walrus
#

ok yeah

#

so the average temp sensor example i sent

#

the bottom of it is the "argument"

#

or whatever you wanna call it

dreamy sinew
#

{{}} is a "print statement"

topaz walrus
#

the "rule"

buoyant pine
#

And the set part is you creating a variable

topaz walrus
#

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

buoyant pine
#

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)

topaz walrus
#

so thats where {{ sensors|max - sensors|min }}

#

would go

dreamy sinew
#

i had to tweak that average one recently though

#

(i think you're using mine) ๐Ÿ˜›

topaz walrus
#

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

dreamy sinew
#

{{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}

topaz walrus
#

thats what changed at the bottom

dreamy sinew
#

unav/unknown -> 0.0

topaz walrus
#

very noobish when it comes to this stuff sorry

dreamy sinew
#

i had a battery die on one of my sensors and it tanked my averages

topaz walrus
#
          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

dreamy sinew
#

yup

#

might be worth having that reject on the sensors|min bit on the new one too

topaz walrus
#
          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

dreamy sinew
#

yup, looks good

topaz walrus
#

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

dreamy sinew
#

nah, it's just show the value of the sensor that is working

topaz walrus
#

yeah weird lol

dreamy sinew
#

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 ยฏ_(ใƒ„)_/ยฏ

topaz walrus
#

{{ sensors|max - sensors|min reject("eq", 0.0) }}

#

that all i have to add?

dreamy sinew
#

sensors|reject("eq", 0.0)|list|min

topaz walrus
#

ahh so close

#

haha

dreamy sinew
#

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"

topaz walrus
#

{{ sensors|max - sensors|reject("eq", 0.0)|list|min}}

dreamy sinew
#

in this case, the min in the other case, counting the number of items

#

looks good

topaz walrus
#

ahh ok

#

thanks!

#

if i were to add a second which would be humidity

#

i would only change unit_of_measurement: 'ยฐF'

#

to %

dreamy sinew
#

yep, should work

topaz walrus
#

ok awesome

frail hawk
#

is there an easy way to test a value_template other than having to restart each time

arctic sorrel
#

devtools -> Templates

frail hawk
#

<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

arctic sorrel
#

Which one though ๐Ÿคท

frail hawk
#

"temperature":"12.8"

#

or any other for that matter ๐Ÿ˜‰

arctic sorrel
#
{{ state('sensor.thing')[0].temperature }}
``` (probably)
dreamy sinew
#

not likely with that structure

topaz walrus
#

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

dreamy sinew
#

@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)

frail hawk
#

@dreamy sinew nice... now i just need to get it from sensor.json_vejr instead

dreamy sinew
#

yup, drop that whole first section and replace value with states('sensor.json_vejr')

frail hawk
#

Error rendering template: UndefinedError: 'str object' has no attribute 'get'

topaz walrus
#

im a tard

dreamy sinew
#

value_json

topaz walrus
#

cant get the template editor to accept

#

{{(sensors|max - sensors|reject("eq", 0.0)|list|min) round|(1)}}

dreamy sinew
#

|round(1)

topaz walrus
#

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

frail hawk
#

@dreamy sinew where do you want me to add that ?

dreamy sinew
#

flip the math?

topaz walrus
#

basically

dreamy sinew
#

min - max

topaz walrus
#

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.

thorny snow
#

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

dreamy sinew
#

no

frail hawk
#

@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

dreamy sinew
#

not something i've really dealt with ยฏ_(ใƒ„)_/ยฏ

mighty ledge
#

@frail hawk "{{ value_json[0]['200000555'].temperature }}"

frail hawk
#

@mighty ledge works on the - platform: rest but not on the - platform: template element

dreamy sinew
#

maybe {{ states('sensor.whatever')|tojson[0]...}}

frail hawk
#

will test ๐Ÿ™‚

dreamy sinew
#

but the real answer might be to just do it in the rest sensor directly

frail hawk
#

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

dreamy sinew
#

add all the other bits i sent you

frail hawk
#

worked this time... didn't before... nice ๐Ÿ™‚

mighty ledge
#

Put the value in attributes for rest

frail hawk
#

now i just need to find out how to do the {% set value = states('sensor.json_vejr')|from_json %} part in the sensor

mighty ledge
#

Youโ€™re limited to 255 characters for the state

#

Youโ€™re going to run into issues

frail hawk
#

so far it saves the items fine

#

but yes i might give problems in the long run

mighty ledge
#

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.

frail hawk
#

thats home assistant that gives it '... cause the source is with "

mighty ledge
#

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 }}
frail hawk
#

yes that works in the testing.... now i just need that down into my config ๐Ÿ™‚

frail hawk
#

thanx @mighty ledge and @dreamy sinew ๐Ÿ™‚ now i just need to get all the devices added ans showed in the frontend ๐Ÿ™‚

sturdy juniper
#

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

brisk temple
#

Grass is capitalized

dreamy sinew
#

daily forecasts is also a list

sturdy juniper
#

{{ states.sensor.accuweather.attributes.DailyForecasts{10}.Grass }}

#

isnt working either, forgive my ignorance, its all new to me ..

rugged laurel
#
{%set a=(state_attr('sensor.accuweather', 'DailyForecasts')[0].AirAndPollen | selectattr('Name', 'in', 'Grass') | list)[0]%}{{a.Category}}
dreamy sinew
#

are you testing in the template tester?

#

devtools > Templates

sturdy juniper
#

{%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

quiet creek
#

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?

rugged laurel
#

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

sturdy juniper
#

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

rare panther
little gale
#

Whats wrong here?

{{ (states('sensor.internal_media_used') | float / 1024) | round(2) }}
buoyant pine
#

Looks fine, what issue are you having

little gale
#

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

buoyant pine
#

Wrap it in double quotes

little gale
#

It is

buoyant pine
#

Include the whole thing that this is part of

little gale
#
        value_template: {{ (states('sensor.internal_media_used') | float / 1024) | round(2) }}
buoyant pine
#

No, wrap the template in double quotes

#

"{{ (states('sensor.internal_media_used') | float / 1024) | round(2) }}"

little gale
#

oh ok

buoyant pine
#

Otherwise it's interpreted as a dictionary

little gale
#

Gotcha. Thanks ๐Ÿ™‚

charred dagger
#

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.

arctic sorrel
#

Templates are fun ๐Ÿ˜„

#

Sane... here... ๐Ÿค”

charred dagger
#

Inb4 "bUt PyThOn": Python is a programming language, it could make sense there. Yaml is a data storage format.

mighty ledge
#

Wrap that sucker in quotes

#

Oops, replying to really old msg

arctic sorrel
#

๐Ÿคฃ

mighty ledge
#

As long as your repr is unique you can use any object as a key for a dict

charred dagger
#

Unique and hashable.

rain glacier
#

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

dreamy sinew
#

should be fine. drop it into the template tester

#

devtools > templates

buoyant pine
#

round(2) maybe?

dreamy sinew
#

oh, yeah

#

you're a bit space happy

rain glacier
#

heh

buoyant pine
#

๐Ÿ‘€

dreamy sinew
#

might need |float and |round(2)

#

i think that's one of those that doesn't matter until it does

rain glacier
#

where wouldi put that

#

before the round (2)

dreamy sinew
#

no, make the places where you're using those and make them look like that

rain glacier
#

oh ok

#

still 0

dreamy sinew
#

you made some changes, what does it look like now?

rain glacier
dreamy sinew
#

you didn't fix the first float, you didn't fix the round

rain glacier
#

oh

dreamy sinew
#

now try it in the template tester

rain glacier
#

still 0

dreamy sinew
#

0 or 0.0 ?

rain glacier
#

0.0

dreamy sinew
#

in the tester just output both your sensors individually

#
{{ states('sensor.sensor2') }}```
#

are either of those 0?

#

or unav/unk?

rain glacier
#

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

silent barnBOT
pine wigeon
#

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 ?

hollow bramble
#

You need to update the sensor based on an entity that's constantly updating ie a time sensor. now() only renders once

pine wigeon
#

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()...

hollow bramble
#

You can use now(), but you have to list sensor.time under entity_id

buoyant pine
#

in the template sensor config

hollow bramble
#
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

pine wigeon
#

I've edited, restart takes several minutes even with the Ryzen 5, I will see. Thank you Villhellm, you helped me a lot today. ๐Ÿ‘

hollow bramble
#

Do you have a Zwave network tied to HA?

pine wigeon
#

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 ๐Ÿ˜†

hollow bramble
#

You need to add those under entity_id as well

pine wigeon
#

Do you have a Zwave network tied to HA?
@hollow bramble Nope, only 10+ NodeMCU

hollow bramble
#
entity_id:
  - input_datetime.reveil_h_min
  - input_datetime.reveil_h_min
  - sensor.time
#

Or you could just wait a minute ๐Ÿ˜‰

pine wigeon
#
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

hollow bramble
#

What does your sensor config look like now?

pine wigeon
#
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: >-
hollow bramble
#

The second one doesn't work?

pine wigeon
#

Nope, sadly

hollow bramble
buoyant pine
#

Does sensor.time exist?

#

Check developer tools > states

pine wigeon
#

Yup

#

friendly_name: Time
icon: 'mdi:clock'

hollow bramble
#
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 ๐Ÿ˜…

pine wigeon
#
  • 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 ๐Ÿ˜†

hollow bramble
#

No, sorry I thought your template had two entities. I wasn't paying close enough attention

pine wigeon
#

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

hollow bramble
#

That I'm not sure of. Either way performance impact would be minimal

pine wigeon
#

Yeah, sure.

mighty ledge
#

@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.

versed lava
#

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?

silent barnBOT
#
:ping_pong: ping?

PONG!

versed lava
#

thanks. found a way

tight thicket
#

Hey everyone. How can I display the time that has expired since a windows contact (on/off) was triggered the last time?

arctic sorrel
#

Set the secondary_info value

tight thicket
#

I have seen that, but I want to show this info on the right side instead of the "open / closed" state

arctic sorrel
#

That then would require a template sensor

tight thicket
#

Are there any examples?

arctic sorrel
#

You have to build the logic you want into the template, for all of it

#

Possibly something like {{ states.binary_sensor.window.last_updated }}

tight thicket
#

Okay i will try, thank you !

hollow ocean
#

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?

hollow ocean
#

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?

ivory delta
#

@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)

mighty ledge
#

@hollow ocean post the entity you are pulling the info from. Take a screenshot of it on the devtools -> states page.

hollow ocean
#

@mighty ledge apparently I can't post photos?

mighty ledge
#

use something like imgur

hollow ocean
mighty ledge
#

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

silent barnBOT
arctic sorrel
#

~codewall @timber locust

silent barnBOT
#

@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.

timber locust
#

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'}

arctic sorrel
#

Possibly

          params: {{states('input_select.vacuum_room_numbers')|int}}
#

The quotes turn it into a string

timber locust
#

I think the code fails to verify when I do that. Let me check!

hollow bramble
#

The service should be parsing it anyway. Might be considered a bug

arctic sorrel
#
      - 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') }}"
timber locust
#

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

hollow bramble
#

Need to wrap it in quotes

arctic sorrel
#
          params: >-
            {{states('input_select.vacuum_room_numbers')|int}}
``` should work then, but I suspect will suffer the same problem
hollow bramble
#

or that

arctic sorrel
#

Yeah, I was wondering if the quotes was turning it into a string, and causing the original issue

timber locust
#

I did Tinkerer's suggestion, and now it validates.

arctic sorrel
#

The real question is, does it work

timber locust
#

About the suggestions that you made earlier, using is_state_attr(), why use that instead of what I have? Is it better practice, or?

arctic sorrel
#

See the templating docs ๐Ÿ˜‰

#

Better practice (basically)

#

There are times you'll want to use the approach you've got though

hollow bramble
timber locust
#

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

hollow bramble
#

Oh okay now I see what you're getting at

timber locust
#

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'}

hollow bramble
#

It could be you're not giving it an array

timber locust
#

When I use the call service dev tool, I can feed it a number or an array and it is fine.

hollow bramble
#

params: ["{{states('input_select.vacuum_room_numbers')|int}}"]

timber locust
#

I tried to give it an array before, that doesn't work.

hollow bramble
#

It works if you wrap the number in quotes?

timber locust
#

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'}

hollow bramble
#

no, quotes go inside the array

#

you just turned the array into a string

timber locust
#

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.

hollow bramble
#

where is key: coming from?

timber locust
#

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.

hollow bramble
#

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

timber locust
#

Okay. Where/how do I do that?

#

Ah. Found it on the website.

timber locust
#

Thank you guys so much for your help!

hollow bramble
#

Sorry it's not actually solved

timber locust
#

Is it a bug in the component or with home assistant itself?

hollow bramble
#

The component is part of home assistant

timber locust
#

But I mean is it with how home assistant handles templates, or with this specific component?

hollow bramble
#

It's with this specific component. The send_command service specifically

timber locust
#

Ah okay. Thanks for the heads-up! I'll file a bug report!

hollow bramble
#

Oh actually it looks like send_command is a service on the base vacuum component

timber locust
#

Is this a good title for the issue: vacuum send_command does not parse non-integer in template

hollow bramble
#

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

timber locust
#

I realise how important good documentation/logging is to solve these problems.

hollow bramble
#

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

timber locust
#

Very good point! Thanks. Updated!

#

Hey @hollow bramble thanks so much for your quick support. I really appreciate it! ๐Ÿ™‚

hollow bramble
#

No problem, glad to help

timber locust
#

How long does it usually take for an issue to get picked up?

buoyant pine
#

Between now and the heat death of the universe

#

There's no clear answer tbh

hollow bramble
#

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

timber locust
#

So days to weeks?

hollow bramble
#

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 ๐Ÿ˜‰

timber locust
#

Haha

hollow bramble
#

Put considering the backlog of 1000+ issues and 250+ PRs idk

timber locust
#

To me, it sounds like a relatively simple issue to fix. If params == string, params = str2num(params) endif.

hollow bramble
#

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

timber locust
#

Sounds understandable. I'm only used to cooking home-made spaghetti in Matlab ๐Ÿ˜›

small silo
#

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.

timber locust
#

Do you get an error in the logs?

heady egret
#

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?

hollow ocean
mighty ledge
#

@hollow ocean yes, the good news is, you already have the complicated part complete

hollow ocean
#

thats encouraging

mighty ledge
#

@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

hollow ocean
#

I dont know where the JSON is?

#

But, I can just put this into the sensor and it will work?

mighty ledge
#

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"
hollow ocean
#

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

mighty ledge
#

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.

hollow ocean
#

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

mighty ledge
#

Youโ€™re missing the leading ( in the template. Check my previous post and compare it to yours. Try it in the template editor

hollow ocean
#

oh its unny how sometimes I just dont see those little things

brisk temple
#

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

hollow ocean
#

@mighty ledge I dont think Im seeing the missining (

brisk temple
#

you have an ending ) after the 86400s but not a beginning (

hollow ocean
#

so it goes ahead o 1

brisk temple
#

i assume you want it infront of now()

#

{{ (now().timestamp() + 1 * 86400) | timestamp_custom("%A") }}

hollow ocean
#

that also led to an erro

mighty ledge
#

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.

silent barnBOT
hollow ocean
#

it looks like this now

#

and I get the errors

arctic sorrel
#

~codewall @hollow ocean

silent barnBOT
#

@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.

hollow ocean
#

sorry about that

mighty ledge
#

I don't know how that's possible because the template is correct and your format is correct.

#

post the error

hollow ocean
hollow bramble
#

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') }}"

marble sun
#

double quotes donโ€™t work inside single quotes?

hollow ocean
#

removing the double quotes caused a red exclamation mark

marble sun
#

huh, Iโ€™d never have guessed

#

thank you!

hollow ocean
#

it is an error

hollow bramble
#

What is the error

hollow ocean
#

bad indentation of a mapping entry at line 73, column 76:
... timestamp() | timestamp_custom('%A') }}'

hollow bramble
#

... you need double quotes on the outside, like I posted

hollow ocean
#

will try

marble sun
#

@hollow bramble I thought those docs were just the HA house style for people writing documentation, not a syntax requirement

hollow ocean
#

im still getting errors in the log

hollow bramble
#

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

hollow ocean
#

and here is the sensor jic

hollow bramble
#

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

hollow ocean
#

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

hollow bramble
#

Test each one in the templates tool

hollow ocean
#

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*

hollow bramble
#

Now do that for all of them

hollow ocean
#

It worked! This was awesome and super helpul

#

much appreciated

#

I will use the template tool way more too

hollow bramble
#

Yes, always test templates before using them in a configuration

hollow ocean
#

makes total sense

mortal monolith
#

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

mighty ledge
#

@hollow bramble you can interchange doulbe and single quotes for inside/outside. That doesn't matter.

buoyant pine
#

though, single outside/double inside looks weird IMO

mighty ledge
#

yah, but it's easier to replace 2 double quote outsides than 27424 double quote insides

#

#lazy

hollow bramble
#

replace all " with ', then replace all '{{ and }}' with "{{ and }}"

rugged laurel
#
options: "{{states.media_player | map(attribute='entity_id') |list }}"
hollow bramble
#

then watch everything break when you had random spaces ๐Ÿ™‚

#

Oh dang, ninja promotion ๐ŸŽ‰

dreamy sinew
#

i'm not sure if that'll work though because you'd get a stringified list

rugged laurel
#

yeah... one can hope ๐Ÿคทโ€โ™‚๏ธ

dreamy sinew
#

maybe |list|tojson?

rugged laurel
#

potentially

#

better to just use AD for it ๐Ÿ˜„

dreamy sinew
#

haha

mighty ledge
#

replace all " with ', then replace all '{{ and }}' with "{{ and }}"
@hollow bramble that's 1 extra step i'm willing to skip

dreamy sinew
#

maybe a multiline could solve it

dreamy sinew
#
{%- for player in states.media_player | map(attribute='entity_id') |list %}
  - {{ player }}
{%- endfor -%}```
rugged laurel
#

Wouldn't that just give:

"- entity"
  "- entity"
dreamy sinew
#

with proper escapging

rugged laurel
#

sure, but the template engine will mangle it?

dreamy sinew
#

ยฏ_(ใƒ„)_/ยฏ

mighty ledge
#

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

buoyant pine
#

M A L F O R M E D

dreamy sinew
#

mine?

buoyant pine
#

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

crude crest
#

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.

rugged laurel
crude crest
#

and then pass that timestamp to something relative_time or something to measure how long it's been.

rugged laurel
#

if you make it a template sensor, you can add the timestamp device class, and the UI makes it human readable

crude crest
#

Good point

#

also, hacs 1.0 looks awesome. thanks for your work.

rugged laurel
#

What's wrong with that?

crude crest
#

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

hollow bramble
#

You can use for in a condition

#

time trigger, condition for 24 hours

crude crest
#

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.

hollow bramble
#

You have 2 vacuums, why not just make 2 automations?

crude crest
#

it's either that or a template. probably easiest to just make 2 automations.

hollow bramble
#

That would be a very complicated template if your trigger is going to be time regardless

crude crest
#

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.

pulsar flax
#

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

mighty ledge
#

That probably depends on the integration

pulsar flax
#

I mean it works but I was curious for my own knowledge

dreamy sinew
#

its a quirk with how apps are named in the android os

pulsar flax
#

ah ok

brisk temple
#

Is there a way to test the value_template of a json without having to make a change reboot, rinse, repeat?

arctic sorrel
#

Well, don't reboot for a start

#

devtools -> Templates though

brisk temple
#

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

hollow bramble
#
{% set value_template = 'paste your json here' |from_json %}
{{value_template.value_you_are_looking_for}}
#

or whatever you want to call the object

brisk temple
#

setting the json in templates i think is going to at least save my sanity

#

thanks

brisk temple
#

I can't get the json_attributes to work in this

#

just goes to state

glad zealot
#

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]}}

flint light
#

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

hollow bramble
#

That's not really how scipts work. They never change state

#

They do have a last_triggered attribute

flint light
#

I see.. why the loop above shows a value..

hollow bramble
#

It probably shows the value of the last time you restarted HA

#

or the last time the attribute was updated

flint light
#

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.

hollow bramble
#

Oh maybe I'm misremembering. What information are you trying to get?

flint light
#

But you are right... they have a last_triggered also.. but how can I get that value?

hollow bramble
#

I just ran a script and last_changed stayed the same

flint light
#

It has to have a delya in it

hollow bramble
#
{% for state in states.script -%}
  {{state_attr(state.entity_id, 'last_triggered')}}
{%- endfor %}
flint light
#

if I try {{ states.script.1590120819845.last_triggered }} it trhows an error

hollow bramble
#

It's an attribute

flint light
#

ah OK.. let me try

hollow bramble
#

So you'd have to do script.script_name.attributes.last_triggered

#

but it's better to use the state_attr function

flint light
#

{{state_attr(state.script.1590120819845, 'last_triggered')}} does not work

hollow bramble
#

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

flint light
#

Yes. That was the problem Now it works.

#

Thanks!!!

flint light
#

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. ๐Ÿ™‚

kindred forge
#

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

flint light
#

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 }}

flint light
#

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 }}

final acorn
#

Nest

brisk temple
#

Is anybody able to look at this and suggest why everything is going to state and not attributes?

hollow bramble
#

@brisk temple what value are you trying to parse for the state?

#

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

brisk temple
#

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

wary horizon
#

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

hollow bramble
#

@brisk temple youโ€™ll just have to split the colors into their own sensors it seems