#templates-archived

1 messages · Page 107 of 1

arctic sorrel
#

And?

thorny snow
#

it still wont work

#

i fixed the errors

#
data:
  power: true
  transition: '{{ states("input_text.fade_time")|float }}'
  color_name: red
  brightness_pct: '{{ states("input_number.end_brightness")|int }}'
entity_id: light.ceiling```
arctic sorrel
#

Then you now have new errors...

thorny snow
#

i wont update the light

oak kiln
#

The template change in 0.117 broke some things for me.

I've had an mqtt.publish with a data_template which returned a json string. Now it's returning something different I guess

#

how do I cast that to string?

inner mesa
balmy wedge
#

Hello everyone

#

I'm trying to build a template to dim all the lights that are on

#

It's a bit ugly - it has the first one hard-coded because it doesn't want to mess with commas, for one.

#

Is there a better way of saying "all the lights that are on in the bedroom" ?

dapper aurora
#

Any idea why this is still evaluating to false? value_template: "{{states('sensor.date') and now().weekday() in (0,1,2,3,4)}}"

inner mesa
#

@balmy wedge if they're part of a group, yes

balmy wedge
#

I have them in an area_id if that works, otherwise I can build a group, sure

inner mesa
#

not really

#

areas aren't helpful

balmy wedge
#

So I've noticed 🙂

#

How would you do it with a group?

inner mesa
#

@dapper aurora What do you get with {{ now().weekday() }}?

dapper aurora
#

ah shoot i get 6... what day of the week does it start w/ ?

#

nevermind

#

thanks!

inner mesa
#

@balmy wedge This outputs a comma-separated list of entities in a group with a specific state:

#

{{ expand('group.fr') | selectattr('state', 'equalto', 'off')|map(attribute="entity_id")|join(',') }}

balmy wedge
#

Oh, brilliant!

#

Thank you

#

It's a pity areas aren't more useful, or don't automatically create an alias group

crisp storm
#

i am trying to do something very similar to stereo, except I would like to select all circadian lighting switches: states.switch | selectattr('object_id', 'startswith', 'circadian_lighting') no test named startswith I can't seem to find a test to accomplish this

inner mesa
#

something like this perhaps:

#
{% for i in states.switch if i.entity_id.startswith(‘foo’) %}
    - {{ i.entity_id }}
{% endfor %}
crisp storm
#

ooo

#

i didn't realize i could use templates like that in an automation, i thought it would need to be a string join in the entity_id field

#
data: 
  entity_id:
    {% for i in states.switch if i.object_id.startswith('circadian_lighting') %}- {{ i.entity_id }}
    {% endfor %}```  Invalid data for call_service at pos 1: not a valid value for dictionary value @ data['entity_id']
#

looks perfect in the dev tool template editor.... guessing that's not the right syntax though

inner mesa
#

you would need entity_id: >-

balmy wedge
#

Hmm, the template expands in the 'template' tab in the dev tools, but I can't figure out how to pass that to lights.turn_on

inner mesa
#

and proper indentation

balmy wedge
#

Oh, is that an answer for us both? 🙂

inner mesa
#
  entity_id: >-
    {% for i in states.switch if i.object_id.startswith('circadian_lighting') %}
      - {{ i.entity_id }}
    {% endfor %}
#

could be. what are you doing?

balmy wedge
#
entity_id: >- 
 {{ expand('group.bedroom') | selectattr('state', 'equalto', 'on')|map(attribute='entity_id')|join(',')  }}
inner mesa
#

if it doesn't like the list, you could do something like this:

#
entity_id: >-
  {%- for i in states.switch if i.object_id.startswith('fr_') -%}
    {{ i.entity_id }}
    {%- if not loop.last %},{%endif%}
  {%- endfor %}
#

@balmy wedge What does it do?

balmy wedge
#

"Failed to call service light/turn_on. not a valid value for dictionary value @ data['entity_id']"

inner mesa
#

show the whole thing

balmy wedge
#

Oh, I'm just calling it from the dev tools > service thing

inner mesa
#

that has issues with templates

balmy wedge
#

Service: light.turn_on, and in the field below, that code

#

Ahh

#

That's good to know

#

It's not doing any better in the automation I'm trying to build

crisp storm
#

thanks for trying robc, but neither of those variants worked

balmy wedge
#
service: light.turn_on
entity_id: >- 
 {{ expand('group.bedroom') | selectattr('state', 'equalto', 'on')|map(attribute='entity_id')|join(',')  }}
transition: 1
brightness_step_pct: -30
inner mesa
#

you need to have a data: block

balmy wedge
#

Ah, I tried that and that didn't work either. Let me try again.

inner mesa
balmy wedge
#

Ah, that's excellent

inner mesa
#

you'll have a problem if there are no matches, though

balmy wedge
#

Then it just won't dim, since the lights are off

#

Hurrah! That worked!

inner mesa
#

easy enough to fix by putting a condition: block above it that checks if the group is on, meaning that any of the entities are on

#

no, it will produce an empty list, which will make the service sad

#

so you need to make sure that you don't call it if it will be empty

crisp storm
#
data:
  entity_id: "{%- for i in states.switch if i.object_id.startswith('circadian_lighting') -%}{{ i.entity_id }}{%- if not loop.last %},{%endif%}{% endfor %}"``` got it working!
#

doesn't work if entity_id is top level but does work if it's part of data

inner mesa
#

yes, that's correct

crisp storm
#

if you specify the actual string directly it works as part of the top-level, but it appears the template is not expanded in that position

#

either way! working! thanks

inner mesa
#

correct

#

entity_id: is one of the few things that can live outside data:, but it's more limited that way

balmy wedge
#

So I just add a condition for state: group.bedroom: on ?

inner mesa
#

with proper syntax, yes

balmy wedge
#
    entity_id: group.bedroom
    state: 'on'```
inner mesa
#
      - condition: state
        entity_id: group.dr
        state: 'on'
balmy wedge
#

Perfect 🙂

inner mesa
#

yes, like that 🙂

waxen rune
#

@balmy wedge would you mind sharing the complete automation? I might need it in the future 🙂

sonic nimbus
#

hi, Im looking for dynamic turning off all of my automations except a few..

#

something like automations.*

#

with a wild card, but after that something like ```except:

  • automations.automation33
  • automations.automation34
  • automations.automation35```
ivory delta
#

I'm not sure something like that exists. What are you trying to do?

#

Generally, if you're turning automations on and off, your logic isn't good enough somewhere else.

sonic nimbus
#

Im basically trying to implement "Guest mode"

#

or "Vacation mode"..

#

input_boolean, when its on

ivory delta
#

So have input booleans for those modes and add those as conditions in automations.

sonic nimbus
#

to shutdown some automations

#

so if I understand you right, in each automation which I want to control from toggle boolean

#

I need to add false condition for that bool

#

?

#

in each automation? :)_

#

🙂

ivory delta
#

In each one that cares about 'guest mode' or 'vacation mode', yes. But that's a discussion for #automations-archived

sonic nimbus
#

yes ofc, but I was thinking that it could be solved via templates..

ivory delta
#

A template just returns a value. It doesn't control anything.

#

Templates won't turn off automations.

sonic nimbus
#

oh, I see

somber island
#

{% set alert = false %} {% for forecast in state_attr('weather.farm', 'forecast') %} {%- if forecast.temperature | float > states('input_number.bee_forecast_high') | float %} {% alert = true %} {% endif -%} {%- endfor %} {{ alert }}

trying to make a alert if any forecast days have temp higher then a input_number i set, how do i return a true value ?

#

is the template checking for True/False string or a boolean type?

inner mesa
#

Try True/False

somber island
#

TemplateSyntaxError: Encountered unknown tag 'alert'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.

#

im not sure how to change the variable value inside from inside the loop

inner mesa
#

oh, yeah, you need to use a namespace

#

and set you need set alert = True

somber island
#

okay

#

thanks worked, is True a Boolean or string? also will this namespace only be around while the binary_sensor runs? like if where to use same namespace in a different template will i have access to it?

inner mesa
#

True is a boolean

#

and everything is template-scope

#

so just that template

somber island
#

ok thanks a lot

dreamy sinew
#
{{ True if state_attr('weather.farm', 'forecast')|map('float')|select("gt", states('input_number.bee_forecast_high')|float)|list else False }}
#

masterpiece 😄

inner mesa
#

it was bound to happen 🙂

dreamy sinew
#

eh i probably wouldn't use this

#

was fun to try though

inner mesa
#

lemme know when you finish the complete beekeeper package 🙂

dreamy sinew
#

wazzat?

inner mesa
#

presumably this is just one piece of a bigger puzzle

dreamy sinew
#

oh, prolly

inner mesa
#

it's fun to see the varied things that people are trying to control. Lights/motion sensors are so played out

somber island
#

yea basically its my bee storage, have to manage temperature, humidity and co2 in order to keep as many hives alive by spring HA is helping automate it a lot

silent barnBOT
harsh anchor
#

I love you bot for taking the entire message to pastebin 💗

#

it's been a couple days I'm banging my head on this, still can't make it work
I have this sensor sensor.qnapups_battery_runtime that gets the battery runtime in seconds

I then create a template like so
https://paste.ubuntu.com/p/qpRrrG6ZZ9/
but it doesn't work
tried many permutations of the value template, but no joy
what am I missing?

buoyant pine
#
{{ states('sensor.qnapups_battery_runtime') | float(0)  / 60 }}
#

Also the bot did that because you forgot about the rules 😛

silent barnBOT
#

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.

harsh anchor
#

@buoyant pine was it more than 15 lines? have to start writing messages in my code editor lol 😅

buoyant pine
#

The entire message was (granted, you were just barely over)

brisk temple
#

Will this work as a trigger or do I need to add == true at the end

#
    trigger: 
      - platform: template
        value_template: "{{state_attr('sensor.riverrace', 'clan')['finishTime'] is defined }}"
#

i only want it when true, so ya i probably do

dreamy sinew
#

Output of that should be true/false already

thorny snow
#

why wont this work?delay: '{{ states(''input_number.off_delay'') | multiply(60) | int }}' power: false transition: 10 color_name: orange brightness_pct: 1 its in a script btw

deft timber
#

I would replace the double simple quotes by double quotes

thorny snow
#

ok

dreamy sinew
#

that might be doing string math

#

ah no, |multiply() is smart enough to cover that

thorny snow
coarse tiger
#

1 space too much on that delay element

thorny snow
#

it still errors

harsh anchor
#

value_template: > {{ states(sensor.qnapups_battery_runtime) | float(0) / 60 }}
keeps coming out as non numeric whereas the original is numeric, what's wrong with it?

coarse tiger
#

@thorny snow check those spacings, the last line also looks lost
and share the errors

deft timber
#

@harsh anchor , you miss the quotes around sensor.qnapups_battery_runtime

#

value_template: > {{ states("sensor.qnapups_battery_runtime") | float(0) / 60 }}

harsh anchor
#

ok trying now

thorny snow
#

@thorny snow check those spacings, the last line also looks lost
and share the errors
@coarse tiger it all should be correct

harsh anchor
#

value_template: > {{ states("sensor.qnapups_battery_runtime") | float(0) / 60 }}
@deft timber 🍻 🍻 🍻 🍻 🍻 🍻
finally! thanks man

mighty ledge
#

@harsh anchor why you using float(0), default is zero, just omit it

#
{{ states('xx.xx') | float / 60 }}
harsh anchor
#

ok thanks

sonic nimbus
#
      - conditions:
          - condition: template
            value_template: "{{ states.speaker.state != 'on' }}"```
#

how can I these choose segment to re-write shorthanded?

#

obviosly I have only one condition

#

so I think that conditions tag is wrong

deft timber
#

- choose: - conditions: "{{ states.speaker.state != 'on' }}"

sonic nimbus
#

thanks @deft timber that I was looking for 🙂

waxen rune
#

{{ states.light | map(attribute='entity_id') | list | join(',') }} gives me a list of all entities in the domain light,
but how do I get a list of all "light.hue*", all lights with an entity name starting with "hue"?

coarse tiger
#

you could check for attribute, normally they advertise platform:hue if I‘m not mistaken

waxen rune
#

thanks, but hue was just an example, what I really want is to trigger for the first letters. lika all automations starting with "automation.t" or ..

mighty ledge
#

@waxen rune you have to use namespace and check the string itself

waxen rune
#

hmm, thanks. not sure what that means (yet). reading the jinja documentation now. but one thing is clear, it wasn't as easy as I imagined 🙂

sonic nimbus
#

Why I have an error in this script

#

its regarding my choose statements

#

Invalid config for [script]: [condition] is an invalid option for [script]. Check: script->script->set_speaker->sequence->3->choose->0->condition. (See /config/configuration.yaml, line 19)

late island
#

Sooo. With 0.117 there will be native types support for templates but yeeah. I am not getting it. Can someone lead me in the right direction?
For ex. this automation is giving me this error:
Invalid data for call_service at pos 1: value should be a string for dictionary value @ data['payload_template']

#
trigger:
- entity_id: input_number.couch_led_animation_speed
  platform: state
action:
- data_template:
    payload_template: '{"speed": {{ trigger.to_state.state | int }}}'
    retain: true
    topic: home/McLightingRGBCouch_ha/state/in
  service: mqtt.publish
sonic nimbus
#

is it possible to somehow do a call of another services in template

#

like this

#
    data_template:
      entity_id: > 
        {{ speaker_entityid }}
      source: >
        {% if is_state("type", 'Spotify') %}
          AVR Zone2
        # - service: spotcast.start
        #   data:
        #     device_name: Denon AVR-X2400H
        #     entity_id: media_player.spotify_stefan
        #     uri: 'spotify:playlist:37i9dQZF1DX9loJQLuEvap'
        #     force_playback: true
        #     random_song: true
        #     shuffle: true```
#

so, after setting my Source and if the source is Spotify

#

to call service for playing spotify list?

waxen rune
#

Have a look at this: https://community.home-assistant.io/t/counting-watt-usage-of-tasmota-devices/232489/2?u=tom_l
@fossil venture Thanks!. Good for inspiration. Trivia: I just made HA restart spontaneously while trying out my code in Developer Tools explode
After a couple of more spontaneous restarts, I got this to work.

      {% set ns = namespace(val=[]) %}
      {% for s in states.sensor 
            if s.entity_id.startswith('sensor.idlock') and not s.entity_id.endswith('tmpl')  %}
        {% set ns.val = ns.val + [ s.entity_id ] %}
      {% endfor %}
      {{ ns.val | join(', ') }}
inner mesa
#

@late island the change in 0.117 shouldn't affect what you're doing - there's no need to add the "|int" filter because a string is fine

#

you should change data_template: to data:, too, but that's not your problem here

green girder
#

Hi Guys, I've got a problem with grouping thermostats as climate group.

I made a custom sensor which shows me if thermostat is heating or in idle mode.
I wish to make a group to check if any of thermostat is heating

But a group of custom sensors have a status unknown for all time,

late island
#

Yeea. That really wasn't the problem.. Still getting Invalid data for call_service at pos 1: value should be a string for dictionary value @ data['payload_template']

#
action:
- data:
    payload_template: '{"speed": {{ trigger.to_state.state}}}'
    retain: true
    topic: home/McLightingRGBCouch_ha/state/in
  service: mqtt.publish
#

@green girder Soo what exactly is the group needed for? Like why do u need to know if any of the thermostats are heating? Maybe this Custom Component can help you. Not sure because I dont really get why you want to know that. https://github.com/daenny/climate_group

green girder
#

I with to know how long during a day a boiler is heating

#

wish to know*

late island
#

Any Idea on my Problem @inner mesa ?

green girder
#

I will check this out

#

Thanks

inner mesa
#

@late island Not really. works fine in devtools -> Templates with a regular variable, so might have something to do with the value of trigger.to_state.state. You could stick that in a persistent_message to see what it really is. You also need to let the automation trigger so that it actually has a value

late island
#

Also an Error on another automation.
Invalid data for call_service at pos 1: template value should be a string for dictionary value @ data['attributes_template']

inner mesa
#

that's custom_component, right?

late island
#

Yup

inner mesa
#

you can always add "|string" to force it to a string

#

the custom_component may act unexpectedly with this change

#

0.117 stuff should be in #beta

late island
#

aight

#

thanks!

thorny snow
#

Good evening, I wanted to know how to convert the signal "on" "off" from a motion sensor (which gives continuous changes between on and off even with presence) to a sensor that does not detect motion when there is no person for more than x minutes . I do not know if I have explained myself well, but I attach screenshots of what I have and what I am trying to achieve. Thank you!!

harsh anchor
#

@thorny snow I guess you mean that if it detects an ON, it should stay on for some time before going off, right?

thorny snow
#

yes!!

#

thats it

harsh anchor
#

do you also need it to stay off for some time when it goes off?

thorny snow
#

exactly

harsh anchor
#

let me come up with a template

#

by the way what you want is called hysteresis

thorny snow
#

Thank you very much

harsh anchor
#

give this a try, you have to customize it to your sensor

#

also your sensor may already have such parameters, for example I have a zwave PIR sensor that has such parameters in it already

#

in the code there is a delay only for turning off

#

but it will immediately turn on

#

if you wish to delay turning on too, you can add delay_on: "00:03:00" to it

thorny snow
#

Okey, @harsh anchor

#

I will give a try

#

Really thanks!!

harsh anchor
#

you're welcome 🙂

somber radish
#

i would like to have a datetime variable that holds the timestamp of the start of motion detected

#

group.buzz is a group of motion sensors

trail estuary
#

Good evening folks... I am trying to use {{utcnow().month}} in a template, but I was hoping to get the name of the month, not the number. Is there a way?

dreamy sinew
#

utcnow().strftime("yourformat")

waxen rune
#

{{ utcnow().strftime('%B') }}

#

oh. late to the party

dreamy sinew
#

lol teach a man to fish

spiral bridge
#

Would this be the right channel to ask about help formatting a rest get call?

#

I've tried to learn for various projects the last year and it never makes any sense to me

dreamy sinew
grim flicker
#

Could someone help me with something? I want to turn on a light with an automation but the brightness of that light needs to be time based. so between 23:00 and 7:00 the lights brightness need to be 30 and the rest of the day it needs to 80. is there a tutorial for time in a template? the trigger of the light is a binary motion sensor

#

maybe someone can give me a push in the right direction, i can do the rest

ivory delta
#

If you just want them to come on at a certain brightness, do that in the automation. Using a template seems overkill.

coarse tiger
waxen rune
#

easiest would be 2 automations with time conditions

grim flicker
#

yes i guess im thinking to hard. 2 automations with conditions would indeed be allot easier

trail estuary
#

Is there a way to calculate monthly average of a temp sensor?

ivory delta
#

The statistics integration might be what you're after.

trail estuary
#

Yeah, but it is hard to use, because for calculating the average (or anything) for the month, you need to know how many samples that will include...

#

I was looking at the HA-Average custom component, which looks promising, but I would have to template the start and the end of the calculations.... https://github.com/Limych/ha-average

deft timber
#

You can use max_age

#

And not sampling_size

trail estuary
#

The max age option documentation mentions that you´d have to increase sample size as well....?

coarse tiger
#

yeah I coudn't figure that out myself in some cases, this average component looks good though

trail estuary
#

If someone would help me do the template stuff (which, in this case case is way to complicated for me) I agree... The average custom component looks perfect!

deft timber
#

What if you choose a really high sampling_size and limit through the max_age ?

trail estuary
#

Small issue still... The max age would only be correct every other month and way off in February... 😛

#

From the average sensor docs:

start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
end: '{{ now() }}'

The example end: parameter would work for me, but I would need a "template" that got me to the first day of the month...

ivory delta
#

.replace(day=1)

inner mesa
#

.replace(day=1)

ivory delta
#

(I don't know Python)

inner mesa
#

I’m just guessing, BTW

ivory delta
#

We both did. And we both guessed correctly.

#

3 seconds of Googling confirmed it.

coarse tiger
#

legends

trail estuary
#

OK... Let me see what that can do!

#

Works prefectly!!

#

😄

trail estuary
#

Now, I need the automation that this average data is used in to trigger at the end of every month.

ivory delta
trail estuary
#

Yeah, but I am pretty sure they´re gonna throw me back here to use a template as a trigger... 😉

#

But, I can try! 😄

ivory delta
#

Well you already know how to make a template that picks the first day of a month. Can't be too hard to get one that picks the last day...

spiral bridge
#

is there a way in a template sensor to us a variable value as the friendly name?

#

or as part of the friendly name

spiral bridge
#

Thanks! There's so many template related pages I keep getting lost

inner mesa
#

or did you want it to change dynamically?

spiral bridge
#

Change it dynamically

#

Ideally it'll be taking what I get from a rest sensor and renaming based on one of the values

inner mesa
#

I don't know if it does that. You'd have to experiment

#

try it and report back!

spiral bridge
#

Yup seems to be working!

#

ah crud, I can't add that variable name to a constant secondary identifer.

inner mesa
#

what is that?

spiral bridge
#

ideally I want a series of sensors '{{ states.sensor.batches.attributes["name"] }}' & a secondary identifier such as status, abv, date

#

nope I'm just an idiot. I didn't change that one from friendly_name to friendly_name_template...

torn meteor
#

to turn off a group of things, homeassistant.turn_off group.group_name?

#

or do you have to use the expand() template function?

inner mesa
#

homeassistant.turn_off turns off anything

torn meteor
#

so all i need to provide that service is the entity ID of my group of air conditioners

#

it will know how to turn that set off..?

inner mesa
#

Yes

torn meteor
#

awesome.

#

thanks. wasnt sure what the capabilities of groups were.

#

alternatively, i could use expand(group.my_group) with the climate.turn_off service, right?

#

(that must be what homeassistant.turn_off intelligently does in the background)

inner mesa
#

I guess you could

brisk nebula
#

Hi everyone, I've set up an mqtt camera that works fine, but sometimes the frame streamer breaks quietly leaving me unaware of a problem. I'm trying to set up a mqtt sensor that listens to the topic of the mqtt camera and just keeps updating itself whenever a mqtt frame arrives. I've tried putting now() or len(value) to the value_template but nothing seems to work. Is there a way to do it?

thorny snow
#

Hello. Redirected from #automations-archived. Please help me out in an automation. Is there any way to check in an automation if a service was called by a script (automation) or it was called by the user from the Lovelace UI? Example: if climate.turn_off was called by pressing a button from the simple-thermostat card button or it was executed by an automation? Thank you.

deft timber
#

@brisk nebula , what do you wan't exactly? You want a way to know if your camera stopped sending an image after a while, correct? Why di you need a mqtt sensor? Couldn't you simply test the value last_changed of your mqtt camera entity ?

brisk nebula
#

@deft timber, tried that. last_changed doesn't work for cameras

deft timber
#

you mean it is not updated?

brisk nebula
#

no, I mean the property is not updated for cameras

#

i mean yes 🙂

deft timber
#

oh ok

#

and the sensor you created on the mqtt topic of your camera, the last_changed is updated ?

brisk nebula
#

no, not updated either

sonic nimbus
#
    data:
      entity_id: media_player.avr_zone1
      volume_level: "{{ volume }}"```
#

I have an error it says expected float

#

this is my call

#
  action: call-service
  service: script.set_avr
  data:
    variables:
      avr_media_player: media_player.avr_zone1
      volume: 0.4
      source: HEOS Music```
compact void
#

Hey guys, hoping someone could give me a quick hand. I'm trying to add 2 sensor values together and I'm sure I'm messing up the config. Currently I have code to change bytes to Gb, then I was going to combine them - platform: template sensors: bytes_received: friendly_name: "MB Received" unit_of_measurement: 'MB/s' value_template: "{{ states('sensor.gotasus_b_received') | filesizeformat(Gb) | round(2) }}" bytes_sent: friendly_name: "MB Sent" unit_of_measurement: 'MB/s' value_template: "{{ states('sensor.gotasus_b_sent') | filesizeformat(Gb) | round(2) }}" and this is the code that I'm having trouble with to add them together - platform: template sensors: combined_network_in_out: value_template: "{{ states('sensor.gotasus_b_received') | float} + { states('sensor.gotasus_b_sent') | float }}" friendly_name: 'Combined Network In Out' unit_of_measurement: 'Gb'

buoyant pine
#

You have an extra } in the middle of the template

#

Oh and an extra {

compact void
#

hmmm... I think I added those because it didn't work before. Let me try it again and see

buoyant pine
#

Oh wait, that file size format filter adds the unit to the end of the number doesn't it?

compact void
#

yea, first time using it today. Seems to work well

#

think I got it working... i must have missed the other {

#

ty!

#

Can I combine those into 1 template?

#

think I answered my own q.... thanks again for the help!

#

hmm... its partly working? any idea? - platform: template sensors: bytes_received: friendly_name: "MB Received" unit_of_measurement: 'MB/s' value_template: "{{ states('sensor.gotasus_b_received') | filesizeformat(Gb) | round(2) }}" bytes_sent: friendly_name: "MB Sent" unit_of_measurement: 'MB/s' value_template: "{{ states('sensor.gotasus_b_sent') | filesizeformat(Gb) | round(2) }}" combined_network_in_out: value_template: "{{ states('sensor.gotasus_b_received') | float | filesizeformat(Gb) | round(2) + states('sensor.gotasus_b_sent') | float | filesizeformat(Gb) | round(2) }}" friendly_name: 'Combined Network In Out' unit_of_measurement: 'Gb'

#

the value I get in return is 1.7 GB153.2 MB gb

#

So I'm definitely missing something up

deft timber
#

{{( states('sensor.gotasus_b_received') | float + states('sensor.gotasus_b_sent') | float) | filesizeformat(Gb) | round(2)}}

#

here you filesizeformat ads the units, so its returning a string, and then you concatenate to another string

#

the round is useless here

buoyant pine
compact void
#

{{( states('sensor.gotasus_b_received') | float + states('sensor.gotasus_b_sent') | float) | filesizeformat(Gb) | round(2)}}
@deft timber So are you saying to just do this? "{{ states('sensor.gotasus_b_received') | float | filesizeformat(Gb) + states('sensor.gotasus_b_sent') | float | filesizeformat(Gb) }}"

buoyant pine
#

You can't add those together with the letters at the end

deft timber
#

no, this: {{( states('sensor.gotasus_b_received') | float + states('sensor.gotasus_b_sent') | float) | filesizeformat(Gb)}}

compact void
#

@deft timber @buoyant pine Thanks guys, I'll give it a shot

sonic nimbus
#

now my turn 😄

deft timber
#

could you share your script?

sonic nimbus
#

sure, here it is

deft timber
sonic nimbus
#

this partially works

#

it turn on correctly media_player

#

but when it turned on, it doesnt change volume or source

deft timber
#

in your picture you use script.turn_on, that is not what is you do in your tap_action

sonic nimbus
#

yes I see now my mistake

#

for now, lets ignore lovelace tap button

deft timber
#

k

sonic nimbus
#

I want to work from services tab

#

Invalid config for [script]: not a valid value for dictionary value @ data['script']['set_avr']['sequence'][2]['entity_id']. Got '{{ avr_media_player }}'. (See /config/configuration.yaml, line 19).

deft timber
#

yes if you use script.ser_avr and not script.turn_on, you should remove the entity_id

#

just a thought but maybe the variables are passed as string ?! could you try {{ volume | float }} ?

sonic nimbus
#

yes if you use script.ser_avr and not script.turn_on, you should remove the entity_id
@deft timber but im using script.turn_on

deft timber
#

in your image, you send 10 as the volume, it should be between 0 and 1

#

I'm lost 🙂 the error message occurs when you do what?

sonic nimbus
#

on my check config

#

Invalid config for [script]: not a valid value for dictionary value @ data['script']['set_avr']['sequence'][2]['entity_id']. Got '{{ avr_media_player }}'. (See /config/configuration.yaml, line 19).

#

if I replace everywhere {{avr_media_player}} with concrete entity_if for example media_player.zone1

#

then it works

deft timber
#

in your script you have "{{not is_state('avr_media_player','on')}}", it doesn't look right to me. You should remove the quote around avr_media_player

#

idem for "{{is_state('source','HEOS Music')}}" and the quotes around source

sonic nimbus
#

still the same error

deft timber
#

if you use templates, the entity_id should be below data

#

- service: media_player.select_source data: entity_id: "{{ avr_media_player }}" source: "{{ source }}"

#

instead

sonic nimbus
#

here is the updated code

#

now it works 80%

#

just volume doesnt work

#

🙂

#

new trigger:

#

so, volume is between 0-1

#

I set 0.33

#

but nothing is changing

deft timber
#

your avr_zone1 is already on ? I'm asking because maybe it in not fully on when you call the volume after the turn_on. In that case a 'delay' or a wait_template could be needed to check that the media_player is well on

sonic nimbus
#

yes, I know, I need a wait template to wait state 'on' for the player

#

I will add it

#

but in boith situations when the player is off or on, the volume is not updating

deft timber
#

if you replace the "{{ volume | float}}" with an hardcoded value, it works? To try to understand if the problem comes from the variable, or from the service call

sonic nimbus
#

I think it is updating

#

🙂

deft timber
#

Good news

sonic nimbus
#

so, the next thing is a spotcast service

#

that isnt triggering

#

if source = "HEOS Music"

deft timber
#

source is a string, not an entity, so you should not use is_state

sonic nimbus
#

that also I was thinking

deft timber
#

a simple {{ source=='HEOS Music'}} should make it

sonic nimbus
#

great

#

could not find device with name Denon AVR X2400H Zone1

#

but that friendly name is presented in my media_player.avr_zone1

deft timber
#

sorry, i don't know spotcast...

#

if you can't launch it through the 'Service' screen, it is not anymore a #template topic, nor an #automation topic

sonic nimbus
#

yes I know

#

I will ignore it for now

nocturne chasm
#

How do you guys/girls deal with the unavailable state in templates? My roborocks vacuum only has 4 settings (silent, balanced, turbo, and max). So a state of unavailable throws an error. Any ideas?

ivory delta
#

Depends what you're trying to do and what the rest of your template looks like... but you can just test that state != 'unavailable'.

nocturne chasm
#
value_template: >-
         {%- if is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Silent' ) -%}
           Silent
         {%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Standard' ) -%}
           Balanced
         {%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Medium' ) -%}
           Turbo
         {%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Turbo' ) -%}
           Max
         {%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Gentle' ) -%}
           Silent
         {%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'unavailable' ) -%}
           Max
         {%- endif -%}
#

How would that fit into here?

ivory delta
#

You're writing a switch case... you'd need to decide on a default case.

#

Which it looks like you have... you're setting it to Max when it's unavailable.

nocturne chasm
#

Yea, but that is just a work around.

ivory delta
#

Workaround is all you can do here, afaik. You want it to return based on a mapping... if it's not in your mapping, it'll fail (or return a default).

#

The sensible option is the default, which is what you've already implemented.

waxen rune
#

I might recommend an "else" instaed of the last "elif", just as a catch all

#

if that's what you're after

nocturne chasm
#

Ok, and this one gets fixed like this

          {% if state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed_list', ! = 'unavailable') %}
            {{ state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed_list') }}
          {% else %}
            starting.....
          {% endif %}
dreamy sinew
#
{{ map.get(state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed'), 'Max') }}```
#

last bit there is the default on a miss

nocturne chasm
#

Ok, no idea what that is. Will have to play with it. Does that work on its own?

dreamy sinew
#

should work as is in your template tester but you can mess with it from there

#

replace the map.get() to change what you're looking up

nocturne chasm
#

And takes the place of both my templates?

dreamy sinew
#

yeah, this can get all of it in one go

#

it has your renaming and if it misses falls to a default value

#

miss conditions would be a new value or None / Unavailable

nocturne chasm
#

So

{{ map.get(state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed'), 'unavailable') }}```
dreamy sinew
#

yup, that would work

waxen rune
#

small typo in StanDard

dreamy sinew
#

oh yeah

nocturne chasm
#

That easy stuff.

waxen rune
#

nice solution. copy-paste for future use

dreamy sinew
#

yeah, much cleaner that a if/elif/else block

nocturne chasm
#

So it maps my values to what HAss uses and what does map.get do?

dreamy sinew
#

dict.get()

ivory delta
#

You're defining a dictionary and then looking up from the dictionary.

dreamy sinew
#

map there is an arbitrary name

#

but i like descriptive var names

buoyant pine
#

set correct_horse_battery_staple =

dreamy sinew
#

aww no staple

nocturne chasm
#

Ok, sure I will be back after template editor.

waxen rune
#

in lay man's terms, you set up your translations (map) and then use the value you get from (fan_speed) to find a match in your map. if found, use the translation. if not, use the exit (unavailable)

buoyant pine
ivory delta
#

Yeah, it's a good one.

#

It's like that three words location thing.

nocturne chasm
#

@waxen rune , so what phnx put is just a start, I have to do the map.get for each fan speed

waxen rune
#

no, it covers everything

#

have you tried it?

dreamy sinew
#

it should cover everything that was in your if for the renaming

nocturne chasm
#

Trying to try it. At the office trying to figure out how I can paste discord into HAss at the house 🤣

waxen rune
#

{% set map = { 'Silent': 'Silent', 'Stanard': 'Balanced', 'Medium': 'Turbo', 'Turbo': 'Max', 'Gentle': 'Silent'} %}

it's like
if (the value from fan_speed) = Silent, then show Silent (because the first thing in the map is 'Silent':'Silent')
elseif (the value from fan_speed) = Standard, then show Balanced
elseif ...
else Unavailable

dreamy sinew
#

but much faster than evaling that

waxen rune
#

very elegant.

#

really need to redo a few of my templates. now.

buoyant pine
#
{{ now() }}
dreamy sinew
#

it won't solve every problem but its fairly powerful

timid schooner
#

Hi,
I have a switch that sometimes disconnect from the wifi for a few moments, and everytime it disconnects the Lock state is set to on. Any ideas why? Is there a way to set the default value to off?

lock:
  - platform: template
    name: Door
    value_template: "{{ is_state('switch.door', 'off') }}"
    lock:
      service: switch.turn_off
      data:
        entity_id: switch.door
    unlock:
      service: switch.turn_on
      data:
        entity_id: switch.door
nocturne chasm
#

I totally get the set.map. The map.get is what is confusing me

dreamy sinew
#

because Unavailable != off

waxen rune
#

think of it as "get value from the map i just defined"

nocturne chasm
#

So I pasted it and it stays at max no matter what I change the fan speed to

dreamy sinew
#

@timid schooner {{ state('switch.door') not in ['off', 'Unavailable'] }}

timid schooner
#

because Unavailable != off
So it should be

"{{ not is_state('switch.door', 'on') }}"

?

#

{{ state('switch.door') not in ['off', 'Unavailable'] }}
Oh makes sense

dreamy sinew
#

it'll return True for on False for the other 2

#

if you want to invert that, remove the not

timid schooner
#

So mine will work as well

dreamy sinew
#

that can also work

#

depends on what you want

#

6 of one half-dozen of the other

timid schooner
#

I want Unavailable and Off to function the same

dreamy sinew
#

both those should behave the same

waxen rune
#

@nocturne chasm and {{state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed')}} gives you?

nocturne chasm
#

Oh, no. State hadn’t actually changed. It works. Thanks @dreamy sinew and @waxen rune

#

So the map.get is the else?

#

Cause I don’t want it to show the unavailable.

dreamy sinew
#

no the .get("thing", "default")

nocturne chasm
#

Ok, now it makes sense. So what you had with max is what I actually need.

#

Does the same thing I was doing just in a cleaner way.

dreamy sinew
#

the reason i didn't put uav in the map is because sometimes attribs just return None instead

#

so it'll just miss on the lookup and fall to the default

nocturne chasm
#

Auh, but I could define unavailable in the set map part and not even need the map.get part

dreamy sinew
#

you could do a direct key lookup but that throws an exception if you miss

#

best to leave it as it is

waxen rune
#

and no. the map.get is the lookup

nocturne chasm
#

Fml. I thought I had it.

#

🤣

#

Alright. I think I need to spend some google time

waxen rune
#

otherwise you have a nice map of "translations", but no one that uses it

nocturne chasm
#

Auh, ok. So map.get would work on its own but the extra variables define when the dict isn’t defined ?

waxen rune
#

no. or yes. maybe that's what you mean :-)
without a map, there nowhere to look for the answer.

  1. define the map, what value should be replaced by what value
    {% set map = { 'Silent': 'Silent', 'Stanard': 'Balanced', 'Medium': 'Turbo', 'Turbo': 'Max', 'Gentle': 'Silent'} %}

  2. use the map, look in the map for x, replace it with y, if you can't find a match, just use 'unavailable'
    {{ map.get(state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed'), 'unavailable') }}

dreamy sinew
#

if you do a dict.get("thing") and it misses you get None

#

the 2nd value just sets a different default value

nocturne chasm
#

Right. So this would still work unless it misses.
{{ map.get(state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed')) }}

dreamy sinew
#

if you do dict["key"] and it fails you get a KeyError

nocturne chasm
#

I just checked in the template editor

#

I get that you need set map

waxen rune
#

everything fine then?

nocturne chasm
#

Yes, get the state unless unavailable

waxen rune
#

get the state unless you can't find a match, then use unavailable

nocturne chasm
#

Ok, so unavailable is the problem so I need to change it to max.

waxen rune
#

you could replace unavailable for anything, it's just the catch all

#

haha, ok

nocturne chasm
#

100% now

#

Thanks

#

And now that I look up Phnx said that like 10 times 🤣

pearl bough
#

How do i iterate over items in a calendar sensor, specifically items for today's date?

#

I want to add the days events/appointments to my morning TTS readout

dreamy sinew
#

i don't have one of those, what are its attributes?

median mason
#

i have hyperion running on separate Rpi and HassOS running in another Rpi. I want to start/stop the software from HassOS with command line switch. I can successfully run a ssh command from following test switch

- platform: command_line
  switches:
    hyperiond:
      command_on: 'ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no pi@192.168.1.17 "mkdir /home/pi/hello_from_switch"'
      command_off: 'ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no pi@192.168.1.17 "rm -R /home/pi/hello_from_switch"'
      friendly_name: Hyperiond Reset

now on to the real switch. i will have a script that will check wheather hyperion running or not and depending on that i will start/restart hyperion. my question is what to put in "command_state:" and " value_template:" of the switch? In the docs under command_state, its written "If given, this command will be run. Returning a result code 0 will indicate that the switch is on.". what does result code 0 means?

brisk temple
#

0 means successful

thorny snow
#

Please help me out with an automation. Is there any way to check inside an automation if a service was called by a script (automation) or it was called by the user from the Lovelace UI? Example: if climate.turn_off was called by pressing a button from the simple-thermostat card button or it was executed by an automation? Is this possible? Thank you.

umbral pond
#

can secrets from secrets.yaml be read from within a jinja2 template? would something like this work?

        {% set local_id = !secret telegram_georgechat_id %}
        {% if trigger.event.data.user_id == local_id %}
          Boiler schedule for tomorrow updated for George.
        {% else %}
          Boiler schedule for tomorrow updated for Vivian.
        {% endif %}
dreamy sinew
#

@umbral pond no

umbral pond
#

do I have any option for something like this?

#

i.e. just an idea , put the secret value into a picker or something

#

and then read the state of the picker?

deft timber
#

you could use an input_text and put the secret in it ?

waxen rune
#

maybe - haven't tried it yet - you can put the whole template in to secrets and the call that from a template sensor?

    test_tmpl:
        value_template: !secret my_template
#

it works with an ordinary secret, don't know if it will interpret the actual code though..

#

generally a bad idea anyway since secrets are supposed to be.. secret 🙂

#

@umbral pond well, I tried it and it actually works.
I put this in a secret

and the a template sensor:

    test_tmpl:
        value_template: !secret my_template

and sensor.test_tmpl evaluates and updates correctly

umbral pond
#

thank you I will do it this way too then!

#

generally a bad idea anyway since secrets are supposed to be.. secret 🙂
@waxen rune dont secrets remain secrets that way?

#

you are always using the !secret <name> syntax

#

regardless if you put the whole code in the secret value or just the value in the value

#

darn i'm confused

waxen rune
#

in "my" way, I guess it's fine, but in the first proposal we would expose the actual secret

umbral pond
#

that I don't get why.
we have a secret , let's call it my_secret.
and we put it into an input_text , now because i'm too bored to look for the actual syntax I will "imagine it" for speed sake

      value: !secret my_secret
#

then in the template we would be like
if (incoming_data_value_id == input_text.value)

#

even if you share the whole thing to github , how can someone infer your secret ?

waxen rune
#

no, i was thinking abour your family/guests/other users

#

if you expose a secret in a input_text, any user can see that secret

umbral pond
#

you mean like in the UI ?

#

easily enough I'll hide that input from the UI

#

plus it's a Telegram chat_id 😛 most of my family members wouldn't know what to do with it , even if I gave them my API token as well 😛

ivory delta
#

That's the same approach I take for anything that needs to reference a secret in a template. It's good enough.

#

I do the same for addresses for the Waze travel time integration. I don't want to commit addresses to source control, so they live in secrets.yaml.

cobalt grail
#

Does anyone know if there is a way to iterate through areas in templates? Or to get what area a device is in?

#

Or to use the devices at all instead of the entity states.

dreamy sinew
#

no and no iirc

umbral pond
#

Ok I've been trying to debug this for some 30 mins now. What is wrong with this line?

{% if states('input_text.telegram_chatid') == trigger.event.data.chat_id %}
I have also tried:
{% if states('input_text.telegram_chatid') == states('trigger.event.data.chat_id') %}
And also:
{% if states('input_text.telegram_chatid') == trigger.event.data.chat_id.state %}
buoyant pine
#

First one looks fine. Post the entire thing

silent barnBOT
umbral pond
#

essentially it's a telegram callback that has some if then else logic to decide which boolean to turn on

#

but always goes with the "else" option ... my if ... never comes through

#

also , the one I pasted has a mistake , uses this line {% if states('input_text.telegram_chatid') == states('trigger.event.data.chat_id') %} but I can assure you I also tried the one you deemed as fine

buoyant pine
#

Is the entity ID right?

umbral pond
#

yes

#

it goes to the else clause every time

#

no mater if the ...data.chat_id is user1 or user2

#

which means it fails to evaluate the if clause (?)

#

as true

#

in every scenario

buoyant pine
#

I mean is input_text.telegram_chatid the correct entity ID?

umbral pond
#

ah let me check that , good thinking

#

yes I just ctrl+c'ed it from "States" menu in the front-end and ctrl+f'ed it inside the code.

#

checks out

#

what is the easiest way to see the contents of the incoming event from telegram integration? to try debug what comes and whatnot ?

#

set the thing into a different input_text?

#

and check its content ?

flat charm
#

Sorry not sure where to put this, can light groups be associated with an Area? I put some entities into a light group from only one area but it's placed in a seperate card automatically by lovelace so wondering if I need to associate it with an area

velvet glen
#

Any ideas???

ivory delta
#
    sensors:
      my_tp_switch_amps:```
glacial creek
#

Is possible to access the "friendly state name" in a template? For a binary sensor this results in on/off {{ trigger.to_state.state }}. It is a Modified Aqara Door sensor that in UI shows as open/close which would be much better.

velvet glen
#
    sensors:
      my_tp_switch_amps:```

@ivory delta Thanks for this - apologies, couldn't decide if it was the template or the integration - the integration appears to be working perfectly (ie can see entity and all its attributes in developer section), just can't seem to get the template right to create a sensor out of it!

mighty ledge
#

@glacial creek the under the hood names cannot change and that is by design. Everything in the UI is translated depending on the language.

#

the best option you have is to make a template sensor but the UI will show whatever your state is and it won't be translated. You can't have both.

glacial creek
#

the best option you have is to make a template sensor but the UI will show whatever your state is and it won't be translated. You can't have both.
@mighty ledge The UI show open/closed but the notification show on/off. I want the notification to also show open/closed.

mighty ledge
#

@glacial creek Then you have to do the translation yourself in the notification

#
{{ 'open' if is_state('binary_sensor.xxxx', 'on') else 'closed' }}
maiden jungle
#

@inner mesa I finally got back to my template issue from 9 days ago, and i figured it out. thought id let you know that i didnt let it win...

#

thank you again

umbral pond
#

I still haven't managed to determine why this logic always goes to the else clause. I've tried multiple different syntaxes , I 've verified correct spelling and indentation , I 've tried to troubleshoot by "printing" the event.data.chat_id inside a text_input to ensure its value is indeed what I'm expecting and all that in vain.

    - service: input_boolean.turn_on
      data_template:
        entity_id: >
          {% if states('input_text.telegram_chatid') == trigger.event.data.chat_id %}
            input_boolean.one
          {% else %}
            input_boolean.two
          {% endif %}
#

does the chat_id inside the event object not qualify as string? do I have to stringify it maybe somehow?

inner mesa
#

you could try forcing it to be a string: |string

umbral pond
#

ok , let me try!

#

Nope!

inner mesa
#

making there are extra characters in there? you could try something like if trigger.event.data.chat_id|string in states('input_text.telegram_chatid'), or flipping the two

#

or actually, maybe that won't work

umbral pond
#

making there are extra characters in there? you could try something like if trigger.event.data.chat_id|string in states('input_text.telegram_chatid'), or flipping the two
@inner mesa there is an "in" comparator? Not questioning , just making sure you meant to write "in"

inner mesa
#

yes

umbral pond
#

ok let me try!

inner mesa
#

it's like Python

#

{{ "test" in "test" }} returns True

umbral pond
#

my bad , I didn't try the "in" thingy , I had forgotten to reload automations after the |string change. I did , and it worked.

#

so apparently the attribute does not come as a string (?)

inner mesa
#

probably an integer

#

states are forced to strings, but other things, like attributes, retain their types

#

anyway, glad it's working

umbral pond
#

That was a valuable lesson for me on types! 😛 I'm glad too and thank you!

torn meteor
#

little bit of help with a trigger.

#

i've got devices a, b and c. I want to trigger if any of them experience a state change.

#

"if a.state, b.state, or c.state go from <any> to 'target_state', trigger"

dreamy sinew
#

sounds like a normal automations thing

waxen rune
torn meteor
#

but i don't want to create separate triggers for all of them

#

there are actually 14 devices

#

i thought maybe i could use group > expand?

dreamy sinew
#
automation:
  trigger:
    platform: state
    entity_id: device_tracker.paulus, device_tracker.anne_therese
    # Optional
    from: "not_home"
    # Optional
    to: "home"```
#

note the multiple entity ids

torn meteor
#

oh. comma separated?

torn meteor
#

got it. can i shortcut this by using a template for entity_id?

#

i already have a group.all_house_Echo_dots

dreamy sinew
#

that trigger type doesn't accept templates

torn meteor
#

ok. not a big deal

#

thank you

waxen rune
#

can't you use the group as entity?

#

answering my own question: well, you could, but then it will trigger as soon as any of the entities in the group changes state to on, but it won't go off until all of them are off

inner mesa
#

all boolean (optional, default: false)
Set this to true if the group state should only turn on if all grouped entities are on.

#

probably not helpful here, but wanted to point out an option that I just found out about a while ago

frozen vale
#

With the new native types for templates - is it now possible to use a template for the options: in - service: input_select.set_options in an automation?

frozen vale
#

Hm. I guess not. But it looks more like a bug than a feature: options: "{{ states.foo.attributes | list }}" => TypeError: __init__() missing 1 required positional argument: 'render_result'

dreamy sinew
#

definitely smells like a bug. can you report that please on github?

silent barnBOT
dreamy sinew
#

top one

halcyon island
#

hello all I have a problem with graph

#

the value is good on the sensor, but the graph display an old value

halcyon island
#

I have reboot my server, now graph work, the problem isn't the ui

#

the database save none of all previous day

silent barnBOT
#

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

ivory delta
#

Your problem sounds like frontend. Wait for a response over there.

halcyon island
#

yes after reboot I see it's a frontend not ui

silver sun
#

hi guys, ive been reading up on templates and messed around with the template debugger, but im not sure where i create them?

inner mesa
#

create what? template sensors?

#

templates themselves just...are

#

and are used all over

dapper aurora
#

How can i update this template to get last time in a certain state? last time vacuum was cleaning {{ relative_time(states.vacuum.roomba.last_changed) }}

velvet glen
#

Can anyone help me debug this error: https://paste.ubuntu.com/p/Hw35qwB73g/ Getting 'Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printers') for dictionary value'

rugged laurel
#

check you quotes

#

and indentions

velvet glen
ivory delta
#

It's your templates, yes... you can't start the name of an entity with a number:
states.switch.3d_printers.name

#

.3d = bad

#

.threedee_printers = good

rugged laurel
#

really?

velvet glen
#

Ah, no way to escape numbers etc? Ok will A3d_printers work?

ivory delta
#

So I've heard, Ludeeus. I think it's down to the way the templating engine tries to parse the string.

rugged laurel
#

huh

#

{{ states.switch['3d_printers'].name}}

ivory delta
#

D'oh. That's the one...

#

Keep the names, alpha... fix the templates 😄

velvet glen
#

Ah ok, will try that

rugged laurel
#

When I think of it, I think I saw this in the docs somwehere at one time

ivory delta
#

Yeah, I'm sure I've read it rather than just heard it in passing.

#

But I don't know enough Python/Jinja to understand why.

ivory delta
#

I wonder what it's trying to access when you do .number. In JavaScript, it'd be fine with that (even if it's bad practice to start variables with numbers).

#

Oh... it's expanding it 😮
got 'd_printers') for dictionary value @ data['sensors']['switch_threed_printers_amps']

#

switch_*threed*_printers_amps

velvet glen
#

I misunderstanding this?

ivory delta
#

What's the error?

#

And yes, you got it wrong 😄

#

states.switch.['3d_printers'].name should be states.switch['3d_printers'].name

#

Note the dot I removed.

velvet glen
#

can not read a block mapping entry; a multiline key may not be an implicit key at line 71, column 26:
unit_of_measurement: 'A'

#

Ah!

#

Where's the faceplant emoticon... 😉

ivory delta
#

a.b is equivalent to a['b']

#

It's an easy one to miss, don't worry about it.

velvet glen
#

Yeah, makes sense - although still getting: can not read a block mapping entry; a multiline key may not be an implicit key at line 71, column 26:
unit_of_measurement: 'A'

ivory delta
#

Which line is line 71?

#

I see bad quotes in there though... Careful about mixing " and '

#

If you're using ' around the template, you must only use " inside. Otherwise the second ' closes the pair and the rest is garbage.

#

All of your value_templates have the same issue

velvet glen
#

Hmm - yeah just lifted this from the home assistant site example and worked before introducing the numbered sensor, so this must be throwing it off. Ok, will try and adjust!

#

Ok validating now!

#

TBH in future I'll probably just avoid leading numbers in names, but good to understand the logic!

#

Thanks for help - never would have got that one!

blazing burrow
#

anyway to get the selected index from an input_select?

rugged laurel
#

yes, no, kinda

#
{% set idx = {"option1": 0, "option2": 1} %}
{{ idx[states('input_select.my_selector')] }}
silver sun
#

hi guys, struggling on how to get started with templates, ive got my hue ambiance bulbs added in HA and can turn them on/off using alexa via emulated hue, but when i turn them on i want the bulb light temperature to be set dependant on time of day

inner mesa
blazing burrow
#

@rugged laurel that's what I was afraid of... I have 89 options in my select lmao

#

can I use something like zip in a template? I could get the state_attr of my input's options attribute as a list right? and then maybe zip with a range? or am I thinking too python?

blazing burrow
#

@rugged laurel thats going to work perfectly, once i get all my options in 😅

cinder basin
#

does anyone know how to create sensors from weather forecast from met.no

#

i know how to crate sensors for temperature, humidity, ... but i have trouble creating sensors for forecast values. I'm using met.io home assistant plugin

clear pulsar
#

guys.. when I run this I got error.. anyone can help me out? ```
binary_sensor:

  • platform: threshold
    entity_id: sensor.bedroom_ac_plug_current
    upper: 400
    name: Real Bedroom AC Plug Status
#
2020-10-30 23:36:14 WARNING (MainThread) [homeassistant.components.threshold.binary_sensor] State is not numerical
pure pulsar
#

Greetings all, I am trying to wrap my head around templates and how to do calculations, anyone here who might be able to assist?

clear pulsar
#

Greetings all, I am trying to wrap my head around templates and how to do calculations, anyone here who might be able to assist?
@pure pulsar what do you mean?

pure pulsar
#

I am trying to divide number of deaths by number confirmed

#

sensor.us_coronavirus_deaths sensor.us_coronavirus_confirmed

#

to get a %

clear pulsar
#
- platform: template
  sensors:
    worldwide_corona_percentage_infected:
        friendly_name: Worldwide Percent Infected
        value_template: '{{ ((float(states.sensor.worldwide_coronavirus_current.state) / float(states.sensor.worldwide_coronavirus_confirmed.state)) * 100) | round(1) }}'
        unit_of_measurement: "%" 
#

thats how I do it

pure pulsar
#
  "deaths": states('sensor.us_coronavirus_deaths'),
  "confirmed": states('sensor.us_coronavirus_confirmed')
} %}    

{{my_covid_json.deaths}}
{{my_covid_json.confirmed}}```
ivory delta
#

US Corona cases? I'm surprised it can handle numbers that big 🤷‍♂️

pure pulsar
#

That was witty

#

Last year there were 34 Million cases of the flu so I guess we are not even close yet

#

@clear pulsar thanks that gets me closer. I am more trying to understand how to do calculations using the templates tab under development tools

#

so yours gets me close, but I am struggling with how to just do the basic math portion

#

When I built the template you have there it works for me

#

Added this to my Configuration.yaml for the moment:

#
  - platform: template
    sensors:
      us_corona_death_percentage:
          friendly_name: US Death Percentage
          value_template: '{{ ((float(states.sensor.us_coronavirus_deaths.state) / float(states.sensor.us_coronavirus_confirmed.state)) * 100) | round(1) }}'
          unit_of_measurement: "%"```
clear pulsar
#
- platform: template
  sensors:
    worldwide_corona_percentage_recovered:
        friendly_name: Worldwide Percent Recovered
        value_template: '{{ ((float(states.sensor.worldwide_coronavirus_recovered.state) / float(states.sensor.worldwide_coronavirus_confirmed.state)) * 100) | round(1) }}'
        unit_of_measurement: "%" 
#
- platform: template
  sensors:
    worldwide_corona_percentage_deceased:
        friendly_name: Worldwide Percent Deceased
        value_template: '{{ ((float(states.sensor.worldwide_coronavirus_deaths.state) / float(states.sensor.worldwide_coronavirus_confirmed.state)) * 100) | round(1) }}'
        unit_of_measurement: "%"
pure pulsar
#

that does work on the templates page

clear pulsar
#

thats is the rest

pure pulsar
#

yep I am seeing it now, I am just using the covid stuff to better understand how to formulate my own templates

#

or better yet, calculations

clear pulsar
#

at the momont try to figure something for my self

#

need to round my sensor.. but trying to figure it out where should I put it out..

clear pulsar
#

anyone know why I got error for this template

#
- platform: template
  sensors:
    bedroom_ac_plug_current_round:
      friendly_name: Bedroom AC Plug Current Roung
        value_template: {{ states('sensor.bedroom_ac_plug_current')|round(0) }}
        unit_of_measurement: "mA" 
buoyant pine
#

Indentation is off, and you need to wrap the template in quotes

#

Also...

silent barnBOT
#

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

buoyant pine
#

@clear pulsar

clear pulsar
#

@buoyant pine thanks.. I have been pulling my hair because of that indentation...

#

👍

lost tide
#

I have been working on this all night. I had it working for quite some time until I added a new switch yesterday. I somehow lost the config that accomplished what I want. I have a MQTT switch that an arduino monitors. When the MQTT switch is press the MQTT topic is turned to 1 and the arduino mimics my garage door button press. When the arduino opens the door it returns the MQTT topic back to 0. And waits for the topic to return back to 1 before it mimics the garage button press again. Been working for over a year and works great. I have a zwave sensor on the garage door to know if the garage is open or closed. Until yesterday I had the MQTT switch icon change from "garage" to "garage-open" based on the zwave sensor. I can't seem to get this to work again. I'm not even sure how I did it because it was so long ago. I'm currently adding the following code to my switch but I don't think this is the proper way to do it.

icon: >- {% if is_state('binary_sensor.main_garage_door', 'on') %} mdi:garage-open {% else %} mdi:garage {% endif %}

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

inner mesa
#

what isn't working? the wrong icon is showing up?

#

is that from a card?

lost tide
#

That is my switch. - platform: mqtt name: "Garage Door Button" unique_id: "garagedoorbuttonmain" state_topic: "hass/garage/door_button" command_topic: "hass/garage/door_button" payload_on: "1" payload_off: "0" qos: 0 icon: >- {% if is_state('binary_sensor.main_garage_door', 'on') %} mdi:garage-open {% else %} mdi:garage {% endif %}

inner mesa
#

There's no indication that that field supports a template

#

I use a cover template for that:

lost tide
#

Thanks. I'll use that code and lookup more about cover templates. I really needed a direction to look more than anything.

inner mesa
#

sure, np. main takeaway is that you only use templates where they're explicitly supported, or in a data: block of a service call

lost tide
#

Trying not to sound stupid but is there a simple doc that indicates where templates can be used? Google searches brings back a lot of outdated or misleading data.

waxen rune
#

One way of achieving what you want is to do a separate template binary_sensor based on your mqtt switch. then you can have your icon in that template

inner mesa
#

Really, just what I said above

waxen rune
#

ha. missed that link

inner mesa
#

That wasn’t to you, trying to answer:

#

Trying not to sound stupid but is there a simple doc that indicates where templates can be used? Google searches brings back a lot of outdated or misleading data.

#

sure, np. main takeaway is that you only use templates where they're explicitly supported, or in a data: block of a service call

#

‘Explicitly supported’ means ‘the docs say so’

waxen rune
#

@lost tide I agree it is a lot to plow trough when you start templating. A problem for me is that I need to know what you're looking for to google it - but I don't really know that just yet. I just know what I want to achieve, not what components to use - yet. I think the docs are great, especially compared to many other open source projects and despite the developing pace in HA is extreme, but it is not always user friendly.
Anyway, did you get the examples you needed to move on? If you don't want to use the example RobC gave in https://hastebin.com/agikakudiq.less, I would start with https://www.home-assistant.io/integrations/switch.template/ and/or https://www.home-assistant.io/integrations/binary_sensor.template/

lost tide
#

I have been searching for "home assistant change switch icon based on sensor" I just tried the provided example but I'm not sure I implemented it correctly. Most likely I didn't communicate well enough to for RobC to know what I was asking. I have worked with Home Assistant for years but it runs so well that I by the time I want to add or update it I have forgot most of how I put it together.

inner mesa
#

what did you end up with? The strategy was to separate the MQTT switch from the cover abstraction, so you could simply replace my entities with your MQTT entities

lost tide
#

I added your cover but it doesn't change when I open the garage. I'm still trying to wrap my head around it.

inner mesa
#

it even has a section for garage doors 🙂

mighty ledge
#

that looks near identical to my garage door template. You don't need the icon template.

#

you can use device_class: garage

inner mesa
#

or that

mighty ledge
#
  - platform: template  
    covers:
      garage_door:                                                   
        friendly_name: "Garage Door"
        device_class: garage
        value_template: "{{ is_state('binary_sensor.garage_door_sensor', 'off') }}"
        open_cover:                          
          service: switch.turn_on
          entity_id: switch.garage_door_switch                                     
        close_cover:            
          service: switch.turn_on
          entity_id: switch.garage_door_switch
        stop_cover:
          service: switch.turn_on
          entity_id: switch.garage_door_switch
#

@waxen rune cover templates need to resolve on/off or true/false

#

that's probably why @lost tide's isn't changing state

inner mesa
#

could be. haven't seen it yet 🙂

mighty ledge
#

Oh, sorry! It wasn't you

waxen rune
#

(I removed mine since it confused things more than helped..)

lost tide
#

I had this working before without covers. I just don't remember how. Grrrrrr.....

mighty ledge
#

most likely a switch template

#

which is going to be near identical.

#
- platform: template
  switch:
    garage_door: "Garage Door"
    value_template: "{{ is_state('binary_sensor.garage_door_sensor', 'off') }}"
  turn_on:                         
    service: switch.turn_on
    entity_id: switch.garage_door_switch
  turn_off:                         
    service: switch.turn_on
    entity_id: switch.garage_door_switch
#

I recommend (like the others) using the cover template.

#

@lost tide what's your switch name, what's your sensor name. What state should the sensor be when the door is open?

#

acutally, I just moved up and saw your other post. Is your binary_sensor an MQTT device?

lost tide
#

The switch name is switch.garage_door_button and the sensor is binary_sensor.main_garage_door.

mighty ledge
#

and the switch is always being turned on?

lost tide
#

Binary sensor is a zwave sensor.

#

WAIT!!! The sensor is a sensor from my alarm system. I forgot I changed that.

mighty ledge
#

So.. is that MQTT?

lost tide
#

no. its a sensor from my old DSC alarm system.

inner mesa
#

so you were checking the wrong sensor and that's why the icon wasn't changing?

mighty ledge
lost tide
#

RobC no. The name is the same. Its just not a zwave. Still a sensor.

lusty cipher
#

When I run a rest command all I get a whole bunch of fields like this

        "name": "power",
        "label": "Power",
        "type": "Boolean",
        "value": 0
    },```
Is there a way I can just extrapolate them all to a template, or do I have to specify the ones I want? The examples indicate you have to specify the fields you want.
lost tide
#

This still doesn't change the switch icon. I need an entity to click on and the icon changes based on the sensor.

acoustic wedge
#

Hi, I have many heater valves, for all of them, I have a sensor that tells if it's set to the heating temperature or not.
The sensor template is:

{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float < 17 %}
  off
{% endif %}
{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float > 24 %}
  on
{% endif %}
mighty ledge
#

@lost tide it's not going to change the switch, its going to change the cover.

#

there's nothing you can do to change the switch icon

acoustic wedge
#

That works for all my valves except one, I don't know why, it does not get the temperature.

mighty ledge
#

that switch icon is set in stone. You can make a second template switch and have that icon change.

#

@lusty cipher you can send it to attributes if that's available for the integration you're using.

acoustic wedge
#

If I do {{ state_attr('climate.thermostat_wc_1er', 'temperature') }} then I have the right value

mighty ledge
#

@acoustic wedge do you have that all in 1 template? because that syntax is not correct if you do.

acoustic wedge
#

I just put the value_template

lost tide
#

OMG! I have a backup. Going to see if I can find my old config there. I did make this work at one time. It has been working for almost a year.

mighty ledge
#

@acoustic wedge this is not correct

{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float < 17 %}
  off
{% endif %}
{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float > 24 %}
  on
{% endif %}
lusty cipher
#

Thanks @mighty ledge This is just using the rest integration I was wondering if rest has enough of a standard that HA can figure out based on the type label to give it the proper characteristics.

mighty ledge
#

@lost tide the only way for you to change the icon for an existing item is to use customUI

inner mesa
#

which, unfortunately, will just cause you pain down the road

acoustic wedge
#

@mighty ledge that syntax works for all my other climates

inner mesa
#

or, use a card that lets you change the icon in the frontend, like custom button card

mighty ledge
#

@acoustic wedge but it's not correct. You're sending on and off.

#

you should be using elif

#

also, what happens if the temperature is between 17 and 24?

#

you send nothing

acoustic wedge
#

You're right on that but the issue concerns only one of the conditions

#

So this one does not work

{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float < 17 %}
          off
        {% endif %}
#

also, what happens if the temperature is between 17 and 24?
@mighty ledge It's either set to 15 or 26. I use it to check that the valve has received the instruction.

#

While {{ state_attr('climate.thermostat_douche_1er_2', 'temperature') }} works fine

mighty ledge
#

post your whole config for the section that's not working

acoustic wedge
#

OMG, you were right with your remark: 'what happens when it's in between' and it's the case for this valve, it's set to 22.

#

Sorry

mighty ledge
#

always best to use the correct code!

acoustic wedge
#

Yeah

lost tide
#

Well crap. my backup is to old.

mighty ledge
#
{% set t = state_attr('climate.thermostat_douche_1er_2','temperature')|float %}
{% if t > 24 %}
  off
{% elif t < 17 %}
  on
{% else %}
  lskdjfalkjdsljkfda
{% endif %}
acoustic wedge
#

Thank you again

mighty ledge
#

np, is this a binary sensor?

#

you might have to swap it to a sensor if you want a 3rd state

acoustic wedge
#

Nope, a template sensor

mighty ledge
#

ah ok, then you should be good

acoustic wedge
#

Yes

mighty ledge
#

you can make it 'unavailable' between 17 and 24

waxen rune
#

lskdjfalkjdsljkfda is rather nice also

mighty ledge
#

lol

#

yeah I didn't know what else to put 🤷‍♂️

waxen rune
#

clear indication that the state is unexpected 👍

acoustic wedge
#

Actually I use this code for valves that I set either to 26 or 15, where 26 means on and 15 off. And I was facing the issue with the only valve that I set in between and forgot about it 🙂

#

So value of 22 should never happen

waxen rune
#

well, now you will know if it does 🙂

acoustic wedge
#

Yeah

sand spoke
#

Using the restsensor, how to set the value_template to the current timestamp/date. Now I am just doing value_template: true as value. But setting {{now()}} just gives an error

waxen rune
#

mind sharing the whole sensor config?

sand spoke
#

@waxen rune `

  • platform: command_line
    command: python3 -c "<command>"
    name: fetch_Data_From_API
    json_attributes:
    - data
    value_template: {{states.sensor.fetch_data_from_api.last_changed}}
    scan_interval: 30`
#

I'm brute forcing any option I can think of to just get value_template populated with a timestamp or date

#

Above doesn't work though

lost tide
#

OMG!!! I figured out what I was doing wrong. I wasn't trying to change the icon of a switch. Well I was, but that is a limitation which cannot be done. I created a button associated to the garage door sensor with a tap action associated to the garage button. I feel so stupid now. Thanks petro and RobC for your help. You have helped me understand some of the limitation of HASS. And I learned cover templates. Anyway, all is well.

sand spoke
#

I guess its mandatory to have single quotes around the statement

#

else the templating doesn't work

waxen rune
#

yes

#

everything good then?

blazing burrow
#

so i've figured a way to get the index of the selection from an input_select as a sensor value:

sensor:
  - platform: template
    sensors:
      options_sensor:
        value_template: >
          {% set idx = {"Option 1": 1, "Option 2": 2} %}
          {{ idx[states('input_select.options_list')] }}

input_select:
  options_list:
    options:
      - Option 1
      - Option 2

can i use similar (or different? 😅 ) logic to get the name if all i have is the index?

#

also, i'm good with docs, but don't know where exactly i'd look lol

ivory delta
#

The docs won't cover that since it's well beyond basic templating. Instead, you need to realise that the templating engine is Jinja, which uses Python. Googling for 'python find key by value' led me to this: https://stackoverflow.com/a/8023329/3907492

#

Looks promising, I'm sure someone can convert that into a template.

blazing burrow
#

oh, it's that question above ^^

#

hold on

#

i'm trying to use this as an attribute template for a template sensor:
effect: '{{ states(''sensor.wled_effects'')[state_attr(''sensor.wled_state'', ''seg'')[0][''fx'']] }}'
in order to get the name of the effect.
{{ state_attr('sensor.wled_state', 'seg')[0]['fx'] }} gives me the index

#

@ivory delta came here from integrations

#

my end goal is to SET the input_select i have (also prepopulated, like yours) to whatever the light is currently reporting

ivory delta
#

What does it report? A number for the preset?

blazing burrow
#

this way, if i change the settings from outside of HA, i can run automations to have them fixed

#

yes

ivory delta
#

So just flip the logic of your previous template:
{% set idx = {1: "Option 1", 2: "Option 2"} %}

#

Looking up the index gets the name.

blazing burrow
#

oh yeah i guess so lol

#

oof ok that's fine lol

#

wanted to try and make a template that zips those

#

to save some lines, get the effect list from wled, and range, and zip them

#

but i don't think jinja can do that?

ivory delta
#

Well is everything that cares about the template going to be in the same place? i.e. in the same automation/script?

inner mesa
#

Zip?

blazing burrow
#

i'm putting everything in one file, as a package

#

but i've got inputs, sensors, automations, switches lol

ivory delta
#

But can the same template be referenced by everything that cares about it? There aren't global variables (yet).

blazing burrow
#

i don't think so

ivory delta
#

If it can't be re-used, don't try to make one thing that solves every problem.

#

Solve the individual components.

inner mesa
#

Yeah, no creating zip files from templates

blazing burrow
#

not a zip file

ivory delta
blazing burrow
#

zip(a, b) -> {a[0]: b[0], ...}

ivory delta
#

Maybe there's a way... but it's overkill here.

inner mesa
#

Oh

ivory delta
#

You want WLED's response to set the input_select... and presumably you want changes to the input_select to drive WLED. That's two automations, with their own templates.

#

Keep it simple 😉

blazing burrow
#

it is

#

yes

#

but i can't get the templates right lol

#

i have controlling wled down fine

#

works perfectly

ivory delta
#

They're both dictionaries, just looking up in opposite directions.

blazing burrow
#

i just didn't wanna type out another 100+ element dict 😅

#

i've created controls for speed, intensity, palette, effects, and presets (with some piggybacking on drzzs)

ivory delta
#

Well if you're happy they're in the correct sequence, don't type them out.

blazing burrow
#

but they don't agree if i change them in wled

ivory delta
#

Just keep that array... and reference the index within that array to get the name.

blazing burrow
#

right, i can't get the array

ivory delta
#

You can. You said you curled it.

#

Copy/paste that.

blazing burrow
#

i have a rest endpoint that returns a list ['a', 'b', 'c', ...]

shouldn't this give the value? or do i need value_json? neither works 😅

  - platform: rest
    name: WLED Palettes
    resource: http://192.168.1.189/json/palettes
    value_template: '{{ value }}'
    headers:
      Content-Type: application/json

@blazing burrow

ivory delta
#

Yeah, don't grab it via a sensor... just copy paste.

blazing burrow
#

ohhhh :p

ivory delta
#

The list won't change unless you update WLED.

blazing burrow
#

right, gothca

ivory delta
#

API calls are amazing (I work with and build them for the day job) but they're overkill when the data doesn't change.

blazing burrow
#

yes, that works 👍

#

fantastic

ivory delta
#

When I first became a dev, I always wanted to build things the 'clever' way. Now I want to build them however is easiest to understand and maintain 😉

blazing burrow
#

i mean, i get that

#

i've now got the same list defined three ways in three different sections

#

makes more sense to me to bring it in raw and manipulate it in each place

ivory delta
#

It would make sense if you could bring it in in 3 places. I think global variables are coming soon, so then you'll have a reason to try it again 🙂

blazing burrow
#

👍

blazing burrow
#

you know what... I worked way too hard on that for no good reason

#

I'm using the wled integration for my light... which reports current state for all of those

#

just an automation to set my inputs whenever this change

#

done

#

all working and synced between HA/wled/etc

ivory delta
#

It's all a learning process though.

blazing burrow
#

thanks for your help 👍

cinder basin
#

Hi. has anyone got templete value for extracting met.io forecast values. I want to create a sensor for each day for 5 day weather forcast

ivory delta
#

What have you tried so far?

cinder basin
#

i've extracted values

#

like temperature, humidity and so on

ivory delta
#

Do you know which attributes on the weather entity represent the forecasts?

#

.share them here if it helps

silent barnBOT
cinder basin
#

yes weather.home. but forcasts are under section forecast and there is a lot of values

#

i know how to create sensor for first values

#

but i don't know how to extract values under forecast. and there is 5 conditions

ivory delta
#

So... forecast is just a list (or an array, if you prefer to call it that). You can reference them using [index], where index is a number starting from 0.

cinder basin
#

ok

ivory delta
#

So the first entry in the forecast would be forecast[0].

cinder basin
#

ok

ivory delta
#

If you want something specific from the forecast instead of the whole forecast dict (object), you can use dot notation to get it... i.e. forecast[0].condition

cinder basin
#

forecast[0]. and then temperature, for temperature?

ivory delta
#

Yup

cinder basin
#

ok i'll try

ivory delta
#

Sounds like you've got this 🙂

cinder basin
#

yes...didn't know what that [0] indexes mean. but after reading codes from forums

#

it started to get clear

#

i can try this in developer tools right? (don't have to restart server)

ivory delta
#

Yeah, it looks weird if you're not used to coding 🙂 And yes, you can do it in devtools > Templates to test what a template will give you.

cinder basin
#

great thx man!

#

{{ state_attr('weather.home', 'forecast') }} is returning [{'condition': 'partlycloudy', 'temperature': 17.3, 'templow': 9.4, 'datetime': '2020-11-02T11:00:00+00:00', 'wind_bearing': 249.1, 'wind_speed': 14.4}, {'condition': 'sunny', 'temperature': 17.6, 'templow': 9.4, 'datetime': '2020-11-03T11:00:00+00:00', 'wind_bearing': 242.8, 'wind_speed': 11.2}, {'condition': 'cloudy', 'precipitation': 1.0, 'temperature': 13.5, 'templow': 9.0, 'datetime': '2020-11-04T11:00:00+00:00',

#

but after i want to choses some values from here, it doesent return nothing

#

or i'm not forming the code right

#

{{ state_attr('weather.home', 'forecast[0].temperature') }} ??? this is right?

#

or am i missing something?

ivory delta
#

You wouldn't use state_attr for that. Something more like this...
{{ states.weather.home.attributes.forecast[0].temperature' }}

#

Although you're probably better off making sensors than using a template like that everywhere.

#

Maybe break it down in steps. Make a 'tomorrow forecast' and get all the attributes in the right place using this integration: https://www.home-assistant.io/integrations/template/
Then you can use the simpler syntax ({{ state_attr('sensor.tomorrow_forecast', 'temperature') }}) everywhere else.

cinder basin
#

that's the plan, to create sensor for each day.

#

ok, trying with state_attr

#

I've read template integration document. That's was my plan, but i just have to extract attributes form weather.home and that's where it stopped for me

#

ok

#

this did the trick

#

"{{ state_attr('weather.home', 'forecast')[1].condition }}"

#

i have now all the attributes extracted

#

now I have to create sensors

#

that's it i think

#

thc

#

thx

young shadow
#

Hi guys,
I'm trying to add a space as a thousand separator.
I could add a comma with this:
{{ '{:,}'.format(value_json[0].activeCases) }}
But I cant find any information on how to change this to a space

waxen rune
#

I have one that does just that, but it is an ugly one: "{{ '{:,}'.format(states('sensor.memory_use') | int).replace(',', ' ') }}"

#

only way I could find out. any improvements are welcome.

#

it works fine for displaying a value, but it screws up a graph since it only interprets the thousands as a value, so 1 300 becomes 1
https://imgur.com/a/I7Z9sNe

#

so I'm sure there's a better way, I just haven't found out yet

pseudo barn
#

Hi,
Can anyone help me a bit to create one template?
I want to make something like this:

  • platform: template
    sensors:
    effeciency_recuperation:
    value_template: >
    {% set value = (((states.sensor.vent_vallox_into_houre)-(states.sensor.vent_vallox_from_out))/(((states.sensor.vent_vallox_from_house)-(states.sensor.vent_vallox_from_out))*100)| round %}
    {{ "%0.0f"%value }}
    friendly_name: "Vallox Eff"
    unit_of_measurement: "%"
#

But... does it make sense?

#

It should be like:
eff=(T2-T1)/(t3-T1)

waxen rune
#

@pseudo barn I see what you aim for, but you may have mixed it up a little.

an example could be something like

      value_template: >-
          {% set t1 = (states('sensor.vent_vallox_into_houre') | float ) %}
          {% set t2 = (states('sensor.vent_vallox_from_out') | float ) %}
          {% set t3 = (states('sensor.vent_vallox_from_house') | float ) %}
          {{ ((t2-t1)/(t3-t1) * 100) | round(2) }}

that won't take care of div/0 and such, but as an example
..and this will give you the same result:

{{ ((states('sensor.vent_vallox_from_out') | float - states('sensor.vent_vallox_into_houre') | float) / (states('sensor.vent_vallox_from_house') | float - states('sensor.vent_vallox_into_houre') | float) * 100) | round (2) }}```
pseudo barn
#

Hi @waxen rune
Thank you very much, I will give a try today 😊

cinder basin
#

Hi. I have "2020-11-02T11:00:00+00:00" datetime, how to get a name of that day. So i need to basicly convert date to day

waxen rune
#

Example: {{ utcnow().strftime('%A') }} will present "Sunday" today

thorny snow
#

how do i make a template that only works on sunday and if a input.boolean it on?

waxen rune
thorny snow
#

ye a template if possible

waxen rune
#

could you describe more? a template will always work, but what do you want it for?

thorny snow
#

so i have a script to turn my lights on and off every day and i want to have a input boolean for every day of the week so i cant stop it runing on days i choose

inner mesa
#

the "Sunday" part is {{ now().day == 6 }}

thorny snow
#

@inner mesa is there a way to put it in a if statement with a input boolean at the end?

inner mesa
#

so... {{ now().day == 6 and is_state('input_boolean.xxx', 'on') }}

thorny snow
#

yes thank you

inner mesa
thorny snow
#

@inner mesa TemplateSyntaxError: unexpected char '&' at 33

inner mesa
#

oh, and

thorny snow
#

thanks

inner mesa
#

sorry, C programmer 🙂

waxen rune
#

just curious, if you have an input_boolean for each day you want to run/nor run the script, what do you need the template for?

#

I imagine you have 7 input_booleans, one for each day? or am I assuming wrong here..?

thorny snow
#

I imagine you have 7 input_booleans, one for each day? or am I assuming wrong here..?
yes i do

waxen rune
#

so if you have an input_boolean for each day that to manually turn on/off wether you want to run the script or not. what will the template add to it?
nothing wrong with that, just curious to hear other peoples solutions.

thorny snow
#

so i have {% if now().day == 6 and is_state('input_boolean.sunday', 'on') %} on {% else %} off {% endif %} but it allways returns off in the template testing tool

#

ok so sundays one

waxen rune
#

ah now I see. thanks

#

check {{ now().day }}

thorny snow
#

returns 1

waxen rune
#

it responds 1 exactly

thorny snow
#

yep

waxen rune
#

it think you are in a country that start the week with sunday

thorny snow
#

uk

waxen rune
#

I can see two ways forward:

  1. Dive in to time handling (and please report back how you solved it)
  2. Number your week Sunday = 1, Monday = 2 .. even though you don't like it 🙂 (don't do this, I was wrong, see below)
thorny snow
#

so now().day only can return a 1, 2, 3, 4, 5, 6 or 7 right

#

@inner mesa

inner mesa
#

0-6, I think, but 🤷

thorny snow
#

ok i gtg eat brb

waxen rune
#

another thing, I just realized it is November 1st.
doesn't .day report the day as in date (1)?
{{ now().weekday() }} gives 6 which would respond as day 6 (Sunday) then.
I don't know for sure, but https://docs.python.org/3/library/datetime.html suggests that

#

"date.weekday()
Return the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a Wednesday. See also isoweekday()."

inner mesa
#

it does, and I just realized that 🙂

#

I had a bunch of stuff in the template tool and was looking at the wrong output. I happened to have now().weekday() in there, too

#

thanks for clarifying

waxen rune
#

trying to learn. happy to find my own mistake sometimes 🙂

inner mesa
#

now that the template tool retains the content I type, it accumulates a lot of stuff

waxen rune
#

I made a template that I tried out in the template tool which made HA restart the other day. no proud moment

inner mesa
#

and it does return 0-6. Today is Sunday (for me) and it returns 6, while this returns 0:
{{ (now()+timedelta(days=1)).weekday() }}

waxen rune
#

If you name your input_booleans the same with the day last, like input_boolean.day0 - input_boolean.day6. (or 1 - 7 if you want to use now().isoweekday())

Then I guess you should be able to do this which save a bit of keystrokes:

            {% set d = now().weekday() %}
            {{ 'on' if states('input_boolean.day' + d | string) == 'on' else 'off' }}
inner mesa
#

I think you'd want

#
            {% set d = now().weekday() %}
            {{ states('input_boolean.day' + d | string) == 'on' }}
waxen rune
#

even better

inner mesa
#

you want a boolean, not 'on'/'off'

waxen rune
#

true (!)

inner mesa
#

even better:

#
            {% set d = now().weekday() %}
            {{ is_state('input_boolean.day' + d | string, 'on') }}
waxen rune
#

why is that better?

inner mesa
#

fewer characters

#

maybe? like 1?

waxen rune
#

haha!
ok, I thought it was something like "Avoid using states.sensor.temperature.state, instead use states('sensor.temperature'). It is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup)."