#templates-archived

1 messages · Page 124 of 1

grim flicker
#

yes but { "write" : {"command": "display", "animType": "static", "animData": "1 36776 1 {{paneel1_rood}} {{paneel1_groen}} {{paneel1_blauw}} 0 20 ", "loop": false, "palette": [], "colorType": "HSB"}
1 will also work because you only change the color of tile with id 36776

#

the thing is this code looks weird because it needs to be written like this:
{ "write" : {"command": "display", "animType": "static", "animData": "1 36776 1 255 255 255 0 20", "loop": false, "palette": [], "colorType": "HSB"}

#

255 255 255 are the rgb colors

mighty ledge
#

sorry, on phone, give me a sec

grim flicker
#

if you have more tiles they just come behind the first one. like this:
{ "write" : {"command": "display", "animType": "static", "animData": "2 36776 1 255 255 255 0 20 36666 1 255 255 255 0 20", "loop": false, "palette": [], "colorType": "HSB"}

#

36776 and 36666 are the id's of the tiles. i just did breakes in them to make it readable in the template.

#

so you can leave parts out of this code. You can for example leave 36666 1 255 255 255 0 20out of it. but you cant leave it in and not set the rgb numbers. So if i put in all the tiles like this using the {{paneel1_groen}} etc. to set the colors and a tile is not getting the data the code of that tile would be 36666 1 0 20 and this messes up the nanoleaf controller. so the whole line from id until 20 needs to be removed

#

So i want to check in the restcommand template if a tile is getting the data and if not the whole line needs to be removed. But i understand that this is impossible?

#

I really dont know how to explain it better... sorry

ivory delta
#

But i understand that this is impossible?
Can you stop with that? No-one has told you this isn't possible.

#

But I don't know why you don't just call the REST command multiple times in an automation to save yourself this trouble.

grim flicker
#

because i dont think the nanoleaf controller likes it to get 18 commands in a split second. its not a very fast thing. but havent tried it yet

crude crest
#

Then put in a delay.

grim flicker
#

but home assistant supports only a seconds delay so the last tile will come up 18 seconds later?

ivory delta
#

My ESP devices can handle hundreds of messages a second. I don't know why an expensive thing like a Nanoleaf can't..

arctic sorrel
#

HA supports delays of under a second just fine

#

But maybe you should try it rather than making assumptions 😉

grim flicker
#

i read it on the ha forums

#

but ok

crude crest
#

I think it's a dot notation for milliseconds. so 00:00:00.100

mighty ledge
#
nanoleaf:
  url: http://192.168.178.54:16021/api/v1/token/effects
  method: PUT
  payload: >
    { "write" : {"command": "display", "animType": "static", "animData":
    {%- set all = [ 36776, 40379, 39889, 47065, 62644, 56943, 44929, 4212, 50749, 42705, 55753, 9801, 2975, 5181, 59276, 33852, 34713, 42845 ] %}
    {%- set ns = namespace(panels=[panels | count | string]) %}
    {%- for panel in panels %}
    {%- set ns.panels = ns.panels + [ '{} 1 {} {} {} 0 20'.format(all[panel.number-1], panel.r, panel.g, panel.b) ] %}
    {%- endfor %}
    "{{ ns.panels | join(' ') }}",
    "loop": false, "palette": [], "colorType": "HSB"}
    }
  content_type: 'application/json'
#

then, your service will be:

#
  - service: rest_command.nanoleaf
    data:
      panels:
      - number: 1
        r: 0
        g: 0
        b: 0
      - number: 2
        r: 0
        g: 0
        b: 0
      - number: 3
        r: 0
        g: 0
        b: 0
#

that should get you what you want

grim flicker
#

if this works i will for ever in your debt 🙂

mighty ledge
#

no clue if it will work out of the box

#

actually, it wont, forgot quotes,

#

just edited, should work now

grim flicker
#

1 moment let me put this in and restart

mighty ledge
#

seems to work with a test

grim flicker
#

that would be very awsome!

#

hmm forgot to change the token.... another restart 🤣

#

Error. Url: http://192.168.178.54:16021/api/v1/token/effects. Status code 400. Payload: b'{ "write" : {"command": "display", "animType": "static", "animData": "3 36776 0 255 0 0 20 40379 0 0 0 0 20 39889 0 0 0 0 20", "loop": false, "palette": [], "colorType": "HSB"} }'

mighty ledge
#

bad request

grim flicker
#

i guess the b. doesnt need to be in the begining?

#

or is that short for something else

mighty ledge
#

it's a bad request, so something isn't formatted correctly

#

I don't have your hardware, so the request looks good to me

grim flicker
#

but this seems very close though

#

ill check some more. maybe the id's arent right or something. bad request atleast means that we are close

#

i see the problem

#

there needs to be a 1 after the id

#

its the frame

mighty ledge
#

jsut adjusted

grim flicker
#

dont ask me why it needs to be in

mighty ledge
#

take a look at the previously posted template

grim flicker
#

i allready changed it. man i cant wait to see this thing working!

#

i must be the biggest idiot ever... just copied token back in the config... another restart 🤓

#

and we have a winner!!!!

#

@mighty ledge many thanks for your effort and patience!

mighty ledge
#

np

viral bolt
#

Hi guys, can someone help me with a template code? I have a air quality sensor who is providing all kind of readings in a json format

silent barnBOT
viral bolt
#

what I want is to interrogate this sensor every 2-3 minutes and from one reading to extract a number of sensors: temp, pressure etc. If i make a reading for each parameter the sensor gets overloaded and I get many missing readings

#

i'm trying with this code but i get an error:

silent barnBOT
ivory delta
#

Please stop posting code walls...

silent barnBOT
#

@viral bolt Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

Please take the time now to review all of the rules and references in #rules.

For sharing code or logs use https://paste.ubuntu.com/.

ivory delta
#

What's the error?

viral bolt
#

Template variable error: dict object has no element 0 when rendering '{{ value_json[0].temp }}

ivory delta
#

Right. So that means you're telling it to get the first thing from a list but it doesn't think it's a list.

#

Is "data" part of the response, as well as all the stuff after it?

viral bolt
#

yep

ivory delta
#

You want something more like this:
value_template: "{{ value_json.data }}"

#

Then what you have for json_attributes will grab all the individual ones.

viral bolt
#

oky, i'll give it a try, thanks

ivory delta
#

If you want just the temperature in the state and still to get all the attributes, it'd be more like this:

value_template: "{{ value_json.data.temp }}"```
And keep what you have for the `json_attributes`
crude crest
#

Any idea where I should look? I can't even find value_json in any of my configuration files.

mighty ledge
#

it's coming from MQTT discovery

crude crest
#

hmm. Okay. It mentioned it was a template variable. so I wan't sure. I'll have to see what I can track down.

naive hatch
#

Does anyone know how to turn on an entity if one entity in a group is on?

I tried this:
{% if 'on' in [ states.binary_sensor.zoom_eliot, binary_sensor.zoom_eliot_s_school_account ] %}
but the sensor isn't avalible

crude crest
#

If one entity in the group is on, isn't the entire group marked as on?

naive hatch
#

Sorry, the entites aren't grouped.

crude crest
#

even if the other entities are off.

naive hatch
#

Is that just a better way to do that then?

crude crest
#

Yeah, because then you could just call a service to turn on the group when it turns on (seems redundant) and it'll turn on the remaining entities. As long as they're controllable entities. Binary_sensors aren't.

naive hatch
#

I don't actually need to control the group. I'm just trying to monitor the status of two zoom accounts

crude crest
#

And if one or both is on. Yeah, try a group then.

naive hatch
#

Thanks! Is there a way to add a template to a group entity?

#

I assume customise.yaml

crude crest
#

Yeah, you could change the friendly_name based upon a template in a customize statement

naive hatch
#

Could I change the state?

#

Or should I just create a template sensor

crude crest
#

If > 0 binary sensors are on, the group should get marked as on. I believe it works as an OR statement to determine the group status.

naive hatch
#

Right, I'm just trying to make the state of the entity readable, so not as a 0 or 1. I'll just use a template entity

crude crest
#

Yeah, if you need something immediately human readable, a template sensor will work as well.

dull bloom
#

I'm trying to read the current value from my shelly smart plug as a float, not an integer... This is what my sensor looks like now:

- platform: mqtt
  name: "Fireplace Current"
  state_topic: "tele/shelly_smart_plug_fireplace/SENSOR"
  value_template: '{{ value_json["ENERGY"]["Current"] }}'
  unit_of_measurement: "A"

can I just remove the value_json['ENERGY'] to get the actual float value of current?

#

this is using tasmota, BTW

inner mesa
#

that doesn't really make any sense

#

you're parsing the JSON to get that value

dull bloom
#

MQTT has a value of 0.009 A and I need to read that value, not 0

inner mesa
#

so, no, you cannot just not parse the JSON

dull bloom
#

sorry, learning 😦

#

lemme see if there's documentation on value_json... maybe I can use something other than energy

inner mesa
#

value_json is just letting you index into the JSON. it doesn't know anything about the structure of that JSON

dull bloom
#

so value_json.Current would work?

inner mesa
#

you're parsing a JSON data structure

#

what does it look like?

dull bloom
#

{"Time":"2021-04-14T21:52:37","ENERGY":{"TotalStartTime":"2020-12-26T22:39:32","Total":3.154,"Yesterday":0.225,"Today":2.928,"Period":0,"Power":0,"ApparentPower":1,"ReactivePower":1,"Factor":0.21,"Voltage":121,"Current":0.008}}

#

ah... I see... current is under energy

inner mesa
#

ok, so no, you cannot just remove the "ENERGY" part, because "Current" is a child

#

yes

dull bloom
#

so why is it returning an integer and not a float?

inner mesa
#

you can try adding |float

dull bloom
#

boom... thanks Rob!

zenith junco
#

Is there a way to use a template to do an If / Then statement for a serial sensor?

#

I tried doing this:

  • platform: template
    sensors:
    zone_sensor:
    friendly_name: NilesZone
    value_template: "{% if is_state('{{ states('sensor.file_value').split(';')[0] }}', 'usc') %}
    {{ states('sensor.serial_sensor').split(',')[3] | float }}
    {% endif %}"
#

but I obviously have a syntax error somewhere or maybe its not able to do that

inner mesa
#

you have a multi-line template without formatting it as such

#

or actually, that might work with the quotes, but it's hard to read

zenith junco
#

I'll tell you what I am attempting to do and maybe my whole approach is wrong

#

I am sending commands to a Niles audio zone controller

#

using command line in HA

inner mesa
#

you need an {% else %} in there or you'll end up with no value at some point

#

and that will be a syntax error

zenith junco
#

and depending on the function it spits out either:

#

usc,2,1,0,0,32,0,0,0

#

or something liek this

#

rznt,12,OK

#

So I need a sensor to look for the messages that start with USC

inner mesa
#

that will probably do it, but like I said, you need an else

#

because you can't have no value

zenith junco
#

I tried adding {% else %}

#

still getting syntax error

#

Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token ',', got 'sensor') for dictionary value @ data['sensors']['zone_sensor']['value_template']. Got "{% if is_state('{{ states('sensor.file_value').split(';')[0] }}', 'usc') %} {{ states('sensor.serial_sensor').split(',')[3] | float }} {% else %} {% endif %}". (See ?, line ?).

inner mesa
#

not just an else

#

you didn't provide a value for the else clause

zenith junco
#

ah

inner mesa
#

understand the problemn?

zenith junco
#

Yes

inner mesa
#

it's like you wrote value_template:

zenith junco
#

So what would I say if I want it to do nothing in the else function

inner mesa
#

but I don't think that's the only problem based on the error

#

oh, you're nesting {{ }} inside. that's bad

#

yeah, there's some brokenness in there

zenith junco
#

SO this nested if statement

#

{% if is_state('{{ states('sensor.file_value').split(';')[0] }}', 'usc') %}

#

is probably broken

inner mesa
#
        value_template: >-
          {% if states('sensor.file_value').split(';')[0] == 'usc' %}
            {{ states('sensor.serial_sensor').split(',')[3] | float }}
          {% else %} ""
          {% endif %}
#

something like that

zenith junco
#

Error loading /config/configuration.yaml: mapping values are not allowed here
in "/config/configuration.yaml", line 183, column 24

inner mesa
#

🤷

#

show what you have with proper formatting

zenith junco
#

Ya, its a weird problem

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

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.

zenith junco
#

\\ - platform: template
sensors:
zone_sensor:
friendly_name: NilesZone
value_template: >-
{% if states('sensor.file_value').split(';')[0] == 'usc' %}
{{ states('sensor.serial_sensor').split(',')[3] | float }}
{% endif %}

inner mesa
#

"proper formatting"

zenith junco
#

oops

inner mesa
#

as above

zenith junco
#
    sensors:
      zone_sensor:
        friendly_name: NilesZone
         value_template: >-
          {% if states('sensor.file_value').split(';')[0] == 'usc' %}
            {{ states('sensor.serial_sensor').split(',')[3] | float }}
          {% endif %}


inner mesa
#

you're still missing the else

zenith junco
#

Oh ya. Duh

inner mesa
#

and your spacing is off

zenith junco
#

I'll try fix

inner mesa
#
  - platform: template
    sensors:
      zone_sensor:
        friendly_name: NilesZone
        value_template: >-
          {% if states('sensor.file_value').split(';')[0] == 'usc' %}
            {{ states('sensor.serial_sensor').split(',')[3] | float }}
          {% else %} "foo"
          {% endif %}
#

assuming all that string manipulating is correct for your input

zenith junco
#

Well....The config checker is happy 🙂

#

So testing now

#

thanks for the help!

inner mesa
#

you need to decide what you want in the "else" clause

#

or "foo" is cool

naive hatch
#

Is there a way to use a template to set the attribute of an entity in customise.yaml?

ivory delta
#

I... don't know what you're trying to do.

#

Sounds like a job for a template sensor though 😉

naive hatch
#

Template sensors could solve the world's problems

#

Let me rephrase my question: I'm trying to assign an attribute of an entity to the value of a different entity

ivory delta
#

So... a template sensor 😉

#

You don't set the values of entities. Let integrations take care of that.

naive hatch
#

Can't you set them through customize.yaml?

ivory delta
#

Statically, maybe. Dynamically... template sensor.

naive hatch
#

Okay, thanks :)

ivory delta
#

And I don't know if you noticed... but you have red on you.

naive hatch
#

Yep :)

#

trying to figure out if this is some kind of test

zenith junco
#

Anyone have experience with Serial sensor

deft timber
silent barnBOT
#

Don't ask to ask, just ask your question. Then people can answer when they're around.

When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:

  1. What version of the Home Assistant are you running? (remember, last isn't a version)
  2. What exactly are you trying to do that won't work?
  3. Is the problem uniform or erratic?
  4. What's the exact error message?
  5. When did it arise?
  6. What exactly don't you "get"?
  7. Can you share sample code, ideally with line errors where the error occurs?
smoky idol
#

Hi, untill now I tried the group method which didn't work.
Today I am building an automation based on what you sent. I'll update once finished.
The one mono recommend also didn't work. I kept getting messages from entities without moving.
Bacuse I already created the text entities, I am also testing my idea...

#

I'll try to sum it up for others to come

zenith junco
#

Can anyone tell me why that would result in just 0.0 as a value from this output:

#
    serial_port: /dev/ttyUSB0
    baudrate: 38400

  - platform: template
    sensors:
      zone_sensor:
        friendly_name: NilesZone
        value_template: "{{ states('sensor.serial_sensor') | float}}"```
#

when the serial output is

#

usc,2,1,0,0,48,0,0,0

dreamy sinew
#

because that output is a string and "foo"|float -> 0.0

mighty ledge
zenith junco
#

I need to parse the output

#

usc,1 is the response code

#

the rest are all settings

#

Zone, Input, Mute, Volume, Bass, Treble, Balance

#

basically, I am trying to get the status of a multizone audio controller

#

using serial RS232

dreamy sinew
#

what do you want this sensor to actually output?

zenith junco
#

I need a list of these

#

Zone, Input, Mute, Volume, Bass, Treble, Balance

#

so that I can set the state of the buttons

#

the problem with it is it only outputs the active zone at any time

#

so I need to make a script that will set it to zone 1, output, then zone 2, output, etc through zone 6

#

And then probably return it to the zone that was active at the start of the script

dreamy sinew
#

if its always the same format in the same pattern you can do states(...).split('.')[<pos>] to pull out the individual items

zenith junco
#

I was trying to do that, but was getting unknowns or 0.0

dreamy sinew
#

don't cast to float

zenith junco
#

so I wanted to simply get the output first so I can see that the serial data is actually making it to HA first

#

If I remove | float

#

it just stays as Unknown

#

and turned on debugging, but dont get any output

#

from serial

dreamy sinew
#

"Unknown"|float -> 0.0

#

fix the unknown first

mighty ledge
#

how'd you arrive at sensor.serial_sensor?

zenith junco
#

from this example

#

Are you saying the variable is wrong

#

Actually, now testing I think I am going to have to abandon using there serial sensor

#

It appears to tie up the serial port

#

so I can't send the outgoing commands I need

#

going to have to do it a different way

mighty ledge
# zenith junco from this example

for future referece, don't use examples and assume they will match your configuration. When you create a sensor, the first thing you should check is what the entity_id is by searching your own system.

little gale
#

Will this template retrieve the last state of the entity if the sensor attribute disappears?

{% if state_attr('sensor.orbi_router','WAN In (total)') == None %} {{ states('sensor.orbi_router_wan_in_total') }}
ivory delta
#

No. If it's disappeared, there's no state to read.

little gale
#

This is a value_template

ivory delta
#

Templates only know 'now', they have no concept of history. You'll probably want to use an automation to set an input text each time it changes, unless the change is to None/Unavailable.

#

If things keep going unavailable, the better option would be to fix the underlying problem,.

little gale
#

Gotcha. For a template that has a unit_of_measurement, what happens when it receives a non number? How does the graph react?

ivory delta
#

I haven't seen it before. I would guess that it just misses that point on the graph.

inner mesa
#

or it's zero

little gale
#

Ok. There's no way to get the last known state of an entity in a value_template, right?

ivory delta
#

I just gave you an answer and a solution.

little gale
#

Ah ok thanks 👍

gray cedar
#

Can someone point me in the right direction because I'm not sure it's templates that I need. I have a binary_sensor that is misleading. https://ibb.co/WFgLR6M (picture). I want the binary_sensor.game to show "on" if the wattage is over 25 watts meaning that the console is on and being used. How do i accomplish this with an if statement or variable to either change the binary_sensor or make a new one?

ivory delta
gray cedar
#

Ok. Thank you @ivory delta

ivory delta
#

You haven't said what the problem is.

rigid chasm
#

Hi i have question. i am using template sensor for my hot water usage, and i am getting this reading from it ,,daily water 0.8455m3 how do i narrow it down to 0.8 m3 ?

inner mesa
#

|round(1) will round it, but you may need to do .split('m')[0]|float|round(1)

#

if the units are really part of the state

rigid chasm
#

and i am also using last week sensor witch shows with this reading 18.9902m3 but i would like get this reading 18.99m3 witch is easy to read.

inner mesa
#

same answer

rigid chasm
#

here is my value_template: value_template: "{{ (states('sensor.daily_water')|float * (states('input_number.notkunargjald_m3'))|float) | round(3)}}"

#

i changed it round (1) but no luck

inner mesa
#

you don't need the parens around the state() call. |float binds tightly

#

looks like you're just rounding the last value?

#

you have too many parens in there

rigid chasm
#

so how do i do this ?

inner mesa
#

value_template: "{{ (states('sensor.daily_water')|float * states('input_number.notkunargjald_m3')|float)|round(1) }}"

rigid chasm
#

sorry if i am mispelling my english writing sometimes comes out messy mindblown

inner mesa
#

that's okay - the language of templates is universal 🙂

#

does that work?

rigid chasm
#

hold on i will check

inner mesa
#

just put it in devtools -> Templates

rigid chasm
#

monthly_energy:
friendly_name: Mánaðar orkunotkun
icon_template: mdi:counter
value_template: >-
{{ (states('sensor.monthly_energy_day')|float)|round(1) }}
unit_of_measurement: m³

#

i get zero reading

#

check on this tomorow thanks anyway

naive hatch
#

This is always returning clear?

        return entity.state === 'on' ? 'Motion Detected' : 'Clear'; 
      ]]]```
Any ideas on what I'm doing wrong? The entity is an input_boolean
naive hatch
#

This seems to be a problem with either button_card, or browser_mod.

crude crest
#

Is there a way to just execute a template in a script to setup some variables?

inner mesa
#

rephrase perhaps?

#

what are you really trying to do?

crude crest
#
    sequence: >
      {% do something %}
    - service: domain.whatever
#

I think that's valid, actually.

inner mesa
#

it's not

crude crest
#

damn, okay so i'm trying to basically use a script as a function to create a loop based upon passed variables.

inner mesa
#

then just call it with data:

#
    - data:
        title: "Leak Detector Heartbeat Missed!"
        message: "{{ trigger.to_state.name }} heartbeat missed!"
      service: script.notify_iphone
crude crest
#

and that can be it's own sequence item?

inner mesa
#

the script?

#

that came from an automation, but yes, that can be part of a script

#

scripts can call other scripts

crude crest
#

I'm passing data into a script, need to do some quick math on it, and then run a loop. That's pretty much it.

#

So if I can just do a data block in the script sequence, that's perfect.

naive hatch
#

Does anyone know how to check a list of sensors for the ones that are enabled, and then report the first one that you see (in a javascript template?) I have this: https://pastebin.ubuntu.com/p/QNWDqD7gvn/ but it's always returning 'Clear'
Ignore the formatting of the first line, pastebin likes to mess with it

inner mesa
#

read through that doc page, and note the difference between passing variables when calling a script like service: script.xxxx and service: script.turn_on

#

one requires a variables: block and the other does not

crude crest
#

I've always passed by calling as a service, but I've never seen the fields: blocks before. That's actually really nice for documentation.

inner mesa
#

yep

#

I prefer my code to be hard to use

crude crest
#

Ah, my repo is in the cookbook, so I have to make sure my shit's well commented.

#

It forces me to do so and then I don't go back and wonder wtf I was doing, lol.

naive hatch
#

var deck = states['input_boolean.deck_motion_sensor'] == 'on' ? 'De' : 'X';
This reads X even though input_boolean.deck_motion_sensor is on. Any ideas what could be causing that?

#

This piece of code just doesn't like me

crude crest
#

Having an issue with variable typing. Is there a way to convert a variable from one type to another, or do I have to use a type() function every time the variable is referenced? Issue at L40. https://pastebin.ubuntu.com/p/B32cmz2qjr/

inner mesa
#

like set foo = foo|float?

grave pumice
#

Morning - I'm using Post to get entity states into HA. The problem is they disappear when HA restarts until they get posted in. If I make a template sensor for each with a dummy value woudl that mean the state sticks over restarts?

coarse tiger
#

the post API is only for development purposes afaik

olive ibex
#

Anyone know how to design and implement a full theme for HomeAssistant?

silent barnBOT
#

Please DO NOT cross post. Read the channel description, post it and wait for folks to respond.

If you don't get any responses after an hour or more, and your message is no longer on screen, it is fine to re-post or post a link to it.

stone flare
#

Hi all

#

I have a quick question

#

I would like to add meteo alarm in my config.yaml file

#

But after doing those little lines into the config and restarting hassio again

#

I get a information on my entity binary_sensor meteo alarm that i have no uniqueid for it.

#

The hassio wiki has no example to set in unique id in the yaml. Can anyone tell me where i have to put unique id and how i have to do it?

#

binary_sensor:

  • platform: meteoalarm
    Unique_id: „testmeteo“
    country: "NL"
    province: "Groningen"
#

Is that right?

mighty ledge
edgy umbra
#

Made a script for changing my theme manual. Anyone now if it’s possible to use one script to let’s say set theme black and if theme is black set theme white.

crude crest
# inner mesa like set foo = foo|float?

Yeah, either using something like float(strVar) or strVar | float. I'm trying to make sure that the data that gets passed into the script is typed correctly so that I can use it to calculate another variable. So, do I need to do that every single time, or can I specify a data type somewhere and have it stick?

crude crest
#

Okay, I'm at a point in my script where I'm getting a division by zero error, and I have no idea where it's coming from. None of my divisors should be 0 from what I've given the script as parameters, and the templates all execute correctly in the dev tools page. Does anyone have any ideas? https://pastebin.ubuntu.com/p/fKgN3Dx98D/

ivory delta
#

Where's it saying the error is?

#

That's a pretty long script for you to expect someone to read all of and guess.

#

Saying that... I don't think it does what you think it does. It's doubtful that it knows the value of count at line 49 before it's used on line 54.

#

If you have something that's dependent on being evaluated in a particular sequence, you'll want to actually template that stuff to be evaluated so.

mighty ledge
#

if interval_pct is 0, you'll get a divide by zero

#

if ending_brightness - starting_brightness is zero, you'll get a divide by zero

#

you don't protect against either of those

crude crest
#

That’s what I was thinking, but I’m also not passing it anything that should be erroneous. I’ll try hard coding a value once I get back to my computer.

mighty ledge
#

0 is a valid pct

ruby crane
#

How can I template a sensor to have the value 0 if it's reported as unavailable?

#

I have a template that reports the value of another sensor if it is between 0-100, but if that sensor is unavailable, my template sensor also shows as unavailable

mighty ledge
#

or unknown

#

plenty of examples out there

crude crest
#

@mighty ledge Got it working. I think the issue was that I was encapsulating some of the templates in quotes, and it was being interpreted as a string value, which converted to a 0. Now to add in some parameter checks for if a 0 is actually passed. https://pastebin.ubuntu.com/p/ZRX88vXTMS/

inner mesa
ivory delta
#

Mmmm, that juicy RegEx goodness.

dreamy sinew
#

oh that'll make life much easier

ivory delta
#

Yes. We'll certainly see fewer questions.

crude crest
ruby crane
#

@mighty ledge Why, though? My current statement checks if the value is <= 100 and >= 0, wouldn't that exclude anything that isn't in that range, including, unavailable and unknown?

dreamy sinew
#

"any string"|float -> 0.0

#

also you're including 0

ivory delta
#

Quicker than coding a bunch of unit tests smart

ruby crane
#

Hm, alright. Now I changed it to >= 1, but it still shows as unavailable if the sensor in the value template is unavailable?

#

y tho

#
        {% if ((state_attr('light.sofflampa_vardagsrum', 'brightness')) / 2.54) | float | round (0) <= 100 and ((state_attr('light.sofflampa_vardagsrum', 'brightness')) / 2.54) | float | round (0) >= 1 %}
          {{ ((state_attr('light.sofflampa_vardagsrum', 'brightness')) / 2.54) | float | round (0) }}
        {% else %}
          0
        {% endif %}```
crude crest
zenith junco
#

If I have a command line sensor, that outputs in CSV

#

I know command line sensor can get multiple values via JSON

#

but can I do the same using csv output?

#

usc,2,2,0,0,59,0,0,0

inner mesa
#

Still working on this? 🙂

#

I would use your command line sensor to pull the payload and a template sensor to populate attributes based on the state of the command line sensor

zenith junco
#

Yep Sure am

#

I have made a lot of progress though

#

Using PySerial command line now

#

So I run the command, and it outputs to this: usc,2,2,0,0,59,0,0,0

#
    name: NilesCurrentZone
    command: "python3 pyserialtest.py znc,5"
    value_template: "{{ value.split(',')[2]}}"```
#

Then I am grabbing the zone using that value templaet

#

but wondering how I can break out all of the sensor data

#

instead of just isolating the 1

inner mesa
#

The template sensor that I mentioned

zenith junco
#

Ohhh, I see what you mean

#

Gotcha, so dont do the value split in the command line sensor, have it take in all the data

inner mesa
#

Right

zenith junco
#

then do a template sensor to pull it apart

#

😄

#

Right on

#

Thanks

#

BOOM. That works perfectly

#

And just like that, after 4 or 5 days I take a old useless zone controller and make it work in Home assistant. Or I could have taken my valuable time and did something else and just bought a fully supported monoprice 🤣

honest mauve
#

Hello

#

how can I write this in the Lovelace yaml file?

#
                                    value_template: >-
                                            {% if not is_state('sensor.asciugatrice_program_progress', 'unavailable') %}true{% endif %}
#

found! 🙂

#
  • entity: sensor.asciugatrice_program_progress
    state_not: 'unavailable'
rare panther
#

I have a list which is bascially a list of files in directory, is there a simple filter to display the number of images? for example

[
  "/path/image1.jpg",
  "/path/test.mp4",
  "/path/image2.jpg",
  "/path/test1.mp4"
]

The above is the list which is returned for {{ state_attr('sensor.camera1','file_list')}} I can apply length to get the number of files like this
{{ state_attr('sensor.camera1','file_list') | length }}. However, is there a filter to get the length for only the .jpg or .mp4?

ivory delta
#

You can map the results and use a RegEx to test the extensions, sure.

#

| map('regex_search','YOUR-REGEX-HERE') | select('true') | list | count

#

There's a PR open that should make that simpler but that doesn't help you today.

jagged coral
#
{{states('sensor.valueA') | float|round(2)}} 99.99
{{states('sensor.valueB') | float|round(2)}} 88.88
{{states('sensor.valueA') | float|round(2) + states('sensor.valueB') | float|round(2)}} 188.876462945

Why when adding two floats with two decimal places does it result in an answer longer than 2 decimals?

ivory delta
#

Welcome to floating point math.

#

Round the result 😉

jagged coral
#

Looks like i need to watch more videos.. Normally i would bracket the result of the two sums then round that (excel math) but the syntax is new to me and i'm getting errors when doing that

#

Thanks for pointing me in right direction.

crude prism
#

Hello, please, I want set up the temperature sensor with min and max value of the last 24 hours. But the min value which is displayed is not tru value, for example: it display 8°C, but real value was 4.6°C. thank you https://paste.ubuntu.com/p/685SJ7YRys/

ivory delta
#

You should probably use the statistics sensor instead. You can ask for more information in #integrations-archived if you need more help with it.

rare panther
#

since my file_list is just a list - will I be able to do a map? Ah - please ignore, had to pipe to a true and got the results - thanks!

silent barnBOT
modern torrent
#

Okay that was too long, I hope someone can help me anyway, or should i try posting my question again with some pastes instead of codeblocks?

ivory delta
#

Yeah, just a little too long, given the rules are 15 lines or less...

silent barnBOT
#

@modern torrent Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

Please take the time now to review all of the rules and references in #rules.

For sharing code or logs use https://paste.ubuntu.com/.

ivory delta
#

Is it always the second item in the list that you want or does the order vary?

modern torrent
#

Yes its always the last one i want, but i hope its always the second one

#

so if the last one is not possible, i am totally fine with alwys the second one

ivory delta
#

{{ states.sensor.ping_test_cron.attributes.report.hubs[1].host }}

#

Use square brackets and a number to pick the item from a list (counting from 0, not from 1).

modern torrent
#

ohh damn i was so close then, i thought this would work, but it didnt :
{{ states.sensor.ping_test_cron.attributes.report.hubs.host[1] }}

But this works, thank you 😄

modern torrent
modern torrent
#

i solved it by editing it with tr (and remove "%") and printing it into a file
Then the sensor is using cat and gets the values that way)

mighty ledge
#

it pays to look at examples 😉

silent barnBOT
radiant pewter
#

Hi! Can someone help me with a switch template that calls a service? I had a look at the switch template page but can’t figure it out. When the switch is turned on I want to call the following service: nissan_leaf.start_charge and has the VIN of my car for the data input. The switch should turn off when the binary sensor (binary_sensor.leaf1spre_charging_status) changes to off.

inner mesa
#

You would need an automation to turn the switch off when the sensor turns off

keen crater
#

Hi there,
I'm working on a notification where I want the payload to show who opened the door. I got it working the Developer Tools->Services but once I add it to my automation I'm getting errors. I don't understand why it doesn't work in the automation.
Can this be done from an automation? Thanks fyhelp!

YAML code:
https://paste.ubuntu.com/p/QfH2fkXVGf/
Log errors:
https://paste.ubuntu.com/p/cqPhW6XWhZ/

mighty ledge
keen crater
#

ahh so the automation was "triggered" by a secondary action so the context is not taken from that action?

raven token
#

Hi there has anything changed with templates recently? I had an automation calling a script with template variables and it no longer works.

crude crest
#

Dumb idea: can I target a specific device type based on model number?

entity_id: >
  {% for device in domain.light %}
  {{ if device.model == "value"
  - {{ device }}
  {{ endif }}
  {% end %}

I'm thinking it should be possible, but just not sure where I should look for that value. I know it's in the device information, but I don't know how to probe that instead of an entity.

#

The idea is to be able to set a z-wave parameter on multiple homogenous devices from a single script call.

#

My current scenario is changing the lights on all of my inovelli switches to red when the alarm is armed, and green when it's not. Or something like that.

mighty ledge
mighty ledge
mighty ledge
crude crest
mighty ledge
#

You'll have to just list the entity_id's out

#

you can't call a zwave.set_param on a group

crude crest
#

Boo, lol. Oh well, it was worth a shot.

mortal sundial
#

Hi everyone,

I'm trying to create a template sensor that estimates if my apple tv state is "playing" and the content type is "video". When i use the youtube app the media_content_type attribute is not available. Since I only use youtube to play videos I would like to include the "app_name" attribute "YouTube" to detect video playback.
How do I get my "or" condition to work correctly?

  • platform: template
    sensors:
    apple_tv_state:
    friendly_name: A movie is playing
    value_template: >-
    {{ is_state('media_player.living_room_apple_tv', 'playing') and
    is_state_attr('media_player.living_room_apple_tv', 'media_content_type', 'video') }} or
    is_state_attr('media_player.living_room_apple_tv', 'app_name', 'YouTube') }}
inner mesa
#

Use parentheses and get rid of the }} in the middle

#

Or something like that. The }} doesn’t belong there

#

I don’t fully understand the logic you’re trying to represent

mortal sundial
#

I need a binary sensor that defaults to true if video content is playing to prevent my motion controlled lights from turning on.

#

is just checked with template validator and like this it seems to work

      {{ is_state('media_player.living_room_apple_tv', 'playing') and
          is_state_attr('media_player.living_room_apple_tv', 'media_content_type', 'video') or
            is_state_attr('media_player.living_room_apple_tv', 'app_name', 'YouTube') }}
#

I don't know why but the attribute "media_content_type" is not always available

ivory delta
#

If it's not playing, it won't have a media type.

mortal sundial
#

not in my case

ivory delta
#

Maybe it just can't tell 🤷‍♂️

mortal sundial
#

Do you have an atv and does it tell the video state in any case?

mortal sundial
inner mesa
#

Then write it like that with parens to enforce order of operations

raven token
mighty ledge
raven token
mighty ledge
raven token
mighty ledge
#

Then you did it wrong. Try it again

raven token
#

Umm its definitely not working?

mighty ledge
#

I do that all the time

#

Also, you don’t need to turn on a script. Just call the script as the service

raven token
#

So I was able to get this working, but still can't get it working if I template the '1'

service: script.pool_pump_cancel_boolean
data:
  program: '1'
mighty ledge
#

If you’re using the script caller you can’t template unless your on 2021.4+

raven token
#

Either way, I tried it with both the old method and the new method. Passing a 1 as a string using {{ '1' }} doesn't work while just doing '1' works fine

mighty ledge
#

Don’t know what to tell you. Check out my automations and scripts. I do this all over the place. You can template those fields.

raven token
#

So weird because I literally had this working last year and sometime between now and then, it stopped working... I tried restarting and doing all kinds of stuff but it just will not work

mighty ledge
#

Always check the errors in your logs

raven token
# mighty ledge Always check the errors in your logs

Hmm well I think that might be right then. I do see errors in the logs when I do {{ '1' }} because it can't concatenate int to str, but when I do {{ '{0:d}'.format(1) }}, it doesn't do anything even though I know that should give 1 as a string

mighty ledge
#

Variables have typing now, numbers will be resolved as a number

#

Even if you want it to be a string

raven token
#

I do remember seeing that change a while back

#

Wept that fixed it. Thanks @mighty ledge! Just needed to convert the int to a string in the script itself

carmine crag
#

Hi guys, I'm busy integrating a pannel heater which is flashed with Tasmota as an MQTT climate device in to my home assistant setup. The problem that I'm stuck on at the moment is getting HA to send out an MQTT payload with a set string and then the temperature value from the climate entity. e.g. SetTemperature=25 where "SetTemperature=" is a constant string and the 25 is the temperature value. Does snyone know how to achieve this? I've spent at least 12 hours trying to figure it out.

inner mesa
#

what have you tried?
seems like it would be as simple as payload_template: SetTemperature={{state_attr('climate.xxx', 'temperature')}}
or however you're arriving at your temperature

#

@carmine crag Otherwise, I'm curious what you arrived at in 12 hours 🙂

#

much typing going on

carmine crag
# inner mesa what have you tried? seems like it would be as simple as `payload_template: SetT...

I arrived at a lot of frustration and lost sleep! I'm just getting started with home assistant so a lot of it was spent on figuring out how to define entities and link the mqtt topics in the config file. Going from an embedded C programming mindset to this has been a challenge, especially with figuring out the templates. I'll try your suggestion later.
What should I replace the "xxx" with in your example? The entity name?

inner mesa
#

where is your temperature coming from?

carmine crag
inner mesa
#

is it the state of that entity?

#

climate.xxx is just the name of the climate entity, whatever yours is

carmine crag
inner mesa
#

unlikely that platform: my_mqtt is a thing

carmine crag
inner mesa
#

what's the rest of it?

carmine crag
silent barnBOT
#

When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.

inner mesa
#

if you mean something like this (from the docs):

#
climate:
  - platform: mqtt
    name: Study
    modes:
      - "off"
      - "heat"
      - "auto"
    mode_command_topic: "study/ac/mode/set"
    mode_state_topic: "study/ac/mode/state"
    mode_state_template: "{{ value_json }}"
#

the entity would be climate.study. Entities are all lowercase, with _ replacing spaces and other puncutation

#

but you can just find it in devtools -> States

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

inner mesa
#

so, climate.livingroom_heater

carmine crag
#

perfect, makes sense that there's no space

inner mesa
#

just check in devtools -> States when it's unclear

carmine crag
#

thanks mate! will test it out tonight. the learning curve is definitely quite steep once you get into the more custom components

inner mesa
#

yeah, that MQTT climate platform is pretty complicated

carmine crag
#

one more question while I have your attention, how do I define the modes so that I can switch the heater on and off from the lovelace card? from what I have seen the modes defines what buttons you have on the card but the power button only switches teh unit off so tis only sending the "off" payload to the command topic

inner mesa
#

usually the "on" state is one of the modes - heat, cool, auto, etc.

#

but I don't know anything about that platform

carmine crag
#

fair enough, I do have a switch that does send the correct command but thats something that was added by mqtt auto discovery. the heating button doesnt seem to send anything out an any of the topics. guess that'll be the next thing to figure out.

inner mesa
#

there are a million config parameters for that, so I gotta believe you can make it do anything you want

frosty lotus
#

finally upgraded HA, and am getting warnings in the logs,

The 'speeds' option near /config/configuration.yaml:17 is deprecated, please remove it from your configuration
The 'speed_template' option near /config/configuration.yaml:17 is deprecated, please remove it from your configuration
The 'set_speed' option near /config/configuration.yaml:17 is deprecated, please remove it from your configuration

I'm trying to find out what the current way is for setting up fans, that appears as lights, as fans in HA, but am coming up empty handed. Anyone able to guide me in the right direction?

nocturne chasm
#

Check the breaking changes

#

Not sure but lots of new stuff with fans

bright quarry
#

i have a template that writes a time value;

      - service: input_text.set_value
        data:
          value: |-
            {{ 'Justin East Window -
             {}'.format(now().strftime('%a, %b %d at %I:%M %p')) }}
        entity_id: input_text.lastusedss

and shows as;
Justin South Window - Sun, Apr 18 at 09:29 PM

but is there a way to get in the UI relative time since this state was last changed?

ex; last changed 2 hours 5 mins ago

inner mesa
#

relative_time

#

like that?

carmine crag
carmine crag
#

ok so I have managed to get some basic functionality out of my climate entity configuration. I can switch the heater on and off and the temperature and state are displayed properly. what I cant get working ifor some reason is setting the temperature based on the slider value. every time I change the slider a MQTT message is sent out but there's no target temperature in it. Here's my current config if anyone can pont me in the right direction:

silent barnBOT
inner mesa
#

Test the template first in devtools -> Templates

oak summit
#

How would I take this: https://paste.ubuntu.com/p/hzcsgCZxq6/ (The atributes to sensor.hacs)

And get: "fontawesome, Start Spotify on chromecast"
(A comma separated list of the display names of all the updates available)

inner mesa
#

{{ state_attr("sensor.hacs", "repositories") | map(attribute="display_name")|join(", ") }}

#

my list is currently empty, but this works on your sample data in place of state_attr() @oak summit

carmine crag
inner mesa
#

You literally find devtools on the sidebar and click it

solar swallow
#

I know what I want to do, but I don't know what its called 😄
I'm trying to make a notification automation for a couple of water sensors, and I'm having issues with putting the offending device name in the message body
https://paste.ubuntu.com/p/ZJtqk5w8GC/

carmine crag
#

ha ha, Developer Tools!

solar swallow
#

I'm pretty sure its gotta be in yaml, because ui editor throws some error

carmine crag
#

well there's no errors and the result of the template is what I see eing published on the mqtt topic:
temperature_command_template: SetTemperature=None

inner mesa
#

then you need to identify the attribute you want

solar swallow
#
Visual editor is not supported for this configuration:
Templates not supported in visual editorYou can still edit your config in YAML.
inner mesa
#

that's not an error

#

trigger.state isn't a thing

#

you just need trigger.to_state.name for the name, and trigger.to_state.state for the state

carmine crag
#

so still no idea how to get the target temperature from the climate slider. I've tried these and more:
temperature_command_template: SetTemperature={{state_attr("climate.toma_heater","desired_temperature")}}
temperature_command_template: SetTemperature={{state_attr("climate.toma_heater","target_temperature")}}
also, interestingly enough "current_temperature" does give me the format that I want but the value is obviously not the one that I want.

How on earth do I identify the attribute of the temperature slider? according to the documentation ist targe_temperature but that gives me "None" as well. fml

inner mesa
#

devtools -> States

carmine crag
#

seems like I'm catching up, just set "temperature: 25" and it set the target temperature of my heater. this is great but there's still a disconnect between the slider and the temperature variable

#

so whenever I move the temperature slider it sets the climate entity's mode to "off" which then sets the temperature to "null"

sonic nimbus
#

hello, I jsut wanted to check following code with you guys if I need to convert to string

#
      data_template:
        entity_id: input_text.vacation_lights
        value: "{{ state_attr('group.simulation_lights','entity_id') | random }}"```
#

Im getting correct value in my templates editor

#

switch.livingroom_coridor_main_light but I think I need to convert it into string in order to add to my input_text ?

ivory delta
#

Templates return strings anyway 🤷‍♂️

inner mesa
#

Unless they don’t

ivory delta
#

Fairly certain they always do and HA just knows when to attempt to cast them to another data type.

sonic nimbus
#

I tried just this to read from input_text

#

and I got an error

#

I think the problem is in reading the input_text.vacation_lights entity either in writing to it

solar swallow
#

okay so I got trigger.entity_id to return something, but I'd like the friendly name, but I can't find that in the document, google makes me think that maybe I'm trying to find an attribute?

inner mesa
#

trigger.to_state.name

solar swallow
#

Error: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'

#

is that because run action is a poor way of testing?

inner mesa
#

Yes

#

There’s no trigger

solar swallow
#

go to developer and just enter low battery values into state and wait?

inner mesa
#

That’s one way

solar swallow
#

im happy to learn another

inner mesa
#

No, that’s fine

solar swallow
#

k

#

aha!

#

who knows how many times I did it right, but tested wrong

#

Thanks!

jagged obsidian
#

how to escape f.e. "current_temperature_template":"{{value_json['TuyaSNS']['Temperature']}}" that needs to be in an automation mqtt publish payload field? currently its trying to parse value_json when triggered

night warren
ivory delta
#

Pictures of text 🤢

night warren
#

No solution tho!

ivory delta
#

To answer your original question though... it's pretty self-explanatory. At the time of rendering those templates, value_json didn't have the properties your templates are trying to read.

#

Unless you share your config (as text and using a sharing tool if it's over 15 lines), it's hard to say more.

night warren
#

Could that cause the out of memory issue?

ivory delta
#

Almost definitely not...

#

That's usually going to be because people run way too much on kids toys like the Raspberry Pi.

night warren
#

I'm running on a VM...Its been quite happy with 2GB of RAM until now....I've added a further 2GB to it and still it happens

jade citrus
#

Hi eveyone, new to this place!
Really having troubles with templating; and i should continu with templating or AppDaemon.
From an email i get a date in Dutch "1 mei 2021" (English 1th May 2021). I can get this string from the mail, but i can't use this date as it's Dutch.
i can extract the day, year; but the month is difficult: Mei = May = 05.
Any ideas how to achieve this?

ivory delta
#

You want the number of the month based on the Dutch name for the month?

#

Just use an array of the names and find their index (add one at the end, since computers count from zero):

{{ months.index('mei') + 1 }}```
jade citrus
#

ok that is something i'm looking for.
But can i do all of this in the value template of a sensor?

ivory delta
#

Sure, why not? You can do multi-line templates 😉

jade citrus
#

ok first i use this:
{{ state_attr('sensor.boekingen_imap_sensor','body') | regex_findall_index("Datum:\s\d+\s(\w+)\s") }}
to get written month name; I need to store this first in a variable i guess?

#

or i can put this directly in to the ('mei') part i guess!

ivory delta
#

If it were me, I'd track the different date components as variables just to make it easier to read. But yes, you can do it in-line if you prefer.

jade citrus
#

awesome!
{% set months = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli','augustus','september','oktober','november','december'] %}
{{ months.index(state_attr('sensor.boekingen_imap_sensor','body') | regex_findall_index("Datum:\s\d+\s(\w+)\s")) + 1 }}
This just works! love Hass

dawn relic
#
  - platform: scrape
    name: 'Ethereum Exodus balans'
    resource: "https://etherscan.io/address/0x82fbed465c16679c6dc8e4d8c2dfecd097175fb8"
    select: ".col-md-8"

I was told. If I wanted this output to be a float instead of a string. I had to use a value_template. Could somebody help me setup this template?
Im trying to get just the number from my eth balance and not the extra Ether part at the end.

ivory delta
#

Show what the data looks like, what you want it to look like and what you've tried so far...

jade citrus
dawn relic
jade citrus
#

Did a search on this Discord, but seems only 1 person asked about this, and was in May 2021 and didnt get any help with it... 🤣 So will be a challenge i guess!

ivory delta
#

They won't get help yet, the rest of us aren't in May...

#

Pesky time travellers.

jade citrus
#

May 2018 🙂 lol

night warren
#

I'm trying to set up an automation to take the incoming caller ID as per https://www.sipgate.io/push-api/api-references
It sends the POST request using application/x-www-form-urlencoded
Has anyone got an example of how this should be parsed?
From what I read it should use a filter and 'urlencode' but I'm not sure exactly what this means
This is the data
data: __type: <class 'multidict._multidict.MultiDictProxy'> repr: >- <MultiDictProxy('event': 'newCall', 'direction': 'in', 'from': '447976002117', 'to': '441416111332', 'callId': '54566B150B0C0D3A5D53435F57597E57525B575D535E515A785E515B45524252434747585A57', 'origCallId': '54566B150B0C0D3A5D53435F57597E57525B575D535E515A785E515B45524252434747585A57', 'user[]': 'A8ree', 'userId[]': 'w0', 'fullUserId[]': '1631325w0', 'xcid': '92de953efcecfc7a')>

ivory delta
#

If what you're doing next with it needs a float, you can cast it to a float - but templates will return strings anyway.

dawn relic
#

The arrow points at the blank space between the ' '

ivory delta
#

You need to mix quotes. If you're using single quotes inside a template, wrap the template with double quotes.

#

Which way round doesn't matter but you can't use the same inside and around.

dawn relic
#

Aha, the Ether part is now gone, which is great. Although it seems like the next template:

  - platform: template
    sensors:
      ethereum_waarde:
        friendly_name: 'Ethereum waarde'
        value_template: "{{ (((states('sensor.Ethereum_Exodus_balans') | float) + (states('sensor.Ethereum_Bitvavo_balans') | float)) * (states('sensor.cryptoinfo_ethereum_ethereum_eur') | float)) | round(2) }}"
        unit_of_measurement: '€'

Isn't able to add the 2 values together and multiply it by the worth of ethereum.
I know for sure the Ethereum sensor for the ethereum worth (which is: sensor.cryptoinfo_ethereum_ethereum_eur) is outputet correctly. Do you know how to work around this problem?

#

The output I get from the template is 0.0

ivory delta
#

Test the template at Dev Tools > Templates. Substitute in values in place of the states() functions if you want to experiment with different values.

dawn relic
#

I forgot to put the sensor.cryptoinfo_ethereum_ethereum_eur into the code since I was working in my test instance. Thanks anyway! It works now 🙂

clever fable
#

I am trying to include a criteria for a template sensor that will be used in an occupancy sensor. My issue is only with the last line of this code. I know it is wrong as it wont pass the config check at all.

#
  sensors:
    living_room_occupied:
      value_template: >-
        {{ is_state('binary_sensor.front_door', 'on')
           or is_state('binary_sensor.living_room_mot_n', 'on')
           or is_state('binary_sensor.living_room_mot_s', 'on')
           or is_state ('sensor.living_room_grideye_occu_count'| float > 1') }}```
#

The idea is that it basically "or grideye has a value of less than 1"

#

BTW just fixed the space after is_state and took the ' out

#

It now passes but I'll see if it works.

inner mesa
#

your parens are in the wrong place

#

actually, it's just wrong 🙂

#

states('sensor.living_room_grideye_occu_count')|float > 1

clever fable
#

Yeah I figured as much no offence taken I'm still trying to figure out this template stuff.

inner mesa
#

it has exactly that

clever fable
#

Ok cool thanks that is a much better doc than I was trying to learn from

ivory delta
#

You could simplify that template a lot by putting the 3 sensor sensors into a group.

clever fable
#

@ivory delta how would that look?

ivory delta
#

Even better... wrap the Grideye sensor in a template binary sensor (same logic, count > 1) and include that in the group.

silent barnBOT
#

Groups allow the user to combine multiple entities into one.

clever fable
#

Cool I'll take a look at that

ivory delta
#

Templates can be really powerful and do stuff that wouldn't normally be possible otherwise - but for some things, it's simpler to use the built-in tools.

silent barnBOT
silver basin
#

Hey folks!
I am trying to create a sensor using API that I can make automations with, based on zones.
My problem is that I cannot get my sensor to act as a tracker.
So far I have this - any ideas?
https://paste.ubuntu.com/p/MrjtM3CYxm/

mighty ledge
silver basin
median mason
#

I am trying to parse some data from an API, but cant get the value. all the attributes are parsed except the value.

- platform: rest
  name: Covid19 München Total Cases
  resource: https://api.corona-zahlen.org/districts/09162
  value_template: "{{ value_json.data.09162.cases}}"
  json_attributes_path: "$.data.09162"
  json_attributes:
    - deaths
    - weekIncidence
    - casesPer100k
    - delta
  scan_interval: 3600
ivory delta
#

Your template is invalid. You should use square braces to access keys whose names start with numbers.

#

{{ value_json.data['09162'].cases }}

median mason
spiral imp
#

I have have the attributes in the attached link for sensor.grocy_chores (from the custom component). Is there a way to extract, for example, "next_estimated_execution_time" for "id: 2" ? https://paste.ubuntu.com/p/7YzKbVw43h/

spiral imp
#

I got it. For reference: {{ states.sensor.grocy_chores.attributes.chores.2.next_estimated_execution_time }}

ivory delta
#

FYI, the correct way to access an item in a list is like this: chores[2]. The fact that yours works is just down to a quirk of Jinja/HA and doesn't reflect how you'd normally access list items.

spiral imp
#

good to know, thanks

spiral imp
#

This attribute is coming across as a string so as_timestamp is not reading it correctly. Is there a way to convert this? next_estimated_execution_time: '2022-04-01T00:00:00+00:00'

inner mesa
#

Look into strptime

mighty ledge
spiral imp
#

The attribute for {{ (states.sensor.grocy_chores.attributes.chores[1].next_estimated_execution_time) }} is "2021-05-01T00:00:00+00:00". For {{ as_timestamp(states.sensor.grocy_chores.attributes.chores[1].next_estimated_execution_time) | timestamp_custom ('%b %-d, %Y')}} it is "Apr 30, 2021"

mighty ledge
spiral imp
#

ok, that worked but why? What does "false" do?

mighty ledge
#

treats it as utc

spiral imp
#

I just realized it is still not pulling the correct date. The attached is pasted from the HA Attributes in Developer Tools. The attribute should be '2022-04-01T00:00:00+00:00' but {{ (states.sensor.grocy_chores.attributes.chores[1].next_estimated_execution_time) }} is returning "2021-05-01T00:00:00+00:00". https://paste.ubuntu.com/p/7YzKbVw43h/

#

figured it out, I was assuming that [1] corresponded to the ID:1. I realize now that it is positional and if I change [1] to [0] it is pulling the correct date

thorny snow
#

Hi guys, can someone provide any help with Rest sensor templating? I believe JSON format...but not being an expert

#

In case someone has a couple of minutes...here are details of the issue I have

coarse tiger
#

replace value_json.value with value_json ?

thorny snow
#

then sensors are no more published

patent shore
#

Can anyone help me out with setting up a template binary sensor? I have tuya contact sensors which I’ve “integrated” by setting up switches based on them connecting to my router (they connect for 2 mins every time their state changes). I set it to turn on a switch when they connect and turn it off when they connect again but I’d rather have it as a sensor. I know I could have the sensor based on the switch but it feels like a long route, so want to remove the switch.

Tl;dr: How do I make my template binary sensor to show as open when a device_tracker is home and then show as closed next time that device_tracker is home?

inner mesa
#

you can put whatever logic you want for the value_template: for your sensor

ivory delta
#

Tl;dr: How do I make my template binary sensor to show as open when a device_tracker is home and then show as closed next time that device_tracker is home?
You don't. Templates have no concept of history.
I know I could have the sensor based on the switch
This is how you should do it...

inner mesa
#

nevermind. misread that curious requirement 🙂

stiff summit
#

Hi Does anyone have any thoughts as to why "{{ state_attr('weather.home_hourly', 'condition') }}" does not work for the met.no integration? It just returns "none"? I would very much like to use the met.no integration to populate "condition_template:" in the weather template (the rest I populate with my own rain and wind sensors

If there is a way to "grep" the condition from the forecast array string you get by passing "{{ state_attr('weather.home_hourly', 'forecast') }}" I am welcome to suggestion. Applogize if these are noob questions, but I’m only a few days into HA converting from OHAB

inner mesa
#

Does that entity have a ‘condition’ attribute?

#

Look in devtools -> States

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

inner mesa
#

{{ temp["forecast"][0]["condition"] }}

#

so,

stiff summit
#

so the 0 is the first index of the array forecast

#

and you ask for the value condition?

inner mesa
#

{{ state_attr('weather.home_hourly', 'forecast')[0]['condition'] }}

stiff summit
#

trying to grasp the syntax here : )

inner mesa
#

[] is indexing into something. in this case, I'm both indexing into a list ("[0]") to get the first element and into a dict to get the value associated with a key (["condition"])

stiff summit
#

Gotcha! Guess I am headed to the docs to read up a bit more

#

Appreciate the help!

inner mesa
#

this is Jinja, and there's lots of info on the web

#

np

#

it's also kinda Python-like

thorny snow
inner mesa
#

if you need to retain a state over a period of time, then the template sensor itself isn't enough

stiff summit
#

I have a custom sensor that gives the beaufort name + meters per second as a string, I recon it would be quite a lot of work to strongarm this into the wind speed section of the weather template?

inner mesa
thorny snow
#

ah sorry

#

can you help on my topic? I really can't find how to sort it out

mighty ledge
#

does value exist inside the json?

patent shore
mighty ledge
# thorny snow ah sorry

Also, as an FYI, you put your post in the hardware section on the forums but you're asking a question about your configuration. That question should have gone in configuration, you probably would have gotten a response quickly if you did that.

thorny snow
mighty ledge
#

spoiler: No

thorny snow
#

🙂 so what I should put in the config there?

mighty ledge
#

what information do you want as the state?

#

look at your json

#

and decide

thorny snow
#

Ok, I will try

#

If I put like “cpu_free” will it anyway create a sensor for each json attribute field?

mighty ledge
#

no, you'll get 1 sensor with 7 attributes

thorny snow
#

Mmm i see, ok tomorrow I will do some test: thank you very much in the meanwhile

thorny snow
#

I am trying again. Anyone who can see what I am doing wrong? This is my sensor:

  • platform: rest
    name: 'Qnap TS-410 version'
    resource: http://update.qnap.com/FirmwareRelease.xml
    json_attributes_path: "$.[docRoot].[storage].[model].[?(@.modelName == TS-410)].[firmware]"
    json_attributes:
    • version
      value_template: '{{ value_json.version }}'

And I get this error: Template variable warning: 'dict object' has no attribute 'version' when rendering '{{ value_json.version }}'

marble jackal
#

Can somebody maybe help me with a template, or tell me what I want to do is even possible?
I have a list with items, e.g. a, b, c, d, e, f, g
I have an input_text which has some of these items (comma seperated) e.g. b, e, g

I now want to take a random item from the list, but not if it is mentioned in the input text.

#

I found something like this:

{% for i in range(11) %}
 {{ i }}
{% endfor %}

But if I use that, it gives me Invalid config for [automation]: invalid template (TemplateSyntaxError: expected token 'in', got '|') for dictionary value @ data['action'][1]['choose'][0]['sequence'][0]['variables']['song']. Got None. (See ?, line ?).

#

More background. I have a tag scanner, and want to play a song when the card is scanned. But not one of the last 3 played songs.
This is my full code I have now: https://paste.ubuntu.com/p/qwTWm7bk7x/

ivory delta
#

It tells you the error: expected token 'in', got '|'. You have for songs | random in last_played, which is invalid syntax.

#

You can't just put random stuff in the middle or the for...in and hope it'll work.

#

There's also no need for loops when you can use filters (see the pinned message):

{% set songs = ['a', 'b', 'c', 'd', 'e', 'f'] %}
{{ songs | reject('in', input_text) | list | random }}```
#

I haven't tested whether that behaves correctly with different data types. 'a, b, c' isn't the same as ['a', 'b', 'c'].

#

@marble jackal ☝️

#

That template returns a random element of songs that isn't present in input_text. You can update it to actually use entities, that's just a demo that'll work in devtools > Templates

marble jackal
#

Thanks a lot! I will give it a try

marble jackal
#

My code for the change of the input_text was not correct, but after adding ,1 in the split it works like a charm. Had to change the max of the input_text to 255 as it could not contain 5 items.

peak juniper
#

Any idea how I can get this API sensor data in to home assistant? I have it configured on an excel spreadsheet to scrape data from Vanguard's API

#

but can't seem to figure out how to get it thru HA

ivory delta
peak juniper
#

that's what I thought - I'm putting it in to template editor in the dev tools but guessing it doesn't actually update it and I'd have to just add it as a sensor and reboot?

#
sensor:
  - platform: rest
    resource: https://api.vanguard.com/rs/gre/gra/1.7.0/datasets/urd-product-details?path=[id=vanguard-ftse-global-all-cap-index-fund-gbp-acc][0].navPrice.value

does that look right?

ivory delta
peak juniper
#

oh I see, haha, thanks 😄

#

ok so if the above works and yields the result I kind of want but with "168" and not just 168, do I need a template sensor in ADDITION to the restful sensor or instead?

ivory delta
#

If you just want everything between the quotes, use split() and pick the element you want from the resulting list. This should do the trick:
{{ value.split('"')[1] }}

#

Breaks your value into a list of values that were separated by double quotes. Takes the second part (not the empty value before the first quotes or after the last one).

peak juniper
#

Sorry, I'm relatively new to this and trying to hobble things together. You're saying then that I need:

sensor:
  - platform: rest
    resource: https://api.vanguard.com/rs/gre/gra/1.7.0/datasets/urd-product-details?path=[id=vanguard-ftse-global-all-cap-index-fund-gbp-acc][0].navPrice.value
    value_template: {{ value.split('"')[1] }}
#

?

ivory delta
#

Sure, except you need to either wrap your template in quotes or make it a multi-line template.

#

In this case, despite it being a simple one-liner, I'd go with the latter... you already have a mix of single and double quotes, so you can't wrap it with either without escape characters 😄

#
    {{ value.split('"')[1] }}```
peak juniper
#

template editor is saying: "UndefinedError: 'value' is undefined"

#

but I wonder if that's because it doesn't show restful sensors properly?

ivory delta
#

Where? Dev Tools? It doesn't know about the integration there.

peak juniper
#

yeah, that's what I thought. I'll just chuck it in and reload

#

I appreciate the help. I always feel like I've got 80% of the picture with HA and that last little bit seems impossible to me 😄

ivory delta
#

There's a lot to learn. I've been doing this for a year and I'm a software engineer, yet there's still stuff I take a while to pick up.

peak juniper
#

haha as an English teacher that makes me feel a bit better about my lack of expertise 😄

ivory delta
#

It's all just syntax. You just have a different corpus to pick up now 😉

inner mesa
#

and learn new words like "elif"

ivory delta
#

That's just 'file' backwards smart

peak juniper
#

haha yeah exactly...I've got that one in the ol' bank already

#

I have a collection of various different formatting language and ways of doing things but when I have to do something new it's a bit of a wall, especially if nobody has tried to do the thing I'm doing before

#

your suggestion worked a charm, btw, I've got two sensors now using that API and formatted without the " "

#

thanks so much!

#

another completely useless thing in my HA instance 😄

sour acorn
#

im trying to create a date +64 days from a input_datetime. I was trying to use a templaye sensor for the date value (not sure if thats best), but i dont know what im doing. I thought something like this could work?

- platform: template
  sensors:
    room2_end:
      value_template: '{{ ((states.input_datetime.room2_start_day.state) + (64) ) }}'
      unit_of_measurement: 'Date'
inner mesa
#

states('input_datetime.room2_start_day') + timedelta(days=64)

sour acorn
#

awsome! let me try that

ivory delta
#

I'm not sure you want this though:
unit_of_measurement: 'Date'
It's not a graphable number if it's just a date.

inner mesa
#

I also think that the state needs to be turned into a datetime

#

and as tom_l says in that thread:

#

timedelta() has turned out to be much less useful than I thought it would be because my datetime helpers aren’t datetime objects.

sour acorn
#

timedelta is getting me on the right track

inner mesa
#

that thread has a solution

sour acorn
#

i really green here

inner mesa
#

it would be cool if an input_datetime had an attribute that was equal to its state, but retained the datetime type

ivory delta
#

I smell a feature request.

#

It's a good idea, get it logged 😄

dreamy sinew
#
attrs["native_type"] = self._current_datetime
#

something like that could work

inner mesa
#

right, I think it would be trivial to add

sour acorn
#

I'm still struggling with how to format this

    room2_end:
      value_template: '{{ strptime(states("input_datetime.room2_start_day"), "%Y-%m-%d %H:%M:%S") + timedelta(days=64) }}'
      unit_of_measurement: 'Date'

TemplateError('TypeError: can only concatenate str (not "datetime.timedelta") to str') while processing template 'Template("{{ strptime(states("input_datetime.room2_start_day"), "%Y-%m-%d %H:%M:%S") + timedelta(days=64) }}")' for attribute '_state' in entity 'sensor.room2_end'
5:02:10 PM – (ERROR) Template
Error while processing template: Template("{{ strptime(states("input_datetime.room2_start_day"), "%Y-%m-%d %H:%M:%S") + timedelta(days=64) }}")
5:02:10 PM – (ERROR) helpers/template.py
inner mesa
dreamy sinew
#

seems like your strptime failed to parse so it returned the original string

inner mesa
#

lol, case in point 🙂

dreamy sinew
#

yup, pretty much

#

too bad its a private var

inner mesa
sour acorn
#

I voted it

#

any idea whats wrong with my formatting, or is there a different approach?

dreamy sinew
#

what is the output of {{ states("input_datetime.room2_start_day") }} ?

inner mesa
#

this alternative (using the timestamp) may be easier to handle:

#

`{{ state_attr('input_datetime.fridge_1_filter_changedate', 'timestamp')

  • timedelta(days=change_days).seconds | timestamp_local() }}`
#

it always takes me a bunch of trial-and-error to get the date/time formatting right

dreamy sinew
#

hmm, that should be right. this is what its using for datetime '%Y-%m-%d %H:%M:%S'

#

gotta verify against the actual output though

sour acorn
#
editable: true
has_date: true
has_time: false
year: 2021
month: 3
day: 15
timestamp: 1615791600
friendly_name: Room2 Start Day
dreamy sinew
#

ah, that's why

#
has_time: false
sour acorn
#

ok i really dont want to add time to it

#

can i remove "%H:%M:%S" ?

dreamy sinew
#

can try it

inner mesa
#

yes

#

try it in devtools -> Templates

sour acorn
#

ok rebooting now, i think i tried that before, but maybe i had something else incorrect

#

that worked!

#

thanks @inner mesa & @dreamy sinew

plain zinc
#

states.sun.sun.attributes.next_setting returns a string value of the time in UTC, I want to do time operations on it, do I really need to strptime on it and construct the format to parse it with?

There has to be an easier way to do this?

ivory delta
#

as_timestamp() converts datetime object or string to UNIX timestamp. This function also be used as a filter.

plain zinc
# ivory delta > as_timestamp() converts datetime object or string to UNIX timestamp. This func...

Yes but that causes me another issue, I'm trying to do datetime operations and that returns a float.

{{ as_timestamp(states.sun.sun.attributes.next_setting) - now()}} causes TypeError: unsupported operand type(s) for -: 'float' and 'datetime.datetime' instead of a string error.

could make now() a timestamp but then I still have to convert back, just seems like a big back and forth. I just want to make sure I"m not missing the simple way.

#

I’m happy to use strptime. I just don’t want to miss a simpler way possibly

inner mesa
#

It seems silly and in my humble opinion you should file an issue. There’s no reason for it to be a string

ivory delta
#

Nah, just upvote the existing feature request. It's not a bug.

plain zinc
#

Yeah I’ll poke and maybe just send a patch.

ivory delta
#

It's even listed in the section of the page I linked you to.

plain zinc
#

But does timedelta take strings :p

#

I’ll poke. Just seems silly. I’ll see how hard it is to just patch the sun object and send a PR

inner mesa
ivory delta
#

Gotcha

plain zinc
#

I'll bring it up in the dev channel but to round this off it does call a string type return return { <snip> STATE_ATTR_NEXT_RISING: self.next_rising.isoformat(), STATE_ATTR_NEXT_SETTING: self.next_setting.isoformat(), <snip> }

#

Fix should be simple but it'll break LOTS

#

so possibly just add additional attributes.

inner mesa
#

Since datetime types are displayed properly, I don’t know why it would be converted to a string

plain zinc
#

isoformat seems to return a string to me looking at the python builtin function itself. Anywho, I'll dig further.

#

definitely returns a string 😦 >>> type(datetime.now().isoformat()) <class 'str'>

small hatch
ashen isle
#

hi my friends! im struggleing with yaml i guess. this script: https://www.codepile.net/pile/JKbyYrZV
results in this error: Error. Url: http://192.168.1.220/light/0?brightness=0. Status code 400. Payload: None
as variables are involved its tricky to debug the yaml synatx with the dev tool. can you help me ?

inner mesa
#

400 is "bad request", so what happens if you send that via POST with curl or Postman or some other tool?

#

is that what you expect ti to send?

ashen isle
ashen isle
ivory delta
#

Share the REST command.

inner mesa
#

you can't nest {{ }} like that

#

they're just variables

#

rather than '{{ min_bright }}' | float, just do min_bright|float

#

you can just set the variables in devtools -> Templates and test your template

ashen isle
#

how to set variables in dev tools ?

inner mesa
#
{% set ip_address=xxxx %}
ashen isle
#

ok thx

inner mesa
#

there's an example right in the demo template text

ivory delta
#

What am I missing? I don't see nested templates.

inner mesa
#
     brightness_value: >
        {{ (('{{ min_bright }}' | float) +
        (state_attr('switch.adaptive_lighting_general', 'brightness_pct') |
        float )*0.01*(('{{ max_bright }}' | float) - ('{{ min_bright }}' |
        float) )) | int }}
ivory delta
#

The HTTP method is important. It defaults to GET and you likely need POST. But since you haven't tested that... 🤷‍♂️

inner mesa
#

all kinds of weirdness going on there

#

and the brightness appeared to be the problem

ashen isle
inner mesa
#

first step is to test the command and get it working, second is to integrate it into HA

#

curl is quite straightforward

ivory delta
#

Built things incrementally. Don't throw 10 things together at once and hope it works.

#

Postman is even more straightforward 😄

ashen isle
#

i appreaciate your help guys thx

#

its working with, as no more nested {{}} are used ... now i will try (once again) to dig intu GET and POST 😀

dusty hawk
#

I just figured out that a decimal number in a value_template: requires a leading zero to parse successfully. Version: core-2021.4.4 The log message was that somewhere in the 1,202 line automations.yaml file a value_template: had an unexpected "." Yes, I'd made several changes at once...
This is invalid in an automation template condition:
value_template: "{{ (states('sensor.sample') | float) >= .15 }}"
But this is valid:
value_template: "{{ (states('sensor.sample') | float) >= 0.15 }}"

zinc leaf
#

Got a few questions on FB about conversions (Metric > Imperial) maybe a good idea to put some examples on the HA intergration page ?

silent barnBOT
#

@zinc leaf To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.

ivory delta
#

Also, feel free to delete the duplicate 😉

zinc leaf
#

yeah I know i ff-ed up

#

``sensor:

  • platform: template
    sensors:
    bimmer_range:
    friendly_name: "Bimmer Range"
    unit_of_measurement: "miles"
    value_template: "{{ (states('sensor.i3_rex_remaining_range_electric') | float / 1.6) | round(2) }}"
    ``
ivory delta
#

It's okay. Just tidy up after yourself. You can right click your posts to edit instead of removing them completely.

#

3 backticks at each end, not one 🙂

zinc leaf
#

i forgot it was backticks... thought it was''

ivory delta
#

Single backticks are good for inline code but multiline code is better with triple backticks:

some:
  yaml: thing```
zinc leaf
#

But what I said ... would be a nice addition

#

Som people have something to base there conversions on

#

some*

nocturne chasm
#

This information is all over the forums and anyone can edit the docs.

zinc leaf
#

@nocturne chasm : but somehow people are not finding it

ivory delta
#

There are many, many things that could be written about templates. It's impossible to document every variation for such a versatile templating engine.

#

If you think an example is worth including in the docs, include it.

#

anyone can edit the docs.

dreamy sinew
#

Note that HA allows you to pick your measurement choice for the whole system. If you try to change it for a one off sensor it'll just get converted back

ivory delta
#

There's that too 😄

nocturne chasm
karmic oar
#

Are there any better tools for pulling json values from a restful sensor that don't include restart home assistant every time I make the slightest change?

ivory delta
#

Not really. Changes to integrations usually require a restart - unless it's one of the categories listed in the config page.

karmic oar
#

Is there a way to parse multiple lists? My JSON is formatted [{"val1":"value1","val2":"value2"},{"val1":"value1","val2":"value2"}] and I haven't found a way to have a rest sensor bring that data onboard in a usable form. The rest of my sensors work, but the JSON is formatted differently than this one.

inner mesa
#

That’s one list containing 2 dicts. What are you trying to get out of it?

karmic oar
#

Would like to pull value2 from each dict. Below is how I've tried to access it:

- platform: rest
  resource: #api url
  name: data
  scan_interval: 60
  value_template: "{{ value_json.state }}"
#  json_attributes_path: "$"
  json_attributes:
    - 0
    - 1
#

I thought I would access them by $.0.val1, but the data doesn't show up in the sensor for me to access attributes

inner mesa
#

I don’t have much experience with it, but you should be able to experiment with jq

karmic oar
#

I have tried so many variations of the value template to get something out of this. I'm not even sure I can access data from different dicts in one restful sensor

inner mesa
#

Maybe not. A sensor can only return a single value

karmic oar
#

Kind of. Typically you'll pull in a dict and that restful sensor will have mulitple attributes that can be accessed, from which you can create more sensors or reference that data directly.

inner mesa
#

Ah, ok

small hazel
#

I'm trying to create a template sensor that will check if it is between the hours of 8am and 10pm and also that a user is home and has been home for at least 10 minutes. I'm hoping to check the value of this sensor for sending reminders of things that need to be done around the house. I only want the notifications during these hours and I don't want them right when I walk in the door.

#

I've got now().hour > 7 and now().hour < 22. I'm wondering how I would make it's only true if person.name is home for x minutes

fossil venture
#

That sounds like it could be done a lot easier with an automation than a sensor.

small hazel
#

and just update a binary_sensor?

#

(as_timestamp(now()) - as_timestamp(states.person.person_name.last_changed)) / 60 > 10 and now().hour > 7 and now().hour < 22

thorny snow
#

I could use some help templating the max temp forecast out of the weather home entety.
when I do {{ state_attr('weather.home', 'forecast' ) }} I get the json formated data like

[{'condition': 'cloudy', ...., 'temperature': 13.0, 'templow': 2.4,}]
``` but I have a hard time to filter out the `forecast[0].temperature` value
ivory delta
#

A hard time how? What have you tried?

thorny snow
#

things like this {{ state_attr('weather.home', 'forecast[0].temperature') }}

#

I tryed it that way already but it failed me 😆 probably added a filter.
this works now
{{state_attr('weather.home', 'forecast')[0].temperature }}
Thaks for jumping in mono

gray quail
#

Is it possible to get the in-/external_url of homeassistant to show in a template? I couldn't find something like {{ homeassistant.external_url }}

ivory delta
#

Not that I know of. Templates are usually used for things that change though - how often are you expecting your URL's to change? 🤔

gray quail
#

Not at all. But was curious if it was possible. I was looking into sending the correct url if you are home/not-home

fossil venture
#

You can get the public ip with the myip integration "{{ states('sensor.myip') }}"

gray quail
#

Thanks Tom for the idea

fossil venture
gray quail
#

My problem is a non-issue, as I'm always using Wireguard. so it's always local...

fossil venture
#

Ah, ok.

trail estuary
#

I have a bunch of sensors from my washing machine, on for each program avilable, indicating which program is active. Can I create a template sensor to check which of these sensors are on? Only one sensor can be on at any given time....

inner mesa
#

What do you want the sensor’s state to be?

#

But yes, you can use a template to change the state based on which sensor is active

ivory delta
#

Are they all binary sensors?

#

If so, you don't even need a template... just make a group.

trail estuary
#

Actually, I just noticed they are not sensors, but switches...

#

But I suppose the general rule still applies?

trail estuary
inner mesa
#

Entity IDs are not dynamic

trail estuary
#

No. I was hoping the state of the template sensor could be the entity_id of the switch that was currently on?

#

I was thinking the template could iterate over the switches and return only the one that had state on...?

inner mesa
#

Your template can return whatever string you want

#

Sure

trail estuary
#

How do I approach filtering the switches based on state?

#

They all have predictable entity_ids, like switch.wau28p_program_<program_name>.

inner mesa
#
{% for i in states.switch if i.object_id.startswith('family_room') %}
    {{ i.entity_id if is_state(i.entity_id, 'on') }}
{% endfor %}
#

it will get easier in the next HA release with search/match Jinja tests

trail estuary
#

That sounds brilliant! 😄

#

Thanks! I will give that a try! 🙂

inner mesa
#
    test_sensor:
      value_template: >-
        {%- for i in states.switch if i.object_id.startswith('family_room') -%}
            {{ i.entity_id if is_state(i.entity_id, 'on') }}
        {%- endfor -%}
trail estuary
#

Perfect! Just the thing I was hoping to acheive! 😘

inner mesa
#

you probably need to guard it for when none are on

#

{{ states.switch | selectattr('entity_id', 'in', ['switch.family_room_watch_roku', 'switch.family_room_watch_shield'])|selectattr('state', '==', 'on')|map(attribute='entity_id')|first}}

trail estuary
#

The only time that will happen is when the washer is off....

inner mesa
#

well, that happens, right?

#

or are you constantly washing something?

trail estuary
#

What are the consequences?

inner mesa
#

it will fail because the template will be empty

#

boo. "None" is now a special case

#
    test_sensor:
      value_template: >-
        {% set entities=states.switch | selectattr('entity_id', 'in', ['switch.family_room_watch_roku', 'switch.family_room_watch_shield'])|selectattr('state', '==', 'on')|map(attribute='entity_id')|list%}
        {{ entities|first if entities|length != 0 else "Not Running" }}
#

works

trail estuary
#

Let me try to adapt that! 🙂

inner mesa
#

filtering based on entity_id will get much easier in 2021.5 and you won't need to list all the entities individually. Or you can adapt the for loop from earlier

trail estuary
#

You know what... I will wait for the beta and try this then. I have a basic working thing, thanks to you! Guarding it for edge-cases can wait...

#

🙂

#

I have what I need for now:

tough lily
#

How do I display a timestamp as a time in hh:mm am/pm format? I'm trying to display the time my shades will close which is sunset + 15 minutes so this gets me the correct timestamp, I just can't figure out how to display it: {{ as_timestamp(state_attr('sun.sun', 'next_setting')) + 900 }}

#

I've tried | datetimeformat, | timestamp_to_time, and |strftime with no luck

inner mesa
#

you want |timestamp_custom

tough lily
#

thank you!

inner mesa
#

{{ as_timestamp(now())|timestamp_custom("%I:%M %p") }}

tough lily
#

oh that's perfect, I'm so happy I'm finally getting my frontend cleaned up for tablets after months of putting it off

unique harbor
#

Hi y'all! Anyone able to help me figuring out the right template for a condition for which user scanned a NFC-tag?

#

I have the path syntax to the user_ID as $.context.user_id, but can't figure out how to point to that in a template. I was thinking this would be right: {% if trigger.event.data["context"]["user_id"] == f644f45672e54aaf93d4d504c7baf9cf %}

#

Nevermind, got it, the template was trigger.event.context["user_id"] instead, the new automation tracer is great

tough lily
#

So I've got a template on a markdown card to display "Lights:" + the name of any rooms with lights on. The way I have it now I have to iterate states.light twice: once to get a count of rooms with lights on since I don't display the "Lights:" header if there are none, and again to list the rooms. Is there a cleaner way to do this? This is my first real stab at templating: https://zerobin.net/?c2b2b1b7dea2d409#tGz5HElQDfS6tGzm6UlqL+uIPu4BgecM/2bMDVj+8uM=

#

oh, I thought about adding them all to a list, then using the list's count to decide if the header should show, then finally displaying the list, but I couldn't figure out how to append items to the list

inner mesa
#

Yeah, you can’t append like that

tough lily
#

I did get inspiration from that, but unfortunately I needed to filter my light entities on those with entity_ids ending in "all" and afaik I can't do that with selectattr

inner mesa
#

Or selectattr, but yeah. Next HA build

tough lily
#

kk, I'll make a cleanup pass then, thanks again

acoustic raptor
#

hi guys, based on my limited googling skills, templates seems to be the place if want to store a variable?

inner mesa
#

Not really

#

Look at the input_* helpers, like input_number

#

Templates have variables, and scripts can define variables for use within the script, but they all have limited scope

acoustic raptor
#

i want to store a variable for use as a conditional in automations

#

where can i find input_ helpers?

acoustic raptor
#

i just add it myself?

inner mesa
#

You follow the instructions for what you need

acoustic raptor
#

okay. cant be done via UI right?

inner mesa
#

As per the instructions

#

All the helpers can

acoustic raptor
#

ahh

#

found it

#

thanks

#

still not too familar with the system

nimble copper
#

Is there a way to set a backup value if the sensor is unavailable in this template? I thought default() was the answer but doesn't seem to work as expected

as_timestamp(states(''sensor.master_bedroom_clock_alarms''))|timestamp_custom(''%H:%M'')

#

{{ as_timestamp('unavailable')|timestamp_custom('%H:%M')|default('07:10') }}

This is what I thought should work, but the template returns None

#

Scrap that, I worked it out:

{{ as_timestamp(states('sensor.master_bedroom_clock_alarms'))|timestamp_custom('%H:%M') or '07:10' }}

grim flicker
#

Can someone tell me why:

{% set live = states('sensor.opwekken_live') | float %}
{% set usage = states('sensor.verbruik_kw') | float %}
{% set kw = 1000 %}
{{ (live - usage) * kw | round(0) }}

sometimes still gives a value of XXXX,9999999998 While its rounded to 0?

unreal merlin
#

howdy 🙂

#

is there an easy way to get time spent in a previous state w/o saving that data to an input field?

#

for example: trigger: door sensor closes, and the condition for the action would need to be "if it was open for less than 10 minutes"

unreal merlin
grim flicker
#

@unreal merlin thanks that fixed it!

trail estuary
#

I have a sensor that has a timestamp as state. This is the estimated time when the washing machine is finished. How do I calculate the time between now and that state?

#

Currently the sensor has the state 2021-04-26T11:02:57.515786+00:00

nimble copper
loud otter
#

Hi all I was wondering if someone can help me with a template (if it is possible to create a template to achieve what I want to achieve). Basically my goal is to broadcast messages dinamically, based on media_player status (!= playing) and binary_sensor status (only for device_class = motion). I found a way to greate a group for media players what are not playing and of course the same can be done for binary_sensor in on status. But how to combine them? Can somehow area_id be useful? Every media_player and binary_sensor have a area_id attribute in my config. I'm not that good in templating so I definitely ask your support to understand if this is possible and how to do that. Thank you in advance

steep kiln
#

I got a template sensor for an esp32 with a co2-sensor, rewriting the value with changing ppm levels works fine but if the sensor is offline the last value is still displayed.. is the else statement not valid when the esp is offline (== the sensor value is unavailable)? --> https://nopaste.ml/?l=yaml#XQAAAQDaAQAAAAAAAAAQapmMJu4e3iJbP3A2mxXTBWnOwH7gw2TDJqdwlA9QkUIQQFPf7lMhaKPDyk6B4LgvuB4q1dQ4Gkc119tSIlpygAveQG9Hzzh73qvIdA7sEW4b68TXiooFouOZQGjN/p7/iQSMpQgyljdgBJANNBjNBQIKQzOzgFXYK8s1ahoQKC8W3Bxz1Ztd83c/QHVUBlAiiZH4ZT//w3I7Zw==

#

dang what a huge nopaste url, sry

steep kiln
#

ah and the value above 1000 does not work too :/

steep kiln
crimson quarry
#

I have a template fan (Inovelli LZW36 Light+Fan controller shows up as 2 light levels, so I use a template fan to create an actual fan and map speeds) that I need to convert from the old 'Speed' templates to the new 'Percentage' templates. Anyone here have a working example of a template fan that I can reference? Thanks.

modern hearth
#

I am doing a template sensor, is there a way to make sure the system sees the state parameter as Fahrenheit degrees?

      ground_floor_zone_temperature:
        friendly_name: "Ground Floor Temperature"
        unit_of_measurement: "??????"
        value_template: "{{ state_attr('climate.ground_floor', 'current_temperature') }}" ```  whatever i put in the unit of measurement just seems to be a text label?  i think i have done something wrong?
ivory delta
modern hearth
#

cool that sets the icon however the text in the template docs says "Sets the class of the device, changing the device state and icon that is displayed on the UI (see below). It does not set the unit_of_measurement."

#

is unit of measurement just temperature?

ivory delta
#

The unit of measurement is whatever unit you want displayed...

#

If you want '°F', then use that.

modern hearth
#

oh, lol, i didn't think it could be arbitrary unit

#

I have another sensor that reports in deg C but displays in deg F - so i assumed there was way to make sure the system could cope with tmperature display units being diff from underlying data, i can live with this solution 🙂

sour acorn
#

im having trouble formating this, im just trying to subtract 200 from a input_number for a trigger and condition

  trigger:
  - platform: numeric_state
    entity_id: sensor.2_co2_sensor
    below: "{{ states('input_number.2_co2_on') | float - 200 }}"
  condition:
  - condition: numeric_state
    entity_id: sensor.2_co2_sensor
    below: "{{ states('input_number.2_co2_on') | float - 200 }}"
inner mesa
#

You can’t use templates there

#

You could use template triggers to accomplish that

#

What’s the point of the trigger and the condition?

sour acorn
#

i guess it could just be a trigger

#

sorry no point in the condition

inner mesa
#

I puzzled over that for a while trying to figure out what value it added 🙂

#

You could probably also use a value_template to adjust the sensor value prior to the comparison with the input_number

sour acorn
#

i have a input set point for a co2 sensor.
i would like to it turn on a fan at -200 set point, and turn off at set point

inner mesa
#

Right

#

So either a template trigger or use a value_template

sour acorn
#

OMG, i was having nothing but issues

#

i thing maybe it should be noted somewhere, but preferable not allowed to happen ot fixed

#

you can NOT have a input_number start with a number.. ie "input_number.2_coxx_on"

#

the "2" becomes a problem

inner mesa
#

Yeah, that’s a limitation of entity names

#

Sorry, didn’t think about that earlier

sour acorn
#

well if you make a helper with the name "1 myinputnumber" it males the id with the number

#

not your fault

#

i just could not for the life of me figure out what i had wrong

#

3 hrs for one line of code

#

lol

#

i was trying to set a variables within... evey which way didnt work until i changed the input id... and me being a hack at best didnt help

#

but thanks for your help rob

rare panther
#

for the below dict, I need to retrieve the key and value which has 'tracked' in key. What filters I could use?

  "22": "Just Missed - 6 min, 44 sec - 20 min, 31 sec",
  "24_tracked": "9 min, 6 sec - 17 min, 53 sec - 29 min, 53 sec",
  "43": "5 min, 47 sec - 10 min, 54 sec - 39 min, 18 sec"
}```
#

I tried the following so far {{ states.sensor.bus_stop.attributes.items() }} and it returns me
dict_items( [('22', 'Just Missed - 6 min, 44 sec - 20 min, 31 sec'), ('24_tracked', '9 min, 6 sec - 17 min, 53 sec - 29 min, 53 sec'), ('43', '5 min, 47 sec - 10 min, 54 sec - 39 min, 18 sec')] )

#

How can I use the filters to retrieve the key "24_tracked" and its value "9 min, ...." ?

fossil venture
#

Does the number in front of 'tracked' change?

#

If not: {{ state_att('sensor.bus_stop', 'items()')["24_tracked"] }}

rare panther
#

yes it changes, and thatswhy was looking to see what best we can use to filter out all "*tracked" values

#

btw the {{ state_attr('sensor.bus_stop', 'items()') }} returns None...so adding ["24... does not work

solemn dirge
#

How can I convert a list ['Item1', 'Item2'] into somethin like Item1, Item2?
I guess I need to use a for-loop but I can't seem to access the variable outside of the loop.

dreamy sinew
#

you don't need to use items()

#

state_attr('sensor.bus_stop', '24_tracked')

fossil venture
#

Ugh. Sorry I thought that was the attribute.

loud otter
#

Hi all I was wondering if someone can help me with a template (if it is possible to create a template to achieve what I want to achieve). Basically my goal is to broadcast messages dinamically, based on media_player status (!= playing) and binary_sensor status (only for device_class = motion). I found a way to greate a group for media players what are not playing and of course the same can be done for binary_sensor in on status. But how to combine them? Can somehow area_id be useful? Every media_player and binary_sensor have a area_id attribute in my config. I'm not that good in templating so I definitely ask your support to understand if this is possible and how to do that. Thank you in advance

glad moth
#

Hello, I am trying to create a binary sensor where the sensor will turn on or off if one of the windows is opened. This worked when I had two devices but when I added a third it stopped working. Does anyone know what is wrong with this?```binary_sensor:

  • platform: template
    sensors:
    windows:
    friendly_name: "Windows Status"
    device_class: window
    value_template: >-
    {{ is_state('binary_sensor.office_window_south_status', 'on')
    or is_state('binary_sensor.office_window_north_status', 'on')
    or is_state('binary_sensor.porch_door_status', 'on')
    }}
rare panther
#

I know the supplied data from source is a mess, but this is what I need to work with. Had it been a proper Json, it would be so easy

dreamy sinew
#
{% set windows = ['binary_sensor.office_window_south_status', 'binary_sensor.office_window_north_status', 'binary_sensor.porch_door_status'] %}
{{ states.binary_sensor |selectattr('entity_id', 'in', windows)|selectattr('state', 'eq', 'on')|list > 0 }}```
#

@rare panther if its that arbitrary you'll need to wait for the regex filters