#templates-archived

1 messages Β· Page 91 of 1

buoyant pine
#

the UI doesn't handle templates well

fast mason
#

I know the templates result into corresponding devices/radios

#

I'll change the yaml and check

buoyant pine
#

btw this is a better method for templates:

"{{ states('input_select.playback_device') }}"
fast mason
#

I've seen both around but never understood the difference. Are there pros/cons sort of thing?

buoyant pine
#

basically prevents errors from being printed in the log

#

IMO it also looks cleaner especially when you start tapping into state attributes

fast mason
#

Yayyy that worked now πŸ˜† Thanks a lot!

#

Haven't play much with templates before so it's all new for me

#

Ah another quick question. For the input_select dropdown options is it possible to set up friendly names?

#

Rather than choosing from e.g. media_player.kitchen_dot etc to Kitchen Dot

buoyant pine
#

you could change the input select options to what you want and use templating to convert it to an entity ID

#
entity_id: "media_player.{{ states('input_select.playback_device').lower().replace(' ', '_') }}"
#

if the input select option is Kitchen Dot that would generate media_player.kitchen_dot for the service call

fast mason
#

Hmmm it's giving me media_player.h_o_m_e e_c_h_o

#

Is there any good links you know for learning how to create templates like that?

#

I don't know what I should be googling exactly

buoyant pine
#

oh whoops lol

#

correction above

#

the page i linked above is helpful and also has a link to the jinja2 templating engine docs which is what home assistant uses for templating

#

apart from that the online python courses i took were helpful in learning how to do other things with templating/string manipulation

fast mason
#

I know what I'll be doing when I'm off work

buoyant pine
#

it's pretty fun. you can also test templates at developer tools > template before adding them to automations, sensors, etc

fast mason
#

That's what I've been doing πŸ˜‰

buoyant pine
#

brings a tear to my eye

trail estuary
#

Hi folks! Is it possible to use a template to extract data from an event?

arctic sorrel
#

πŸ€”

trail estuary
#

Those are triggers. Not exclusive to automations?

arctic sorrel
#

Triggers are exclusive to automations, hence why that's in the automations part of the docs πŸ˜‰

trail estuary
#

Hehe... Let me explain my intentions then. πŸ˜‰

rugged laurel
#

you want an eventsensor, not possible with core, there is a custom option

trail estuary
#

I use an ESP to pass some data to HA. I can listen for the event on HA, but I was wondering if I could set up a template sensor to hold the data I need.

#

@rugged laurel Ahh!

arctic sorrel
#

You could fake it with an event trigger and in input numer/text/whatever

rugged laurel
#

okey... sure...
do that ☝️

arctic sorrel
#

number, even 🀷

#

I'm lazy, if I have the tools to assemble a Heath Robinson contraption, why not πŸ˜›

trail estuary
#

Thanks guys! I might be back when my attempts on this isn't working! πŸ˜›

dusty hawk
#

I've been working to get sensors that track the number of lights, windows, etc, on/open, whatever. This generates the count:

#
{{ expand('group.all_lighting')|selectattr('state','eq', 'on')|list|count }}
#

But, the group's state doesn't update when another light comes on, only when the first one does, or the last ones goes off. So, I need a heartbeat it seems to get the expand() to execute periodically. Here's what I'm trying: (time updates by minute)

#
{% if (strptime(states('sensor.time'),'%-M')|int) in range(0, 59) %}
   {{ expand('group.all_lighting') | selectattr('state','eq', 'on') | list | count }}
{% endif %} 
#

Seems that every minute I'll execute my expand(). I'll see.

#

Is there a better way, or a better heartbeat to use to force template sensor updates?

slate ferry
#

Hey folks, I have a thermostat that is showing the temp as 10x the actual value. Can someone explain how I might make a template and divide the temp sensor value by 10?

mighty ledge
#

@dusty hawk it won't update because the template can't resolve any entities to update from. You need to list out all the entities in the group to the entity_id field.

#

@slate ferry look up template sensors & templating. {{ states('sensor.xxx') | float / 10 }}

slate ferry
#

Thanks Petro, I’ll play with that and see what happens.

dreamy sinew
#

fun thing i just got bit by, states('sensor.xxx') | float returns 0.0 for unknown / unavailable

#

i have a template that averages a bunch of sensors and that 0 tanked the value πŸ˜„

#

Solution is to reject the values before the divide for the average

#
          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)}}```
thorny snow
#

hi all, can a sensor template hold one url as the value, something like this: `

#

- platform: template sensors: ring_video_url: friendly_name: "Ring video url" value_template: "{{ state_attr('camera.front_door', 'video_url') }}"

#

because what i get is a state unknown

arctic sorrel
#

Check the template in devtools -> Templates and check your log file for errors or warnings

thorny snow
#

yep, thak you, so i found this on the log: . State max length is 255 characters.

nimble skiff
#

Hi all. I'm trying to test a REST sensor. They query returns the expected JSON but how can I use a value_template to parse out just the 'ltebandwidth' value? Thank you!
{"data": [{"ltebandwidth": "10 MHz"}], "meta": {"limit": 20, "next": null, "offset": 0, "previous": null}}

buoyant pine
#
"{{ value_json['data'][0]['ltebandwidth'] }}"
nimble skiff
#

@buoyant pine thank you that worked perfectly. I should have asked before but because the value is '10 MHz' and not 10, will the sensor card line graph still update as the value changes? Or if not is there a way to strip off the ' MHz' ? Thanks again!

buoyant pine
#
{{ value_json['data'][0]['ltebandwidth'].replace(' MHz','') }}
#

if you use that and set a unit of measurement for the REST sensor it should work with the line graph

#

unit of measurement being MHz

deep tapir
#

Trying to get a template binary sensor working to pull an attribute from an Ecobee thermostat. Have tried the following:

#

binary_sensor:

  • platform: template
    sensors:
    furnace_fan_living_room:
    friendly_name: Fan Running
    device_class:
    value template: "{{ is_state_attr('climate.entryway' ,'fan' ,'on') }}"
#

Any thoughts on where I'm going wrong?

buoyant pine
#

You left device_class: blank and value template: should be value_template:

#

Also...

silent barnBOT
#

@deep tapir 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

deep tapir
#

I get:

#

Invalid config
The following integrations and platforms could not be set up:

binary_sensor.template
Please check your config.

buoyant pine
#

Take a look before that

deep tapir
#

Thanks. The underscore for value_template must have fallen out in one of the variants I tried. That fixed it!

snow zenith
#

Hi can someone help with this please

sensor:
  - platform: file
    name: smartctl
    file_path: "/smartctl/test.json"
    value_template: "{{ value_json }}"
  - platform: template
    sensors:
      dev_sda_smart_status_passed:
        value_template: "{{ value_json.smart_status.passed }}"
      dev_sda_temperature_current:
        value_template:  "{{ value_json.temperature.current }}"
#

basically I need to pull about 10 sensors out of a json file, but just want to access the file on the disk once

#

so the value_json needs to change to the sensor.smartctl

#

but i;m not sure about the valid syntax

arctic sorrel
#

Probably {{ states('sensor.smartctl').smart_status.passed }} but I'd get that first sensor in and then test in devtools -> Templates

snow zenith
#

ok cool

#

i'll have a look

#

thank you Tinkerer

#

I'm coming back with a harder question soon πŸ˜„

#

hmmm

#

Error: 2020-05-07 20:08:26 ERROR (MainThread) [homeassistant.components.file.sensor] '/smartctl/test.json' is not a whitelisted directory

#

do I just have to put the file in the config directory or something?

snow zenith
#

I tried docker exec -it homeassistant bash and I can read the test.json file

arctic sorrel
#

Or move it, yes

snow zenith
#

ok thank you

#

What would be the optimal location for something like that

#

I can just put it anywhere

arctic sorrel
#

"that" goes in the section shown there πŸ˜‰

#

That section can go anywhere in your config

snow zenith
#

ok

snow zenith
#

hmmm

#
sensor:
  - platform: file
    name: smartctl
    file_path: "/smartctl/test.json"
    value_template: "{{ value_json }}"
#

test.json

{
  "temperature": 25,
  "unit": "Β°C"
}
#

I checked HA can read the test.json file

#

There is no error in the logs

#

But sensor.smartctl is blank

#

It's not unavailable it's just an empty sensor

#

I'll try get rid of value_template line

#

hmm im stuck

#

the problem is the file sensor only reads the last line of the file

#

hmm i think i need to use command_line sensor to read more than one line from a file

arctic sorrel
#

Or have the JSON on a single line

#

jq is great for reformatting JSON

snow zenith
#

i got the sensor to take json on a single line

#

but im having trouble going to the next step of extracting values from the sensor

#

sensor.test = {'test': 'hello world', 'name': 'mike'}

#

but can't figure out how to get hello world out of that

#

because all the examples don't extract json from existing sensors

arctic sorrel
#

{{ states('sensor.test').test }}?

snow zenith
#

can u upload a picture in discord?

#

(screenshot)

#

{{ states('sensor.test').test }} doesn't work

arctic sorrel
#

It has examples there ...

#
{{ states('sensor.test')|to_json }}
``` for example
snow zenith
#

yup i got that going but still can't get a value out

#

^ as per above photo

wary fiber
#

last line try from_json instead of to_json

#

@snow zenith

snow zenith
#

from_json gives error i will show you screenshot

#

actually i got it going now

wary fiber
#

mmm lemme add your file sensor and test

snow zenith
#

its ok im think im almost there

#

it's wierd I think the value_template: "{{ value_json }} doesn't work properly, if i just read the file as text and then turn into json later it works ok

arctic sorrel
#

Sharing code ... as images 😱

snow zenith
#

its show i can share the template output lol

#

actually its the quotes

#
{{ my_testb.test }}

{% set my_testc = states("sensor.test_b")|from_json %}
{{ my_testc.test }}
wary fiber
#

yeah :/ screenshots arent the easiest way for us lol

snow zenith
#

I have to change the quotes because the value_template: {{ value_json }} turns the " into ' then when I try to use 'quotes' in the templating it throws an error.

little gale
#

Can multiple entity_id be listed under... ?

        turn_on:
          - service: switch.turn_on
            entity_id: switch.internal_mount_1tb
snow zenith
#
  - service: switch.turn_on
    entity_id:
      - switch.switch_one
      - switch.switch_two
#

😦

#

" State max length is 255 characters "

#

start again.

arctic sorrel
#

@little gale Yup, same as any other place, separate with commas

little gale
#
  - service: switch.turn_on
    entity_id:
      - switch.switch_one
      - switch.switch_two

this would work as well right?

snow zenith
#

yes both work

arctic sorrel
#

They're the same, just different to humans

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
#

Backtick is the one next to 1️⃣ on the keyboard usually

somber hamlet
#

':-)

#

I'm still struggling with this bolean (MQTT) sensor:

- platform: mqtt
    name: "rob_aanwezig"
    state_topic: "domoticz/out/floorplan/rob"
    value_template: "{{ value_json.nvalue }}"
    payload_on: "1"
    payload_off: "0"

After a restart of HA the sensor is off and I would like it default on. Help is appreciated.

arctic sorrel
#

On restart, does that topic hold the on or off value?

somber hamlet
#

The on value.

arctic sorrel
#

Odd, I'd have expected it to work then 🀷

somber hamlet
#

The topic from Domoticz is only active when the switch is activated.

arctic sorrel
#

Can you have it set the retain flag?

somber hamlet
#

I don't think so.

arctic sorrel
#

Then the best option would be to have an automation that publishes the right payload to the topic when HA starts

somber hamlet
#

Ok, I will look into that. Thanks!

tame carbon
#

Can anyone sanity check this template, please?

silent barnBOT
#

Please don't say I have an error or describe an error. Share the whole actual error message so we can help you.

tame carbon
#

bad indentation of a mapping entry at line 55, column 25:
friendly_name: 'NΓ€chstes Startdatum'

arctic sorrel
#

That's not the problem πŸ˜‰

#

Line 10

#

That is where the typo is

tame carbon
#

Missing `?

arctic sorrel
#

}'

#

The statement isn't complete

tame carbon
#

Perfect, thanks!

#

No idea how you spotted that so quickly

arctic sorrel
wary fiber
#

anyone using rhasspy here ?

arctic sorrel
#

Pasted it in there, saw the error. Stripped out the second platform block, saw the error more clearly πŸ˜„

tame carbon
#

@arctic sorrel nice - thanks for the hint!

arctic sorrel
#

No worries

wary fiber
#

well it s a script_intent :p @arctic sorrel

arctic sorrel
#

The thing you named is a voice assistant πŸ˜‰

wary fiber
#

hehe oki πŸ™‚

arctic sorrel
#

Maybe you were planning on asking a template related question?

wary fiber
#

yup dont know how to get the siteId value from the intent in my template

silent barnBOT
arctic sorrel
#

Why don't you share all the information you have, and then maybe somebody will be able to help πŸ˜‰

wary fiber
#

pasting πŸ˜‰

#

i included the mqtt result

#

i just want ( for testing ) a persistent notification with the siteId name

#

but the value is always empty

#

😒

arctic sorrel
#

Patience πŸ˜‰

#

Somebody who can help will be along, eventually, and if not you can always post on the forum

wary fiber
#

yup πŸ™‚

median vale
#

i feel like i'm doing just like the documentation examples. they are using temperature i'm using power.

wary fiber
#

what are you trying to do ?

median vale
#

i want google to tell me the consumption when i call this script

arctic sorrel
#

Where is data_template?

silent barnBOT
arctic sorrel
#
test1:
  alias: test1
  sequence:
  - data_template:
      message: "{{ state('sensor.machine_a_laver') }}"
    entity_id: all
    service: tts.google_translate_say
#

Important Template Rules

  1. You must use data_template in place of data when using templates in the data section of a service call.
median vale
wary fiber
#

@arctic sorrelbtw i posted about my problem on the forum 3 days ago ... still no anwser 😦

arctic sorrel
#

🀷

#

And you're tagging me to tell me that because ?

#

I have no magic wand to force people to help you

#

People give up their time for free to help

wary fiber
#

i know ... but maybe you know someone lol

#

yeah i know

arctic sorrel
#

I know many people...

#

If you read and followed the sticky post on the forum, you've done all the right things there

#

Tagging folks to nag/demand help just leads to you being blocked or banned πŸ˜‰

wary fiber
#

yeah guess so

arctic sorrel
median vale
#

thank god it is working

#

thank you for the support

wary fiber
#

yup i ve read it ... tho there s so little infos about intents handling :/

arctic sorrel
#

Yeah, that post is about how to ask a good question

wary fiber
#

and searching :p

#

sorry english is not my native language sometime i have difficulties to be clear

amber elbow
#

Could you please suggest me how to debug this error `Error doing job: Exception in callback async_track_state_change.<locals>.state_change_listener(<Event state_...480144+02:00>>) at /usr/src/homeassistant/homeassistant/helpers/event.py:81
Traceback (most recent call last):
File "<template>", line 1, in top-level template code
TypeError: '>' not supported between instances of 'NoneType' and 'int' . ?

wary fiber
#

i m kinda new to homeassistant but i 'd say one object you are trying to use doesn t exist

#

or you are not comparing the same type of data

#

e.g. "20Β°C" and "20"

amber elbow
#

I've a lot of automations and scripts. I'm trying to understand if and how I can narrow the debugging. I wish I had catch this error sooner 😦

buoyant pine
#

does this happen on startup by any chance?

stray topaz
#

Let's say I want something like this:

entities:
  - data_template:
      message: "{{ state('battery_level') }}"
    entity_id: "all"

But this doesn't work, what am I doing wrong?

buoyant pine
#

what is the context for this?

stray topaz
#

I'm trying to get a custom:battery-state-card with all battery_level states on it. So I want the list of entities to be populated automagicly πŸ™‚

buoyant pine
stray topaz
#

Sorry, to be rude, but how is frontend going to answer this? Because I was just send to this channel...

arctic sorrel
#

You can't do that with a template

#

One whole card supports that, the auto-entities custom card

stray topaz
#

Ok, so, let's say I want to create a group with all battery_level entities. How would I go and do that?

arctic sorrel
#

Well, you can't use that to add them to a card

#

If you want to create a group, you create one with all the entities listed - again, no templates

stray topaz
#

Ok, I'm kinda surprised about this. Not that it isn't possible with templates, but more that the "filters" like with "exclude / include" with some integrations isn't widely added to things like this. Would that be something to create a feature request for? Would save a lot of typing for a lot of people, and there is the benefit of it being self populated when adding entities to HA.

arctic sorrel
#

Sure, you can create a feature request on the forum

#

Anybody can πŸ˜‰

stray topaz
#

Yeah, I know. But do you, as a developer and more acquainted with the HA core, think it is a viable feature? Or would it give to much overhead to the system?

buoyant pine
#

Tinkerer

Developer
pick one

arctic sorrel
stray topaz
#

Assumption is the mother of all ...

arctic sorrel
#

My Python skills are ... rusty. I think it's been a decade since I last touched Python, maybe more

#

There's no harm in opening a feature request

thorny snow
#

I touch mine several times a day

stray topaz
#

Ok ok, I'l do that. πŸ˜€

thorny snow
#

WHOA there.. only I do that without invitation

stray topaz
#

@thorny snow, I'm not following... Sorry I'm autistic (really).

thorny snow
#

Haha.. just making a joke as if you were talking to me, and I knew you weren't

stray topaz
#

I touch mine several times a day
@thorny snow Ah, now I get it.... Sorry... Slow to this. Obviously.
Have fun then! πŸ˜†

thorny snow
#

hahaha

snow zenith
#
automation:
  - alias: "sda"
    trigger:
      platform: states
      entity_id: smartctl_sda
    action:
      service: script.turn_on
      data_template: >-
        {% if is_state('sensor.smartctl_sda_json','0') %}
          entity_id: script.sda
        {% else %}
          entity_id: script.do_nothing
        {% endif %}
#

Does anyone see the problem with that it gives config invalid error

#

Invalid config for [automation]: Invalid platform specified @ data['trigger'][0]. Got None
expected a dictionary for dictionary value @ data['action'][0]['data_template']. Got None. (See ?, line ?)

thorny snow
#

else_if?

snow zenith
#

thanks

#

silly me!

thorny snow
#

no, that's a guess

snow zenith
#

actually thats not a mistake

thorny snow
#

did it work?

snow zenith
#
        {% if is_state('sensor.smartctl_sda_json','0') %}
          entity_id: script.sda
        {% else %}
          entity_id: script.do_nothing
        {% endif %}

works in template editor

thorny snow
#

but wait, why does your sensor name have json in it?

#

is that a template?

snow zenith
#

yes

thorny snow
#

ahh

snow zenith
#

actually no

#

thats just an entity_id

#

i could try change that to something else

#

and see if it works

#

like if 1 == 2

thorny snow
#

ok, curious... why does it have json in the name? I've never seen that as a default entity_id

snow zenith
#

its one i created from reading a json text file

thorny snow
#

so yes, it's a template

snow zenith
#
sensor:
  - platform: command_line
    name: smartctl_sda_json
    command: "/bin/cat /config/smartctl/sda.json"
    value_template: "{{ value_json.smartctl.exit_status }}"
    json_attributes:
      - smartctl
      - smart_status
      - ata_smart_attributes
      - power_on_time
      - power_cycle_count
      - temperature
    scan_interval: 10
thorny snow
#

value_template: "{{ value_json.smartctl.exit_status }}"

#

template

#

just curious

snow zenith
#
automation:
  - alias: "sda"
    trigger:
      platform: states
      entity_id: smartctl_sda
    action:
      service: script.turn_on
      data_template: >-
        {% if '1' == '2' %}
          entity_id: script.sda
        {% else %}
          entity_id: script.do_nothing
        {% endif %}

^ that is invalid config as well

#

must be a space_bar or something causing an error

thorny snow
#

it works for me

#

I get do_nothing

#

and sda for 1==1

#

did you figure it out?

snow zenith
#

yes

#

look at line # 5

#

entity_id: smartctl_sda

#

should be entity_id: sensor.smartctl_sda

thorny snow
#

true LOL

snow zenith
#

god damn

thorny snow
#

I am terrible at this

snow zenith
#

im spending forever trying to make the hdd sensor that tracks all my HDDs (i have 15)

thorny snow
#

does anione know how to make a template for a light brightness slider to be converted to a fan speed slider?

#

I receive the following messages from the device Dimmer2IS0

#

and need to send Dimmer1:{dim percentage 0-99} -->> dim dimmer one

snow zenith
#

give us the value from the light template and then what you need it to look like for a fan template

thorny snow
#

what are you actually trying to accomplaish with this?

#

well i add a light entitie direct in yaml

snow zenith
#

i assume it's a custom card that works for lights but not fans?

thorny snow
#

oh, you don't like the low med high off card?

snow zenith
#

or maybe controlling a fan with a light dimmer switch?

thorny snow
#

well, that's bad

#

well i need the dimming slider as mandatory. is to be used in a extractor to a grow room eheheh and need to be set by % in order so i can maintain oerfect temps

#

yes

#

I use a centrifugal in dimmer1 and a inline fan in dimmer 2

#

so a regular fan controller won't do becuase you need it to go lower than low?

#

It does. i have regular analogue dimmers and does the job

#

this hack armtronix dimmer copy does also.

#

well, tell HA it's a light

#

it doesn't know the differenct if it's just a dimmer

#

Just name it fan

#

In on off i can do it with no problem but i need to have the capabilitie to change dimming values from ha

snow zenith
#

and use a fan icon

thorny snow
#

yes ive done that allready

#

Ooops, and fan icon πŸ˜„

snow zenith
#

so what part doesn't work?

thorny snow
#

so use brightness_pct to map your value.. easy peasy

snow zenith
#

your not asking a specific enough question πŸ˜„

thorny snow
#

look the switch/fan is working ok in the mather of on and off but i want to put a slider to control brightness/fan speed for it. The Mqtt message that I have to send is Dimmer1:{dim percentage 0-99} -->> dim dimmer one

#

I see.. ok

#

Now i do not know how to make a slider that send message

#

make an input slider

#

do you need the code i have now?

#

map input slider to your mqtt

#

1 sec

#
light:
  - platform: mqtt
    name: "DIMMER1"
    command_topic: "testesub"
    payload_on: "R13_ON"
    payload_off: "R13_OFF"
    optimistic: true
    qos: 0
    retain: true
#

i have the code already made.. gimme a sec to find it

#

the payload that ive receive is Dimmer1IS0 when off and Dimmer1IS+0 when on. but the command R13_ON that is dimmer on puts the dimming value at 100% every time.
I assume that i have to template the final part of that sentence in order to have also sensor if the light is on.

#

thanks im just giving ideias

#

Like if Dimmer1IS0 ZERO show light off, if more than 0 then show light on icon

#

because if i used the switch instead of light it just goes on off position after a few seconds. because the message i have put on the state only knows zero and 100.

silent barnBOT
thorny snow
#

DAMMIT

#

sorry

#

it happens to me all the times

#

need to set the min speed to - also

#

"0"

#

did you get that?

#

im reading the code

#

just a sec

#

hide entity needs to go also

#

you can do a slider also, I just did a number

#

will paste in the config and restart the server to see the changes.

#

will give reply of it

#

πŸ™‚

#

make the fixes I said

#

min 0

#

and hide entitiy = delete

#

that part sorry i do not understand

#

the entitie i have now you mean?

#

delete this line: " hide_entity: false"

#

ahh ok got it

#

now have 3 new entities, but need to make slider based on the number right?

#

sorry im kind of dumb in programming

#

humm the slider goes on his own to 0 and does not control the dimmer

#

no, the mqtt controls the dimmer

#

I used the topic you gave

#

but you can make that an input_silder

#

the topic i gave is the right on. but the payload change

#

will send the complete payload for you to see

#

is the fan actually listening on that topic though?

#

and i receive a message in testepub with Dimmer1IS(0~99)

#

Ok, your on/off already works?

#

yes

#

i have the thing in my front next to the computer

#

ok, 1 sec

#

if i click the fan icon it does turn on and off but only 0% and 99%

#

did you add the input_number.fan_speed_pct to a card?

#

it should be a slider by default

#

it is but does not control the dimmer

#

cool there you go

#

not yet... 1 sec

#

the command topic is not the same as the reply from the dimmer

#

try this for the payload

#

payload: '"Dimmer1":{{ trigger.to_state.state | int }}'

#

removing the outer squiggles

#

squiggles?

#

LOL the "{"

#

ahh. non english native

#

I could tell, it's ok

#

payload: '"Dimmer1":{{ trigger.to_state.state | int '

#

this ?

#

payload: 'Dimmer1:{{ trigger.to_state.state | int }}'

buoyant pine
#

I believe the word you are looking for is braces

thorny snow
#

squiggles dammit

#

heheh

#

so what do YOU see wrong with the template I gave?

#

I know you can fix it

#

well is rebooting.

#

ok, that only sets the fan, not the slider.. so we'll fix that when the tx part works

#

well

#

good and bad news

#

it didn't blow up is good news

#

if i track the slider it does turn on but goes off on is own

#

ehehehe

#

the slider goes back off? yeah.. that's expected still

#

we just want to make the fan speed work first

#

but now it seems controlling it

#

will try the button

#

turn on and off on the button does not affect the slidder

#

it turns on and off but no feedback on the slider

#

the slider isn't going to work yet

#

ok, see the 2 automations?

#

ahh ok. like ive said is too much sand for my truck

#

no, it's not.. it's just all new

#

but with your kind help im getting there

#

it'll be your turn to help someone else soon

#

so how do you know the fan speed?

#

i receive on the topic: testepub the following message: Dimmer1IS0 or Dimmer1IS20 etc

#

you can make an automation to set the input slider to 0 when you hit the off button

#

is that the same example you gave earlier?

#

yap

#

the same topic??

#

i have a publish topic and a subscribe one

#

there are not the same

#

so the RX msg automation needs to listen to the pub topic so it can listen for speed

#

what's that topic

#

i receive info in testepub

#

and send commands in testesub

#
  • alias: Fan Speed RX msg
    trigger:
    platform: mqtt
    topic: 'testepub'
#

just change the topic

#

well i see now that the names i choose are misleading no?

#

restarts and restarts are a pain in the ass

#

no change mate

#

I know, I need to fix the value

#

so it should look like "Dimmer1:{45}"?

#

from mqttfx

#

you realize you can listen to mqtt from inside HA?

#

and publish too I think

#

it's difficult to see those pics

#

yes. but was allready instaled in the mac. now i know

#

why is the data "214"

#

oh... sequence

#

I can't see what that says.. Dimmer1???

#

Dimmer1IS0

#

dimmer1 is 0

#

but writen as the first sentence i put

#

Dimmer1IS0 !!

#

is that the dimmer name?

#

it looks like that's Dimmer1 I S O

#

no no spaces

#

is that the brightness value somehow??

#

yes

#

ISO?

#

that last number goes from 0-100 it may be handled like brightness

#

IS(zero)

#

OK..... so... DIMMER1 Intensity "50"

#

OH... IS ZERO

#

is Dimmer1IS50

#

WOW... ok... this changes things because now you have to split the Dimmer1IS away from the number... 1 min

#

thanks mate

#

and after that i will be copying over the code because i have a dual channel dimmer for extraction and intraction on the grow. exaust hot air and intake of cold air

#

Yeah, Dimmer2

#

dont know if where you are i can say what i grow eheh

#

I am well aware when people avoid saying

#

πŸ˜„

#

well im not a dd. just a user that likes growing the best he can for his own happiness

#

do you use meters or feet?

#

is a 1mt1mt2mt height grow

#

is very small

#

it's not legal here, just "decriminalized"

#

here to, im in portugal

#

that hasn't changed much though

#

I lived in Rota for 2 years.. stationed there back in 97-99

#

but now people is starting to make such a problem, as a mater of fact is now plans for legalization but some bigpharma does not want the self growing

#

is like going to their pockets

#

yup

#

but im not paying like gold for some bad quality stuff when i grow biologically

#

no quems only bio ferts

#

im giving you so much work just for a bit of code..... 😦

#

and after we put the code right can I refer you on that portuguese forum i told you. Im not the brain behind so I think its good to give the right to the ones who own them

#

Ok, try this: payload: '{{value_json.Dimmer1[-2:]}}'

#

in the RX msg automation

#

Yeah, I don't have a source problem πŸ˜„

#

change on Fan Speed RX msg right?

#

yes

#

if you can listen in HA to topic # and let me see the speed change messages, that would be better

#

I feel like we aren't using the right json or topics, from what I've seen

#

payload is only on tx

#

on rx i only have value

#

how can i assist you with that?

#

teamviers

#

?

#

i clicked the phisical button a couple of times for you to see changes

#

if i made it with the HA button only shows the 0 or 100

#

this way you see dimming

#

Oh.. so there's no json, just the data

#

Ok, 1 min

#

sure. im not paying so i dont have right to expedite no one πŸ™‚

#

LOL

snow zenith
#

omg

#

missing a comma

thorny snow
#

I just minimize this window

snow zenith
#

😩 problem solved

#

πŸ˜†

thorny snow
#

is a saying that we say in portugal

#

copy this?

#

1 sec.. that is wrong

#

this might work

#
  • alias: Fan Speed RX msg
    trigger:
    platform: mqtt
    topic: 'testepub'
    action:
    service: input_number.set_value
    data_template:
    entity_id: input_number.fan_speed_pct
    value: '{{trigger.payload[-2:]}}'
#

will test

#

but it only senses 2 digit numbers right now

#

10-99

#

need to figure oout how to regex the number off the end

#

because you get a 1, and not 01, correct?

#

yes. but from 10-100 be good. 10% the fan motors does not even rotate

#

so you can make the input slider steps to 10

#

sorry 99

#

I understood

#

will see whats the minimum for each fan

#

the inline the minimum is arround 50% the big extractor I havent test that but since is the main temperature controller will be normally arround 60~70% (less is better, less noise!)

#

now it works, but how can i make the slider goes from 10 steps and the light icon from the button show on every time that is not 0?

#

the input slider you change the "steps"

#

how does that button even work?? Is it an mqtt switch?

#

can i use inicial as the normal sweet spot in terms of %

#

because the dimmer have a % control and a ON/OFF one

#

I see.. the mqtt light

#

when i set swith it goes off on his own and thats the way i found working

#

yeah I set the initial to 0 to prevent accidental movement. Habit.

#

if i know that 50% is the regular value it will start from there and only with human intervention will be changed

#

so when you turn it on, the R13_ON.. the mqtt light should see that and work properly.. but when you set it to 0... tha'ts not the same as R13_OFF

#

because with switch i was not abble to parse the message to have a feedback since the receiving message is the same of the % dimmer. just the command i send is diferenr

#

so the light stays on

#

no. it goes to 0 the same

#

so the fan shuts off, but the button is on

#

slider or button the message i receive is Dimmer1IS0

#

yeah, I don't know how to solve that

#

but messing with slider does not affect the button and vice versa

#

right

#

when the fan gets a ON, what does it do? Max speed or last set speeed?

#

ON means 99%

#

OFF 0%

#

full speed

#

but i would like the last set speed

#

and after that i can run a simple automation based on the temp and the hours that the HPS lamp is working and heating

#

make a template for 0 = off and 0 < ON

#

hummm can help out......

#

and how can i save the last set speeed

#

I will use the slider for ajustment and the button for on/off sensing

#

now when i click the button the slider goes to 99 but no 0 when i click again

#

to turn off

#

Oh... DERP..

#

1sec

#

is there a way of the ON button recall the last set speed instead of the ON-99 OFF-0 that i put?

#

light:

  • platform: mqtt
    name: "DIMMER1"
    command_topic: "testesub"
    payload_on: "R13_ON"
    payload_off: "DIMMER1IS0"
    optimistic: true
    qos: 0
    retain: true
#

i was about to put the code but is there a way of change "payload_on: "R13_ON"" for a slider last set speeed instead?

#

No, I think you'll have to modify the TX automation to use RM_ON as a trigger, then fire off a set mqtt DIMMER1IS(input_select)

#

make sense?

#

chinese

#

make sense now??? hahah

#

haa automate like the 3d printer fan

#

full blip at start then dimm

#

yeah, well...

#

blink right then πŸ˜„

#

is a term used by fw on marlin

#

eheheh

#

blip!

#

but the fan works though???

#

yes

#

ok.. let me look at the TX

#

I am eyeballing my 3d printer

#

it just changes the slider to 99.

#

Ok, paste back what you have

#

but when i turn off the slider remains at 99, but dimmer goes 0

#

the fan stops

#

ok, fix:

#

light:

#

payload_off: "DIMMER1IS0"

#

for DIMMER1

#

testing

#

so if the fan is off, and you send the %, what happens?

#

it starts again

#

at the % i set in slider

#

at that spedd or at 99? same as ON?

#

but im restarting now

#

so wee need to find out how to set the payload_on to be the DIMMER1IS%

#

now when i click off it stays on at 99%

#

oh damn

#

should it be changed in state_topic: instead

#

if the state is 0 then is off

#

I hoped when you clicked off, it would send Dimmer1IS0, but the slider needs to see 2 digits.. 10 -99

#

back to square one again......

#

well, that's a shitty dimmer

#

diy

#

present comapny excepted though LOL

#

1 atmega328p 1 weemos and robotdin 2ch

#

why would you choose that payload.. it's hard to work with

#

i cant choose i was following instrctions

#

i was not the programmer

#

so far you've been giving them

#

πŸ˜›

#

i made a armtronix dimmer with parts i have here

#

basicly i just copy the engennering

#

yes but mine is a dual and is not that finished product,. is more like a breadboard with 2 mcus and a dimmer ac

#

but yes same principle

#

controlling 220VAC

#

yep

#

so you have the actual project? there may be a much simpler way to skin this cat

#

yes

#

what part do you need the ESP or the atmega?

#

whatever is forming the mqtt message, so I gess the esp

#

this that we are doing is a fork right?

#

when we change stuff from other people github codes?

#

well yes

#

normally a fork is to republish also

#

if you think of the code like a tree

#

branches hummm get it

#

this is on an ESP8266??????????

#

wemmos

#

d1 mini

#

fuck i messed

#

same thing.. NOT the atmega.. so MEGs of memory.. why choose to do this withthe mqtt?

#

horrible design choices... anyway

#

yeah, I am reading that

#

I can rewrite the ESP side, but I am not touching the atmega.. we can send it back the serial it expects and the mqtt can be done easier.

#

sure

#

i get πŸ™‚

#

this is what make the obligation to go to 100?

#

else if (msgString.substring(0, 6) == "R14_ON" || msgString.substring(0, 11) == "Dimmer2:100")

#

under the hood, the ESP is doing what we would do in HA if (msgString.substring(0, 6) == "R13_ON" || msgString.substring(0, 11) == "Dimmer1:100")
{
Serial.println("Dimmer1:99");
#ifdef Dimmer_State
DimmerState1 = "99";
saveConfig() ? Serial.println("Dim val saved sucessfully.") : Serial.println("Dim val not saved");;
#endif //Dimmer_State
}

#

so it's already using the data internally and we need to unmuck it

#

just use the r14_on to trigger the dimmer100

#

right?

#

if im reading correcty is what is made in the original code

#

i know almost nothing about reading but common sensr

#

no, we don't need to use R14_OFF or ON

#

we can make it whatever we want

#

it's mostly common sense once you decode the language

#

DM me so we can move out of here since this isn't template stuff anymore

#

sorry i did not understand

#

IM me

#

DM/IM

#

got it

snow zenith
#

wondering if someone can have a look at this template data by copy + pasting it into the home assistant template tool
https://pastebin.com/kwJAq3kd

#
{% set my_json = [... see the pastebin above ...] %}

Find the raw value for id 5
eg. ID{{ my_json[3].id }} = {{ my_json[3].raw.value }}

{% for i in range(0, 30) %}
# if my_json[i].id == 5 then output my_json[i].raw.value
{% endfor %}
warm isle
#

How was the trigger to state template again?

  - data:
      message: 'input_boolean.bed_ads_1x changed his status to {{ trigger.to_state}} '
    service: notify.me
snow zenith
#

It's basically this i think, but the code has syntax errors that i can't figure out how to fix

{% for i in my_json %}
  {% if my_json[{{ loop.index }}].id|int == 5 %}
    my_json[{{ loop.index }}].raw.value
  {% endif %}
{% endfor %
warm isle
#

lol - how you get this json into HA? I guess thats way more then 255 characters

jagged obsidian
#

does HA have a limit on json size?

warm isle
#

sensors have it

snow zenith
#

you break the json into sensor attributes when you load it in

warm isle
#

How you get the json in the first place

snow zenith
#

smartctl --json

warm isle
#

so a file?

snow zenith
#
sensor:
  - platform: command_line
    name: smartctl_sdc_json
    command: "/bin/cat /config/smartctl/sdc.json"
    value_template: "{{ value_json.smartctl.exit_status }}"
    json_attributes:
      - smartctl
      - device
      - model_name
      - user_capacity
      - smart_status
      - ata_smart_attributes
      - power_on_time
      - power_cycle_count
      - temperature
warm isle
#

ah neat

snow zenith
#

and then i parse them and store them in mqtt

warm isle
#

well when you go over the jq route you have a easy live πŸ˜›
`
$ cat json | jq .[].raw.value | jq -cs '{next: .[0], seccond: .[1], third: .[2], fourth: .[3]}'

{"next":2,"seccond":9358,"third":16495,"fourth":0} `

snow zenith
#

jq?

warm isle
#

json query

#

Its built in into HA

snow zenith
#

$single($, function($v) { $v.id = 5 }).raw.value

#

except i don't know how to put that into home assistant template, but I'll try read up on jq then

warm isle
#

I also dont πŸ˜„

snow zenith
#

ok

#

i'll try that

#

actually my file is bigger if i use cat

warm isle
#

JQ filters

#

the output of the sensor will only be the number

snow zenith
warm isle
#

ah! - wich part youre intrested?

snow zenith
#

ata_smart_attributes -> table

#

table:
id 5 -> raw_value
id187 -> raw_value (if exist)
id187 -> raw_value (if exist)
id 197 -> raw_value
id 198 -> raw_value

warm isle
#

and use then the -cs flag to create sensors out of the array

snow zenith
#

that won't work

#

because not every hdd has the same table order

silent barnBOT
warm isle
#

the -cs flag can also create you more complex json afterwards

#

| jq '.data.monitors[] | { name: .lines[].name ,stop: .locationStop.properties.title, towards: .lines[].towards ,data: .lines[].departures.departure[].departureTime.countdown, trafficjam: .lines[].trafficjam }'| jq -cs '{name: .[0].name, stop: .[0].stop, towards: .[0].towards, next: .[0].data, seccond: .[1].data, third: .[2].data, fourth: .[3].data, trafficjam_0: .[0].trafficjam, trafficjam_1: .[1].trafficjam }'"

snow zenith
#

example

[
  {
    "id": 1,
    "name": "Arthur",
    "age": "21"
  },
  {
    "id": 2,
    "name": "Richard",
    "age": "32"
  }
]

JQ -> Find the name of the person who is 32 years old

warm isle
#

cat json | jq '.[] | select(.age=="32")'

snow zenith
#

someone recons i should use regex to find what i want

#

ohh

#

i will try above

warm isle
#

food time - good luck

snow zenith
#

actually maybe i need to use regex

#

inside the template

snow zenith
#

Almost won

#

does anyone know how to make variables exist outside of a for loop

#
{% set var = "unknown" %}

{% for i in my_json %}
    {%- if i.id == 5 %}
      {% set var = i.raw.value %}
    {% endif -%}
{% endfor %}

Answer is {{ var }}
#

{{ var }} works inside the loop, but it loses it's value outside of the loop

#

but its complicated

#
{% set ns = namespace(found=false) %}
{% for i in my_json %}
    {%- if i.id == 5 %}
      {% set ns.found = true %}
      "{{ var }}"
    {% else %}
    {% endif -%}
{% endfor %}
{% if not ns.found %} "unknown" {% endif %}
#

^ solved.

warm isle
#

nice - I came up with this now ```
cat json | jq '.ata_smart_attributes.table[] | { name: select(.id==5).name, id: select(.id==5).id, value: select(.id==5).raw.value}'
{
"name": "Reallocated_Sector_Ct",
"id": 5,
"value": 0
}

warm isle
#
| jq '.ata_smart_attributes.table[]' | jq -c ' [.name, .id, .raw.value] '
["Raw_Read_Error_Rate",1,2]
["Spin_Up_Time",3,9358]
["Start_Stop_Count",4,16495]
["Reallocated_Sector_Ct",5,0]
["Seek_Error_Rate",7,0]
["Power_On_Hours",9,47777]
["Spin_Retry_Count",10,0]
["Calibration_Retry_Count",11,0]
["Power_Cycle_Count",12,7462]
["Power-Off_Retract_Count",192,602]
["Load_Cycle_Count",193,119393]
["Temperature_Celsius",194,32]
["Reallocated_Event_Count",196,0]
["Current_Pending_Sector",197,0]
["Offline_Uncorrectable",198,0]
["UDMA_CRC_Error_Count",199,0]
["Multi_Zone_Error_Rate",200,0]

That also worked

warm isle
#

Only thing I would now like to do is that it is in another array
like this curl -s https://pastebin.com/raw/77T3eCBh | jq '.ata_smart_attributes.table[]' | jq -c '{.id, {name: .name, value: .raw.value}}' But apperantly quoting issues?

shell lynx
#

Posting here because I was in the middle of troubleshooting a json template for parsing an external api, when suddenly the sensor just no longer shows up at all. Stripped the config to everything but the basics for the sensor, but it won’t come back. No errors in the log. Has anyone seen anything like this?

warm isle
#

@shell lynx tryed a curl on the api endpoint?

shell lynx
#

Sorry, I’m kinda new to this. Do you mean trying a curl on the endpoint to make sure data is being given? If so, yes and the data is coming through. Just weird that the sensor stopped showing. Will try to revert to the last backup and see what happens.

warm isle
#

thats right - just checking if ha can actually get data, API's can also change with a update
or maybe you renamed your file to something.yml

earnest arrow
#

given a json output in mqtt of { "current-flow" : 10 } how do I access that in a template? It looks like it's taking the - in current-flow and trying to subtract it? value_template: "{{ value_json.current-flow / 10 }}" When I use the template tester under developer tools it tells me Error rendering template: UndefinedError: 'flow' is undefined

wary fiber
#

found the solution to my problem !!!!!!!!!!!!!

#

if you guys ever needs the siteId in rasspy intents

#

use {{ site_id }} it s a special slot

dreamy sinew
#

{{value_json['current-flow']}} @earnest arrow

warm isle
#

How was the trigger to state template again?

  - data:
      message: 'input_boolean.bed_ads_1x changed his status to {{ trigger.to_state}} '
    service: notify.me
dreamy sinew
#

rule 1 of templating

earnest arrow
#

thanks. shows how much I use templates 🀣

dreamy sinew
#

haha rule 1 is for @warm isle

warm isle
#

?? Check your qoutes?

#

Templates can be tested via devtools > Templates

#

New members: Welcome?

#

aah - finaly found it NukeFacePalm
Always checked the docks for... something

#

{{ trigger.to_state.state }}

queen meteor
#

@warm isle you also need data_template

warm isle
#

ah! thx!! - been so long out of the HA configuration that i forgot that

nimble hinge
#

Hey guys is there anyway to test templates outside of the dev tools

#

I see hass-cli template but I don't know it this works? I tried feeding a file to it and see if it rendered something, but nothing

dreamy sinew
#

why?

shell lynx
#

Just checking/testing. The following is in my sensors.yaml and noting is created. Am I off somewhere? - platform: rest name: simple_test resource: https://jsonplaceholder.typicode.com/posts/42

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

buoyant pine
#

anything in the logs? did you run a config check and restart home assistant?

shell lynx
#

yes, config check is clean, and nothing in the logs. This is just a sample. I had a similar one that was working yesterday, and it just stopped.

buoyant pine
#

do you see it at developer tools > states?

shell lynx
#

no, that's where i normally look for it. Yesterday, it was there just fine. I restored from a backup from yesterday (just before I added the code), re added, and still nothing

#

got it, thanks for that. Wasn't sure where to post.

#

I posted here because i was trying to figure out the template for parsing when it all went away

buoyant pine
#

i've gotcha

shell lynx
#

πŸ‘

thorny snow
#

Does anyone know if input booleans will keep their state over a HA restart?

buoyant pine
#

By default, yes

queen meteor
#

not if you have initial: setting. then it will default to that state.

#

If you want the input_boolean to maintain and restore state, remove initial: attribute where you define it.

thorny snow
#

that is wierd, i have an input boolean that has no initial setting. I set an automation to turn on that boolean when HA shuts down, so I have an indicator if I had a clean shutdown. Unfortunately the boolean will not be turned on after I restart HA.

queen meteor
#

@nimble hinge In general, you can write and test template code in the command line. without hass-cli but you may not have access to the hass objects, states. try something like```
$ python3

from jinja2 import Template

s = "{% for element in elements %}{{loop.index}} {% endfor %}"
Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4

Template("{{ var }}").render(var=25)
'25'

Template("{{ var }}").render(var="hello world!")
'hello world!'

shell lynx
#

I'm getting an error that sensor.lenfant_trains is undefined

arctic sorrel
#

Does sensor.lenfant_trains exist in devtools -> States?

#

Does it have an attribute Trains (not trains)?

shell lynx
#

it does not (thought it did) exist it states

arctic sorrel
#

There you go...

shell lynx
#

thanks!

#

{"Trains":[{"Car":"6","Destination":"SilvrSpg","DestinationCode":"B08","DestinationName":"Silver Spring","Group":"1","Line":"RD","LocationCode":"A01","LocationName":"Metro Center","Min":"3"} that's the payload

queen meteor
#

@shell lynx That's not a valid JSON payload. You are missing a square bracket for the array and the closing curly brace in the end. This is the valid JSON {"Trains": [{"Car": "6","Destination": "SilvrSpg","DestinationCode": "B08","DestinationName": "Silver Spring","Group": "1","Line": "RD","LocationCode": "A01","LocationName": "Metro Center","Min": "3"}]}when I try the following in the template editor, it works: ```
{% set value_json = {"Trains": [{"Car": "6","Destination": "SilvrSpg","DestinationCode": "B08","DestinationName": "Silver Spring","Group": "1","Line": "RD","LocationCode": "A01","LocationName": "Metro Center","Min": "3"}]} %}

{{ value_json.Trains[0] }}

shell lynx
#

ok, thanks. so a template to get "Cars" would look like: ```

  • platform: template
    sensors:
    lenfant_length:
    value_template: '{{ state_attr('sensor.lenfant_trains', 'Trains')[0]["Car"] }}' ``` because i'm getting the 'expected <block end>' error with that
arctic sorrel
#

The JSON you posted was broken

#

If the raw JSON is also broken, that's the problem

shell lynx
#

I think it was just a paste error. I can read the actual jason with value_template: '{{ value_json.Trains[0].Car }}' I guess I just don't understand when to use value_json over state_attr

#

Thanks for your collective help and patience. switching to value_json is going to work.

tropic pawn
#

Is there any way to call in a value of a template into a card's attribute? for example:
cards:

  • entity: sensor.md_srv_media_data_free
    max: [TEMPLATEVALUE]
    min: 0
    type: gauge
    I want the "max" to be the sum of 2 sensor's value, which is done in the template. I'm not sure if this is the best approach, so I'm open for any idea. Thanks
arctic sorrel
#

No, stock cards don't support templates

tropic pawn
#

I see. So I'm guessing there is no way to have a dynamic variable there

arctic sorrel
#

Nope

tropic pawn
#

Okay, ty

#

and how do I call in a template's value into a custom card? πŸ™‚

arctic sorrel
#

That'd be down to the custom card supporting it

silent barnBOT
woeful loom
#

How do I handle a **nested **JSON response from a RESTful sensor.
I want to end up with 4 sensors, duration and risetime each array member.
The only way I seem to be able to get them is by running the REST twice, once with
json_attributes_path: "$.response[0]" and once with
json_attributes_path: "$.response[1]".
This is working well, but I don't want to add to the resource server workload by running two calls when one should do.
Surly I should be able to extract what I want from one REST call.
The REST call works well and returns a response that is an array of two.
The first one, response[0] has two values, duration and risetime.
Obviously the second one, response[1] also has duration and risetime.
I did try to post the REST output but fell foul of the code wall bot - my mistake, never used Discord before.

scenic solstice
#

@woeful loom I think i do that by parsing the rest call sensor with a template sensor to extract out each field i care about

#
  - platform: rest
    name: Frigate Debug
    resource: http://192.168.x.x:5000/debug/stats
    scan_interval: 5
    json_attributes:
      - front
      - coral
    value_template: 'OK'  
#

here's the nesting being handled by the template sensors

#
    sensors:
      front_fps: 
        value_template: '{{ states.sensor.frigate_debug.attributes["front"]["camera_fps"] }}'
        unit_of_measurement: 'FPS'
      front_skipped_fps: 
        value_template: '{{ states.sensor.frigate_debug.attributes["front"]["skipped_fps"] }}'
        unit_of_measurement: 'FPS'
balmy moth
#

could someone assist me in making a template for my d-link swtich to get the watt useage into HA

#

this is what i have so far

#
  platform: template
    current_power_w:
    friendly_name: Drier Power useage"
    value_template: "{{ state_attr('switch.d_link_smart_plug_w215', 'current_power_w')|int }}"
    unit_of_measurement: 'w'```
#

let me know what have buggered ta

buoyant pine
#

@balmy moth indentation is wrong

#

Everything below current_power_w: needs to be indented two spaces

balmy moth
#
  platform: lastfm
    api_key: 
    users:
    - DH4774
  platform: template
    current_power_w:
      friendly_name: Drier Power useage"
      value_template: "{{ state_attr('switch.d_link_smart_plug_w215', 'current_power_w')|int }}"
      unit_of_measurement: 'w'
switch:
  platform: dlink
    use_legacy_protocol: true
    host: 192.168.1.111
    username: admim
    password: x```
#

that?

buoyant pine
#

Oh you need to change platform: to - platform:

balmy moth
#

both?

buoyant pine
#

Yeah

#

Needs to be a list

balmy moth
#

so 2 indents then - followed by platform:

#
  • platform:
#
  - platform: lastfm
      api_key: x
      users:
      - DH4774
  - platform: template
      current_power_w:
        friendly_name: Drier Power useage"
        value_template: "{{ state_attr('switch.d_link_smart_plug_w215', 'current_power_w')|int }}"
        unit_of_measurement: 'w'
switch:
  - platform: dlink
      use_legacy_protocol: true
      host: 192.168.1.111
      username: admim
      password: x```
#
          current_power_w:
                         ^```
#

Everything below current_power_w: needs to be indented two spaces
@buoyant pine odd after doing this it still isnt working

#
  - platform: lastfm
    api_key: x
    users:
      - DH4774
  - platform: template
      current_power_w:
        friendly_name: Drier Power useage"
        value_template: "{{ state_attr('switch.d_link_smart_plug_w215', 'current_power_w')|int }}"
        unit_of_measurement: 'w'
switch:
  - platform: dlink
      use_legacy_protocol: true
      host: 192.168.1.111
      username: admim
      password: x```
buoyant pine
#

indentation is still off and you're missing part of the template sensor config, one sec

balmy moth
#
  - platform: lastfm
    api_key: x
    users:
      - DH4774
  - platform: template
    current_power_w:
      friendly_name: Drier Power useage"
      value_template: "{{ state_attr('switch.d_link_smart_plug_w215', 'current_power_w')|int }}"
      unit_of_measurement: 'w'
switch:
  - platform: dlink
    use_legacy_protocol: true
    host: 192.168.1.111
    username: admim
    password: x```
buoyant pine
#

yeah you fixed the second part but you're still missing sensors: in the template sensor config

#

(didn't see that in your original post)

balmy moth
#

πŸ‘

#

thanks

#

ill try that

#

so uh why do we hate the little green verify icon?

buoyant pine
#

the what?

balmy moth
#

and if it cant be counted on to verify yaml why is it there?

#

the little green tick at top of file editor

buoyant pine
#

i run core only so i don't have addons but i think that just verifies that it's valid YAML, not necessarily that it's a valid config

balmy moth
#

extra keys not allowed @ data['current_power_w']. Got OrderedDict([('friendly_name', 'Drier Power useage"'), ('value_template', "{{ state_attr('switch.d_link_smart_plug_w215', 'current_power_w')|int }}"), ('unit_of_measurement', 'w')]). (See ?, line ?).

#

im this close the throwing the bloody thing in the bin and buying something else

buoyant pine
#

share it again

balmy moth
#
  - platform: lastfm
    api_key: nein
    users:
      - DH4774
  - platform: template
    sensors:
    current_power_w:
      friendly_name: Drier Power useage"
      value_template: "{{ state_attr('switch.d_link_smart_plug_w215', 'current_power_w')|int }}"
      unit_of_measurement: 'w'
switch:
  - platform: dlink
    use_legacy_protocol: true
    host: 192.168.1.111
    username: admim
    password: lolno```
buoyant pine
#

indentation...

#

check what i had again

balmy moth
#

roger

#

ill never be a yaml master, or beat my first yaml gym ever

buoyant pine
#

lol... it'll take time but it'll eventually click

#

one tip. if you have something like

word:
``` anything below that that's related to it will need to be indented two spaces
#

so for example:

  - platform: template
    sensors:
      current_power_w:
        friendly_name: Drier Power useage"
        value_template: "{{ state_attr('switch.d_link_smart_plug_w215', 'current_power_w')|int }}"
        unit_of_measurement: 'w'
#

current_power_w: is related to sensors: so it's indented two spaces

#

just like friendly_name, value_template, and unit_of_measurement are related to sensors:

#

so they are also indented

balmy moth
#

and if it wasnt indented it would be related to - platform?

#

or sensors

buoyant pine
#

i suppose, but that wouldn't be valid

balmy moth
#

last thing how do i give it a icon like a power meter?

buoyant pine
#

are you going to use this in a card in the frontend?

balmy moth
#

yes

buoyant pine
#

you can specify the icon in the card

balmy moth
#

do i need to go into code editor?

buoyant pine
#

you can use the UI card editor

#

if it's a standard card

balmy moth
#

Entities Card Configuration

grand lake
#

hey guys, i'm new to Home assistant and i got some problems... can sb. help me out?

balmy moth
#

@grand lake dont ask to ask, just ask pal πŸ™‚

grand lake
#

i have problems with the config

#

is there a better way to control digital led's?

#

How to setup the config so that everything works? i got mqtt set up and connected, esp running properly - just not the config yet

tropic hill
#

@grand lake try wled firmware

silent barnBOT
arctic sorrel
#

~codewall @woeful loom

silent barnBOT
#

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

woeful loom
#

~codewall @woeful loom
@arctic sorrel I understand about the code wall so I tried to get below the 12 lines or whatever I read was OK. But I just don't know how to explain my question. I see other postings with small blocks of code so is there somewhere else I should be posting or should I not mark it as code? - I've only been on discord a few days an don't feel comfortable upsetting things.

arctic sorrel
#

The problem was the total number of lines you posted in one hit - that's unpleasant for those on mobile/with larger text/smaller screens

#

So, if you're going to most more than a dozen lines, move all the code out to a code share site

woeful loom
#

Thanks for explaining that, I'm not familiar with code sharing sites, I'll try and see what others have done. I'm close to giving up anyway, at my age I'm too old to learn new tricks :-(
@arctic sorrel

arctic sorrel
#

You're never too old πŸ˜‰

#
  json_attributes:
    - next_one # I made this up as array didn't have a label
    - plus_one # # I made this up as array didn't have a label
``` you can't make things up πŸ˜‰
#

Instead try

      iss_duration_test1:
        value_template: '{{ states.sensor.iss_passtimes_test.attributes[1]["duration"]  }}'
      iss_rise_test1:
        value_template: '{{ states.sensor.iss_passtimes_test.attributes[1]["risetime"]  }}'
      iss_duration_test2:
        value_template: '{{ states.sensor.iss_passtimes_test.attributes[2]["duration"]  }}'
      iss_rise_test2:
        value_template: '{{ states.sensor.iss_passtimes_test.attributes[2]["risetime"]  }}'
``` (or maybe `[0]` and `[1]`)
woeful loom
#

68 with conative issues, I used to be Microsoft Certified years back, can't even write a batch file now. Oh that suggestions looks promising. Off to try - I really do appreciate it.

arctic sorrel
#

No worries, and hey, you're trying - that's more than many younger folks πŸ˜‰

scenic solstice
#

Agreed. Good luck and keep at it. It'll click.

woeful loom
#

Thanks guys, it was so obvious using the array index, but it didn't work out, I tried [0] & [1] and also [1] & [2].
I hope this isn't going to code wall, but this is the output of the API call, does it look like it should work?

{
  "message": "success",
  "response": [
    {
      "duration": 557,
      "risetime": 1589066522
    },
    {
      "duration": 647,
      "risetime": 1589072250
    }
  ]
}
#

All four states are "unavailable" 😦

arctic sorrel
#

The sensor should have a bunch of attributes already?

#

But, there, your JSON would require .response[0].duration etc

#

You can test in devtools -> _Templates

woeful loom
#

It's a long story, but in essence, the ISS sensor doesn't work correctly for people in the UK. I spent weeks on it, and lots of others in the UK had the same issue. The sensor would trigger when the ISS was over a completely different continent. The HA MAP would show my home zone in the correct place, it would show the ISS over, let's say, India, and NASA also showed it over India, but the sensor would go true. At other times, the map and NASA would show it over my house, and I could see it with my own eyes, but the sensor would stay false. So I gave up and that is why, my friends, I made the RESTful sensor. It works perfectly, shows me when the next two passes are, how long to wait for the next one, how long before I would lose radio contact and the distance between the ISS and me (ground track of course).
Yes, I use the Templates page all the time, it's been a god-send.
So all this present work (14 days and counting), and the reason I'm here, is to reduce two REST calls to one!
It's not that I just want a solution handed to me, I want to understand how it works.

arctic sorrel
#

Ah, cool πŸ˜„

wary fiber
#

hey all πŸ™‚ i m having trouble with a template ( again )

#
  • service: 'mqtt.publish'
    data:
    payload_template: '{"intentFilter": "Again", "sessionId": {{session_id}}, "customData": {{volume}} }'
    topic: 'hermes/dialogueManager/continueSession'
    retain: true
    • service: 'persistent_notification.create'
      data_template:
      message: '{{session_id}}'
#

the mqtt published is:

#

{"intentFilter": "Again", "sessionId": , "customData": }

#

the variables are not passed :/

#

tryed to escape the first and last {

#

but not working

dreamy sinew
#

Well your first one fails rule 1 of templating

silent barnBOT
wary fiber
#

just made it work hehe thank you πŸ™‚ i did forgot the _template for data

#

data_template instead of data

#

thank you @dreamy sinew

warped hornet
#

Hi. I got this intergration which provides about my houses power usage for the preceding day. I get 24 sensors. One showing usage for each time slot. The sensor got a 'metering date' attribute. I'd like to display this as a graph. What would you recommend for processing the sensors?

#

I had this idea to associate the value with it's attribute (metering date) and not the actual time of storing the data in the database

#

But I'm not sure how to

warped hornet
#

Is it possible to use a variable to construct a sensor name?

#

like

{{ states.sensor.my_sensor_{{ now().hour }} }}
dreamy sinew
#

Possible, depends on where you're using it though

warped hornet
#

as a value_template in a template sensor

dreamy sinew
#

Then it will never update

warped hornet
#

Why not?

#

What can I do, if I want my template sensor to retreive data from a specific sensor, based on a variable?

#

a large if-else statement?

#

Is something like this possible?

value_template: >-
  {%
    {% now().hour == 0 %}
      {{ states.sensor.eloverblik_energy_22_23 }}
    {% now().hour == 1 %}
      {{ states.sensor.eloverblik_energy_22_23 }}
    {% now().hour == 2 %}
     ...
    {% now().hour == 23 %}
      {{ states.sensor.eloverblik_energy_23_24 }}
    {% endif %}
  %}
dreamy sinew
#

Maybe? I'm not sure if that'll work either

inner raft
#

Hey there having some issue with templating:

If I enter:

{{ relative_time(states.input_boolean.washing_machine_full.last_updated) }}
{{ now() }}
{{states.input_boolean.washing_machine_full.last_updated }}

I am getting

21 minutes
2020-05-11 00:21:31.646520+02:00
2020-05-10 21:59:57.682981+00:00

It looks like the first result is minutes from midnight instead of the last_updated
Anyone knows why ?

#

Oh just realize UTC vs local time

#

sorry πŸ˜„

shell lynx
#

What does 'OK' symbolize in value_template: 'OK' ?

formal sable
#

Is this supposed to cause an error?

    - service: light.turn_on
      entity_id:
        - light.kitchen
      data_template:
        brightness: {{255 if states("sensor.time_of_day") == "Evening" else 30 }}
#

the template is valid according to the template editorr

#

otherwise i get an ordereddict invalid key error

candid valve
#

put the entity_id in the data_template

dreamy sinew
#

Need to wrap the template in '

formal sable
#

even if its a number?

#

entity_id needs to be inside data_template? it worked the this way if i hardcoded brightness to 20

#
brightness: "{{255 if states("sensor.time_of_day") == "Evening" else 30 }}"
``` this causes an error
#
    - service: light.turn_on
      data_template:
        entity_id: light.kitchen
        brightness: {{30 if states("sensor.time_of_day") == "Evening" else 255 }}
``` same error
#
    - service: light.turn_on
      entity_id:
        - light.kitchen
      data_template: >
        brightness: 
          {% if is_state('sensor.time_of_day', "Evening") %}20{% else %}100{% endif %}
#

this works but its so verbose

#
    - service: light.turn_on
      entity_id:
        - light.kitchen
      data_template:
        brightness: >
          {% if is_state('sensor.time_of_day', 'Night') %}20{% else %}255{% endif %}
``` this is the only thing that seems to work
#

unless i'm going crazy, thanks babichajacob & phnx πŸ™‚

buoyant pine
#

Will work if you put single quotes on the outside like phnx said

#

"{{ }}" if you have single quotes inside the braces, '{{ }}' if you have double quotes inside the braces (though common convention is the first one)

formal sable
#

oh snap you're right, this worked:

      entity_id:
        - light.kitchen
      data_template:
        brightness: '{{255 if states("sensor.time_of_day") == "Evening" else 255 }}'```
#

thanks πŸ™‚

buoyant pine
#

No prob, single-line templates always need to have quotes on the outside

velvet glen
#

Trying to use the template editor, but not grasping the basics - have a sensor called: sensor.greenhouse_humidity, I can see this has a value in the states tab, I've tried putting : {{sensor.greenhouse_humidity}} in the template editor, but get a 'Error rendering template: Undefined Error: 'sensor' is undefined' error? Can anyone give me a quick pointer?

silent barnBOT
arctic sorrel
#

{{ states('sensor.greenhouse_humidity') }}

velvet glen
#

Ah useful - thanks! I'd read that page, but missed the part in highlights..... πŸ€¦β€β™‚οΈ

blissful scaffold
#

Hi All, I am using a value_template in an automation to change my light colors based on the holiday, how can I put and and in this. {% set n = now() %} {{ n.month == 5}} so that I can do it for more than one month? like lets say I wanted May and July to be in the same automation

queen meteor
#

Use and

blissful scaffold
#

its that easy?

#

can I use multiple ands in the same line like {{ n.month == 5 and n.month == 7 and n.month == 8}}

queen meteor
#

Yup

blissful scaffold
#

perfect, thank you. I didnt know of a way to force HA to check for that month to see if it works.

queen meteor
#

You can simply use now().month. No need to set variable.

blissful scaffold
#

oh, well that would have been a little easier.

velvet glen
#

Can anyone point to documentation on the use of speech marks, quotes etc in yaml files? I can see there's some sort of convention and would like to understand why you add them, why you don't, why you use doubles, singles etc this works, but I don't know why...!

#

where: '"device" = ''Greenhouse'''
measurement: '"BrynyneuaddSensors"'
value_template: {{ states('sensor.greenhouse_humidity') | round(1) }}
field: Temperature

#

Eg why speech marks AND quotes around the measurement, why do some examples have single quotes around the value_template and others don't - why no quotes needed around 'temperature' etc!

queen meteor
#

@velvet glen it has nothing to do with Home Assistant. It is how YAML is structured. It is usually best practice to surround values with quotes. If the value has quotes in it, you need to escape those. When you use in-line templates, you are required to put the code in quotes - like ```
value_template: "{{ states('sensor.greenhouse_humidity') | round(1) }}"

velvet glen
#

Great explanation - thanks, crystal clear!

gusty nimbus
#

hey anyone has an idea i have an RF sensor on my postbox outside (its an metal one but my RF bridge is near and luckly it works)
so it sends telegram now that there is post

#

using this:

#
  • alias: Receive RF Briefbus
    trigger:
    platform: event
    event_type: sonoff.remote
    event_data:
    name: Briefbus
    action:
    • data:
      message: Er is post!
      service: notify.telegram
#

in automatisation

#

is it possible to create a Card (postbox for example)

#

that shows for a day the times when there was delivered something?

#

for example just a list:
Briefbus
9u32
11u23
14u33

#

so i see it directly without much clicking πŸ˜‰

hexed galleon
#

Probably a super simple one, but what's the easiest way to check if now() >= a certain time?

arctic sorrel
#

In an action or a condition, or a trigger?

hexed galleon
#

Hmm, to be used as a condition I guess. true/false response. For a bayesian sensor.

arctic sorrel
#

You'll see that {{ now() }} produces a human time in devtools -> Templates

hexed galleon
#

Yeah, saw that. Just needed the comparison logic and converting time string to time object. Looks like those docs will do the trick, thanks!

cobalt kernel
#

oh, for bayesian sensor.. nvm

hexed galleon
#

Am I safe to just wrap a not() around an is_state to invert it?

arctic sorrel
#

{{ not is_state('binary_sensor.asleep','on') }}

hexed galleon
#

First template-driven bayesian sensor with 8 observations done. Some whacky logic in there!

#

Wow, the display of observations for templates in the entity is... less than ideal.

woeful loom
#

Instead try

      iss_duration_test1:
        value_template: '{{ states.sensor.iss_passtimes_test.attributes[1]["duration"]  }}'
@arctic sorrel
I've solved it at last, so easy when the penny dropped, had to add one more level - thanks for your patience:

value_template: '{{ states.sensor.iss_passtimes_test.attributes[response][1]["duration"] }}'

silent barnBOT
small rock
brisk temple
#

Don't need -

#

In front of media_players

#

And your logic won't work, needs one full if, elif, else, end

small rock
#

How could i do It then?

brisk temple
#

You'll need to use trigger.entity_id

small rock
#

trigger isn't possible it's part of a bigger script

arctic sorrel
#

Strip the - out of the entity lines

#

Your entity isn't - media_player.banana but media_player.banana

#

Not entirely sure you can do a list like that though

small rock
arctic sorrel
#

I don't think you can do multiple entities like that

small rock
#

The idea is to pause mopidy or spotify entries, play tts and then resume

brisk temple
#

Your automation can still send the trigger.entity_id

small rock
#

Currenlty I only run the script

#

is there a way to do it for conditional per entity?

fringe leaf
#

Would this be the right channel to ask about a Utility Meter sensor making problems? πŸ™‚

brisk temple
#

@phdelodder how are you running this, clicking each script manually?

small rock
#

@brisk temple No I use the script ui_tts

#

It's include in the paste

brisk temple
#

Just break out into each entity into it's own template

#
    data_template: 
      entity_id: >-
        {% if is_state('variable.spotify_isabel', "True") %}
         - media_player.spotify_isabel
        {% endif %}```
#

so you would have 4 of those for each of your media players

#

and variable.

small rock
#

often they are false so the script fails

#

But hey I'll split it up even more

#

Can I use a script variable in a template eg: {% if is_state('variable{{script_variable}}', value) %}

brisk temple
#

might have to | int it as it will probably come over as a string

small rock
brisk temple
#

πŸ‘

#

your condition will stop the script from continuing if first user is not true so it won't run the others

stray topaz
#

short question (i hope πŸ˜‚ ): Why is this not working?

action:
  service: light.turn_on
  entity_id:
    - light.1e_garderobe_test_lamp
  data_template:
    brightness: >
      {% set grens = states('input_number.lumen_grens_buiten')|int %}
      {% set lumen = states('sensor.voortuin_deur_multisensor_illuminance')|int %}
      {% if lumen < grens %}
        "{{states('input_number.1e_garderobe_plafond_licht_sterkte_in_de_ochtend_in_de_avond')|int}}"
      {% else %}
        "{{states('input_number.1e_garderobe_plafond_licht_sterkte_overdag')|int}}"
      {% endif %}
fringe leaf
#

Could it be that this Template reset itself with HA restart?..
{{ as_timestamp(states.binary_sensor.dryer_on.last_changed) | timestamp_custom('%d/%m %H:%M',True) }}

stray topaz
#

It produces this error: Invalid data for call_service at pos 1: expected int for dictionary value @ data['brightness']

arctic sorrel
#
        "{{states('input_number.1e_garderobe_plafond_licht_sterkte_in_de_ochtend_in_de_avond')|int}}"
``` πŸ€”
#

See the "? Bin them πŸ˜‰

#

Same for the other line

#

You're carefully turning your state into an int, and then into a string

stray topaz
#

Damn, I thought I tried that... You're a life saver again! Thanks!

visual aspen
#

Hi, for a Template Switch’s power_on action, is it possible to call multiple services please?

#

switch:

  • platform: template
    ...
    turn_on:
    • service: switch.first
      data ...
    • service: switch.second
#

Is this possible?

arctic sorrel
#

I'm pretty sure you'd need to use a script for that

visual aspen
#

I just tried it and it didnt complain about the config. Seems to be working but need to test thoroghly as both actions are backups for each other and its hard to tell if both worked