#templates-archived

1 messages ยท Page 106 of 1

ionic hazel
#

I wanted to have it as a switch, but maybe i dont need that

inner mesa
#

something like this should work:

#
turn_on:
    - service: wake_on_lan.send_magic_packet
      data:
        mac: "ff:ff:ff:ff:ff:ff"
        broadcast_address: 192.168.15.3
    - service: media_player.select_source
      data:
        entity_id: media_player.living_room_tv
        source: 'Netflix'
#

whether you need a template switch or not is another question

ionic hazel
#

right right, im getting a little ahead of myself on the template switch Q

#

ahh entity_id only needs to be there once. nice

inner mesa
#

not sure what you mean. you need to provide whatever each service call requires

#

they're separate calls

#

a template switch looks like a good fit for what you're doing

ionic hazel
#

ah my syntax was all f'd up, but i followed ur example and it passed the config check!

inner mesa
#

my spacing is not right either (remove 2 spaces for everything under turn_on:, but that was a pain in the neck in teh editor

#

but it should work

ionic hazel
#

yea i ended up doing just that!

#

Is it possible to have delays in between the separate calls?

inner mesa
#

follow the script syntax

#

yes

ionic hazel
#

thanks again Rob!

thorny snow
#

@brisk temple Thanks.... it works now

thorny snow
#

Really like your help guys.. can anybody check the following code? I guess the sun event line is incorrect

inner mesa
#

what's wrong with it?

thorny snow
#

It does not represent the correct state

#

I'm wondering if this line of code is correct:

#

{% set ts_from = as_timestamp( states.sun.sun.attributes.next_dusk ) %}

inner mesa
#

it looks like next_dusk is in UTC

odd flare
#

I was getting an error and after doing some searching i found a thread that recommended wrapping it in if statement. Just started up and it doesnt look like it's helping. Still getting the 'split' error

#

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 401, in async_render_to_info
    render_info._result = self.async_render(variables, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 334, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: UndefinedError: 'None' has no attribute 'split'
dreamy sinew
#

.share your template

silent barnBOT
odd flare
#
  {% set d, h, m = state_attr("sensor.quarantine_meter_dk", "value").split() %}
  {% set d, h, m = d[:-1] | int, h[:-1] | int, m[:-1] | int %}
  {% set hours_outside = ((14 - d) * 86400 - h * 3600 - m * 60) / 3600 %}
  {{ (hours_outside / 7) | round(1) }}
{% endif %}
")
#
  sensors:
    quarantine_meter_hours_outside_per_day_dk:
      friendly_name: Quarantine Hours Outside DK
      value_template: >
        {% if states.sensor.quarantine_meter_dk.state %}
          {% set d, h, m = state_attr("sensor.quarantine_meter_dk", "value").split() %}
          {% set d, h, m = d[:-1] | int, h[:-1] | int, m[:-1] | int %}
          {% set hours_outside = ((14 - d) * 86400 - h * 3600 - m * 60) / 3600 %}
          {{ (hours_outside / 7) | round(1) }}
        {% endif %}
dreamy sinew
#

use states('sensor.quarantine_meter_dk') instead

odd flare
#

instead of state_attr?

dreamy sinew
#

oh, interesting

#

that thing has a value as None that's why its getting past your if check

odd flare
#

so it's proceeding on none

dreamy sinew
#
        {% set attr = state_attr("sensor.quarantine_meter_dk", "value") %}
          {% set d, h, m = attr.split() if attr else ("", "", "") %}
          {% set d, h, m = d[:-1] | int, h[:-1] | int, m[:-1] | int %}
          {% set hours_outside = ((14 - d) * 86400 - h * 3600 - m * 60) / 3600 %}
          {{ (hours_outside / 7) | round(1) }}
odd flare
#

should i the if to that or remove the endif?

dreamy sinew
#

remove the endif

odd flare
#

@dreamy sinew thanks, that solved it!

simple fossil
#

Having an issue with a template sensor and wanted to ask here. Trying to pull data from other weather template sensors and do an if statement to determine boat weather. Ultimately trying to make an entity to use for badge on lovelace

#
        icon_template: "mdi:sail-boat"
        friendly_name: "Boat Weather Today"
        value_template: >-
          {% if states('sensor.forecast_wind_today')|float <= 10 and states('sensor.forecast_precip_today') <= 0.05 and states('sensor.forecast_condition_today') in ('clear-night', 'partlycloudy', 'cloudy', 'sunny') %} 
            Yes
          {% else %} 
            No
          {% endif %}```
inner mesa
#

your issue is?

simple fossil
#

Sorry, returns as "unavailable"

inner mesa
#

test each part in devtools -> Templates

#

this needs a "|float": states('sensor.forecast_precip_today')

#

but still, just test each part

simple fossil
#

I feel kind of dumb but didn't know this tool was here. Awesome

#

Thanks so much

inner mesa
#

np

#

it's a lifesaveer

spiral imp
#

I got the following working in template editor. I am trying to get it to work in the 'name:' field of the custom:button-card. What do I have to change to get it to work there?
{% if is_state('automation.basement_lights_dim', "on") -%} Disable {%- else -%} Enable {%- endif %}

regal salmon
#

friendly_name_template I guess? Not sure tho

#

Got another Question:

            {% if states['light'] | selectattr('state','eq', 'on') | list | count > 1 %}
            on
            {% else %}
            off
            {% endif %}

works as intended in dev tools. It just doesn't change the actual value of the entity.

inner mesa
#

share the entire template definition?

spiral imp
#

Figured out mine:

              - entity: automation.basement_lights_dim
                name: '[[[ if (entity.state == "on") return "Disable<br/>Auto Dim"; else return "Enable<br/>Auto Dim" ]]]'
silent barnBOT
regal salmon
#

Uh, helpful bot :)

silent barnBOT
#

Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.

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

mighty ledge
#

@odd flare state_attr() is returning a string and you're trying to split it on startup. You have to check the attr against None and you can't use the is_state_attr method because it doesn't handle None well.

{% if state_attr('x', 'y) != None %}
  ... do crap here
{% endif %}
#

Well apparently my discord wasn't up to date and as soon as I hit enter all this crap filled in. Disregard my message

inner mesa
#

I hate that

odd flare
#

@mighty ledge appreciate the explanation...I was 90% there but this sealed it

mighty ledge
regal salmon
#

So, what I'm attempting to do is this: https://pastebin.com/WihEBrvK
The value_template works fine in dev tools, but the actual entity does not update. It's purpose should be an "All lights" entity that is used for alexa ("Alexa turn on/off all lights").
It always works for turning lights on but it doesn't turn them off again.

mighty ledge
#

because youre using states.light

#

that'll only update once every minute

regal salmon
#

oh

mighty ledge
#

make an all light group

#

then use this template {{ expand('group.all_my_lights') | selectattr('state','eq','on') | list | count > 1 }}

#

value_template wants a true/false too, so you don't need an actual if statement

regal salmon
#

Sorry, it's kinda late. -
If I go through the hoops of creating a group with all my lights manually, I could just create a light.all_my_lights, couldn't I?

mighty ledge
#

yep

#

if you want something dynamic you could make a sensor that reports the number of lights with an attribute template that has all the entity_id's in a list. Then use said list in your expand function.

regal salmon
#

This doesn't really sounds worth in timesavings to just create and manually update an light.all_lights entity, I guess?

mighty ledge
#
sensor:
- platform: template
  sensors:
    light_manager:
      value_template: >
        {{ states.light | count }}
      attribute_templates:
        entity_ids: >
          {{ states.light | map(attribute='entity_id') | list | join(',') }}
#

then for your light

#
light:
  - platform: template
    lights:
      all_lights:
          friendly_name: "All"
          value_template: >-
            {% set entity_ids = state_attr('light_manager', 'entity_ids').split(',') %}
            {{ expand(entity_ids) | selectattr('state','eq','on') | list | count > 0 }}
          turn_on:
            service: light.turn_on
            entity_id: all
          turn_off:
            service: light.turn_off
            entity_id: all
#

the light manager will update once a minute. So you'll have to wait a minute sometimes after adding a light for the first time.

#

or just restart and it'll work instantly

regal salmon
#

Okay, 1st: Thanks so much for your effort. 2nd: I really gotta wrap my brain around that.

mighty ledge
#

It's magic

#

just accept it

regal salmon
#

That wouldn't be no fun, would it? Also I could flex in front of my colleagues

mighty ledge
#

Lol, have at it. Just ping me if you have q's

regal salmon
#

I will haha

#

It should be sensor.light_manager in {% set entity_ids = state_attr('light_manager', 'entity_ids').split(',') %}, shouldn't it?

mighty ledge
#

yah yah, typo

regal salmon
#

Aye x)

#

So, the entity works as it should, but stupid alexa isn't turning anything off. But that's a problem for both another day and another channel. Thanks so much for your help! :)

#

Btw, alexa's just stupid. i renamed the "all" entity to "wurst" and alexa will turn "wurst" happily on and off. jesus.

wintry moon
#

can I use variable/template ( {{ value.split }} ) in 'entity_id' of script's sequence service?

merry ravine
#

can you use the new variable feature from 115 in template sensors? so i can use the same value in value_template, icon_template etc

sharp bone
#

I am trying to setup some iLO sensors. I have found an example. The template is value_template: "{{ ilo_data.temperature['01-Inlet Ambient']['currentreading'] }}" and it returns (15, 'Celsius') but i only want the 15 and none of the rest of it, how do i get the 15 out?

deft timber
#

Have you tried {{{{ ilo_data.temperature['01-Inlet Ambient']['currentreading'][0] }}?

acoustic wedge
#

Hi, I'd like to set a condition in an automation as follows:

- condition: numeric_state
  entity_id: climate.thermostat_room1
  attribute: temperature
  not: >
    {% if is_state('input_boolean.vs_room1', 'off') %}
      15
    {% else %}
      26
    {% endif %}

I need to check in some cases that it is different than 15 and in other cases that it is different than 26. Since equal and not does not exist, can I change the below and above with a template?

deft timber
#

you can do it in a template condition

#

smth like
- condition: template value_template: > {% if is_state('input_boolean.vs_room1', 'off') %} {{ state_attr('climate.thermostat_room1', 'temperature') != 15 }} {% else %} {{ state_attr('climate.thermostat_room1', 'temperature') != 26 }} {% endif %}

plush leaf
#

Is there a way to merge an entity's state and an entity's attributes into a single JSON map in a template? Specifically, I want to add the state as a new member of the attributes map and send it out as JSON via MQTT. I tried to do something like:
{% set wx_attrs = states['weather.home'].attributes %} {% set wx_attrs['condition'] = states('weather.home') %} {{ wx_attrs }}
But that doesn't work to assign a new map member. So I tried the direct route:
{% set wx_attrs = { "condition": states('weather.home'), states['weather.home'].attributes } %}
But it didn't like this, either..
Is there a way to do this in the templates, or am I SoL?

deft timber
#

i don't think you can change the states in a template

plush leaf
#

Note that I am not trying to change the states, per se. I am just trying to create a single JSON map that merges a state and the attributes map, so I can send that out via MQTT., sort of like merging two different maps into one map. I.e., if I had {a:b} and {c:d}, I'd like to make {a:b, c:d}.

deft timber
#

ok my bad

plush leaf
#

That's okay, @deft timber ... I know I can do it by explicitly rebuilding the full map, e.g.:
{% set wx_attrs = states['..'].attributes %} {% set result = { "condition": states(...), "temperature": wx_attrs['temperature'], "humidity": wx_attrs['humidity'], "forecast": wx_attrs['forecast'], ... } %}
But that seems so long-winded.

frank raven
#

@plush leaf It seems like you can add an element with dict() ```
{% set x = {'a':1, 'b':2} %}
{% set y = dict(x, c=3) %}
{{ y }}

#

So I guess {% set wx_attrs = dict(wx_attrs, condition=states('weather.home')) %}

#

However, I don't know about JSON ...

plush leaf
#

Thanks @frank raven -- That works!!
{% set wx_attrs = states['weather.home'].attributes %} {% set result = dict(wx_attrs, condition = states('weather.home')) %} {{ result }}
This gives me the map I need. Then I can send it. Sweet! Thanks!

acoustic wedge
#

Do you see any error here, it's complaining about a missing endif

action:
  repeat:
    while:
      condition: and
      conditions:
        - condition: template
          value_template: '{{ repeat.index <= 25 }}'
        - condition: template
          value_template: >
            {% if is_state('input_boolean.vs_room_1', 'off') %}
              {{ state_attr('climate.thermostat_room_1', 'temperature') != 15 }}
            {% else %} 
              {{ state_attr('climate.thermostat_room_1', 'temperature') != 26 }}
            (% endif %}
deft timber
#

last line, you have a parenthesis instead of a curly bracket

inner mesa
#

Lol

#

Good catch

acoustic wedge
#

yes, good catch
Thanks

deft timber
#

It was my mistake at the first place ๐Ÿ˜…

sharp bone
#

Have you tried {{{{ ilo_data.temperature['01-Inlet Ambient']['currentreading'][0] }}?
@deft timber That doesn't seem to work, config check gives me: Invalid config for [sensor.hp_ilo]: invalid template (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['monitored_variables'][14]['value_template']. Got "{{{{ ilo_data.temperature['01-Inlet Ambient']['currentreading'][0] }}". (See ?, line ?).

#

removing the extra {{ at the start fixes it

acoustic wedge
#

It was my mistake at the first place ๐Ÿ˜…
@deft timber yes but it's Okay

#

Thank you very much @deft timber, @brisk temple and all the others. You help me fix some of my zwave issues with this templating.

acoustic wedge
inner mesa
#

what's wrong?

#

for one, you don't put {{ xx }} in a block of {% xxx %}

#

just use the variable name as-is, since you're already in a tempalte

#

you've done that throughout

acoustic wedge
#

Okay, thanks

#

That fixed it. Thanks.

acoustic wedge
#

Here is my script:

set_temp_until_okay:
  sequence:
    repeat:
      while:
        condition: and
        conditions:
          - condition: template
            value_template: '{{ repeat.index <= 5 }}'
      sequence:
        - service: persistent_notification.create
          data_template:
            title: 'Thermostat {{valve}} tentative {{repeat.index}} ร  {{now().timestamp()|timestamp_local}} '
            message: 'Looper has triggered.'
        - delay: "{{ delay }}"
#

And I'm calling it this way from dev console with this data and calling the service directly through script.set_temp_until_okay:

data:
    valve: climate.thermostat_entresol
    virtual_switch: input_boolean.vs_entresol
    delay: '00:00:05'
#

The delay I pass in data is not considered as well as {{valve}}

inner mesa
#

should work

acoustic wedge
#

Agreed ๐Ÿ™‚

#

But it does not

inner mesa
#

you have too much indentation

acoustic wedge
#

It goes 5 times into the loop immediately and the title of notification is Thermostat tentative 5 ร  2020-10-16 23:20:32

#

you have too much indentation
@inner mesa You think that may be the issue?

inner mesa
#

probably not, just inadvisable

acoustic wedge
#

I'll look to that tomorrow. Thanks again to all for the help.

inner mesa
#

calling script.test2 generates a persistent_message every 10s

noble nova
#

Hi Friends. I'm using Dark Sky API & trying to get it to show the forecast data with the time its predicted to happen. For example for "sensor.dark_sky_temperature_6h" have it show "45ยฐF (Sat 1:50A)". I don't have much experience with templates and can't figure out the correct way to add time

distant plover
#

I have a custom component sensor with the 5 latest bank transactions. It's being updated every 20 minutes. Any ideas how I can make an automation that notifies me for every new transaction? I only want to be notified once of every new transaction. Here is the info I have in the sensor: https://pastebin.com/Fw4eb27K

eternal orbit
#

Hi all

#

Do any of you recall a method to manage hvac in a coupled manner?
I've tado for heating and samsung clima for cooling (and heat pump if needed). But in this way I've two thermostats in my house.
I was thinking in using a template to emulate the switch between cold and hot.

mighty ledge
scenic solstice
#

In an automation is there a template variable or object that holds the name of the automation that exectued?

#

Similar to trigger.entity_id but for the automation name

inner mesa
#

not that I can find. The state of the automation changes because the current attribute is updated, but I don't think there's any way to know which automation you're in. Is this for passing to a common script or something? If so, you could just pass a variable to a script identifying the origin

scenic solstice
#

Yeah. Im thinking about a mobile notification action that disables (effectively muting) an automation for say 1t minutes. I didn't want to have to make an automation for each notification type.

alpine surge
#

Hi. I need help.
From device tool, we can play youtube url with media extractor. Is there a way or template that we just paste url in lovelace and play on device?

acoustic wedge
#

calling script.test2 generates a persistent_message every 10s
@inner mesa Thanks. It was exactly what I was doing but now it works ๐Ÿ™‚

acoustic wedge
#

If I trigger the script from another script, it works perfectly. But if I trigger it from an automation, then, when the loop is over, it starts again.
Here is the automation:

- alias: looper
  initial_state: false
  trigger:
    platform: state
    entity_id: automation.looper
  action:
    - service: script.test
      data:
        delay: '00:00:03'
#

And here is the script:

test:
  sequence:
    repeat:
      while:
        condition: and
        conditions:
          - condition: template
            value_template: '{{ repeat.index <= 3 }}'
      sequence:
        - service: persistent_notification.create
          data:
            message: 'test {{repeat.index}}'
        - delay: "{{ delay }}"
trail ginkgo
#

i want to create a template switch where the value_template uses the numeric value of another sensor to determine 'on' or 'off' ...

#
  on
{% else %}
  off
{% endif %}```
#

is that the most elegant way of doing that?

rare panther
#

you can write single line statement as well {{ "ON" if states('sensor.bedroom_tv_wattage')|float > 20 else "OFF" }}

trail ginkgo
#

Oh Nice!

#

Thanks

#

Is there a way using templates where I can put in a condition. โ€œIf the value has been over 20 for x minutesโ€ so to speak?

#

I guess not unless I put in a helper of sorts?

rare panther
#

You can use the time pattern trigger for that

trail ginkgo
#

In a template switch?

trail ginkgo
#

Yeah thatโ€™s what I figured. Im trying to get a template switch set up. Will spend some more time reading up. Thanks for your comments!

rare panther
#

yeah but don't go overboard with automations making them super complex. Keep them simple with proper naming so that tomorrow if there are issues, it is easier to debug. I have seen people (including myself) making it super nested complex and when 1 thing breaks, very difficult to debug

trail ginkgo
#

I set a 'house state' (day, evening, sleep) and trigger individual automations based on that only. So every automation triggers on the house state, and does just one thing.

alpine surge
#

Hhi. I need help. Using media extractor, we can play url in automations, is there a way to paste url from lovelace ???

#

Like in mini media player, there is txt box for input text to anounce on player.
Same like that if txt box for paste url then play on speaker or chrome cast device

silent barnBOT
coarse tiger
#

whoops was scrolled up

sonic nimbus
#

hello, Im trying to put field from my script to some condition

#

but Im getting an error, when I try to call this script, it says that script has failed

#

extra keys doesnt allowed @plucky token[speaker_name]

#

is it even possible to put into templating field from a script?

buoyant pine
#

@rare panther @trail ginkgo you can just use a template binary sensor for that.

"{{ states('sensor.bedroom_tv_wattage') | float > 20 }}"
silent barnBOT
trail ginkgo
#

@buoyant pine the true/false becomes on/off? Also, can I do that with is_State too?

buoyant pine
#

Yes and yes, you can use any template you want

trail ginkgo
#

Cool. I shall try tomorrow. Done for the day ๐Ÿ˜„ Thanks!

sonic nimbus
#

Is this a proper way to setup random rgb colors

#

rgb_color: ['{{ (range(0, 255)|random) }}','{{ (range(0, 255)|random) }}','{{ (range(0, 255)|random) }}']

inner mesa
#

Is there a way using templates where I can put in a condition. โ€œIf the value has been over 20 for x minutesโ€ so to speak?
@trail ginkgo โ€˜delay_on:โ€™ and โ€˜delay_off:โ€™ in the template binary sensor may help with that

distant plover
#

I have a custom component sensor with the 5 latest bank transactions. It's being updated every 20 minutes. Any ideas how I can make an automation that notifies me for every new transaction? I only want to be notified once of every new transaction. Here is the info I have in the sensor: https://pastebin.com/Fw4eb27K

kind hornet
#

hi, I'm playing around with rest_command and templates
using
payload: '{ "iot2tangle": [ { "sensor": "Homeassistant1", "data": [ { "value": "{{val1}}" } ] }, { "sensor": "Homeassistant2", "data": [ { "mp": "1" } ] } ], "device": "DEVICE_ID_1", "timestamp": 1558511112 }'
works, but if I want to use a sensor value I get into troubles with the quotes I guess
payload: >
{ "iot2tangle": [ { "sensor": "Homeassistant", "data": [ { "value": " {{(states(sensor.bb_aussen_temperatur) |float)}}" } ] }, { "sensor": "Homeassistant2", "data": [ { "mp": "1" } ] } ], "device": "DEVICE_ID_1", "timestamp": 1558511112 }
Any hints ...

deft timber
#

quotes are missing around sensor.bb_aussen_temperatur

kind hornet
sonic nimbus
#
    data:
      entity_id: media_player.bedroom_tv
      source: "{{ tv_source }}"```
#

is this legit? I can use it variable as tv_source declared above, in my script?

kind hornet
sonic nimbus
#
      entity_id: script.bedroom_tv
      data:
        tvsource: "Netflix"```
#

from log: Bedroom TV toggle via encoder: Error executing script. Invalid data for call_service at pos 1: extra keys not allowed @ data['tvsource']

#

and tvsource is my field (variable in script bedroom_tv.yaml) => fields: tvsource: description: Particular application (eon, yt, netflix..) example: Netflix

fossil venture
sonic nimbus
#

thanks, it working now, I missed that variables: part ๐Ÿ™‚

#

and does somebody have an example for rotary encoders and dimming lights?

#

something like this

#

nothing really happens though

#

logs: Error rendering data template: UndefinedError: 'sensor' is undefined

deft timber
#

you have to use states.sensor.bedroom_entrance_led_ceiling_dimmer

#

or {{states('sensor.bedroom_entrance_led_ceiling_dimmer') | int }}

sonic nimbus
#

thanks @deft timber it works now ๐Ÿ™‚

sonic nimbus
#

and another question - I want to control my 6-zone amplifier volume control

#
     entity_id: media_player.zone_13
     data:
       volume_level: >
        {{states('sensor.bedroom_entrance_actuator_1') / 100 | float}}```
#

I can see clearly that volume in HA is setup like 0.somethng

#

0,26 so I decided to my encoder values from 0 - 100 divide by 100

#

again I have a trouble with this one also

#

my volume_level doesnt respond it seems

deft timber
#

The | has the priority over the /, you should do {{ (states('sensor.bedroom_entrance_actuator_1') / 100) | float}}

#

otherwise you are just converting the 100 in float

fossil venture
#

Actually it should be {{ states('sensor.bedroom_entrance_actuator_1')|float/100 }}

sonic nimbus
#

the solution it seems doesnt work @deft timber , I will try @fossil venture solution also

#

Im getting unkown error when Im testing in templates section

deft timber
#

Hmm, I don't really understand, but okay...

fossil venture
#

States are always strings. You need to convert the to numbers ("float") before attempting division.

deft timber
#

well actually yes, you first need to convert the sensor

#

okay

sonic nimbus
#

thanks guys, it works ๐Ÿ™‚

sonic nimbus
#

I have left and right encoder near my bed, how to setup volume form one or another

#

maybe in action to set trigger.state or something similar?

#

and ofc, I need to set other encoder value, when second one is toggled

deft timber
#

you could simply use 2 automations

#

i don't thing you have access to the trigger info ({{trigger.*}}) when using the state trigger, only when using an event trigger

#

fyi you can also simulate an 'or' by using the choose statement

sonic nimbus
#

ok, I will consider that

#

but for now 2 automations, just to see how it will behave

buoyant pine
#

@sonic nimbus your hastebin is blank

deft timber
#

oh ok, good to know, thanks ๐Ÿ™‚

median mason
buoyant pine
#

.rest_command perhaps?

silent barnBOT
median mason
#

.rest_command perhaps?
@buoyant pine thanks

#
wled_lor0:
  url: http://ip-address/json/state
  method: POST
  payload: '{"lor":0}'
  content_type:  'application/json; charset=utf-8'
#

this is working fine

#

now i want to make a switch depending on the value of lor (0/1/2)

#
- platform: rest
  name: Wled Lor
  resource: http://192.168.1.39/json/state
  # is_on_template: >
  #   {% if value_json.lor == 1 %}
  #     True
  #   {% elseif %}
  #     {% value_json.lor == 0 %}
  #     False
  #   {% endif %}
  headers:
    Content-Type: application/json
  body_on: '{"lor": "1" }'
  body_off: '{"lor": "0" }'
silent barnBOT
median mason
#

first i get error for the commented part, then with the code switch is not working...if i turn on the switch, nothing happens in the light and state of the switch gets back to off

buoyant pine
#
is_on_template: "{{ value_json.lor == 1 }}"
#

oh actually, you don't even need that since you defined body_on: @median mason

#

two things:

silent barnBOT
#

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

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

#

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

median mason
#

i see no msg after i turn on the switch in logs

#

but the switch turned to off by itself

timid epoch
#

Hello, I am trying to put entire domain to history exclude , and then individual entity in include. But it's not working. Should I be able to do something like that?

#
include:
    entities:
        - device_tracker.i5gulodesktop
exclude:
    domains:
        - device_tracker
inner mesa
#

From this, it sounds like that won't work:

#
Filters are applied as follows:

No includes or excludes - pass all entities
Includes, no excludes - only include specified entities
Excludes, no includes - only exclude specified entities
Both includes and excludes - include specified entities and exclude specified entities from the remaining.
#

you're in that last category, and I would expect it might include that one entity and then exclude the whole domain

#

probably easiest just to exclude the device_tracker entities that you don't want

timid epoch
#

yeah, I figured, I will just to them by hand, thanks!

daring wedge
#

Hi all, I want my automation to start 5 minutes before my input_datetime, how should I template that?

#

something like: trigger: platform: template value_template: '{{ ((now().strftime("%s") | int + 300) | timestamp_custom("%H:%M:%S")) == states.input_datetime.alarm_clock.state }}' ?

daring wedge
#

Although the upper code is without error (I can save the automation) it is not triggering the automation :/ how come?

#

Okeee seems like I need a sensor.datetime

blazing burrow
#

@marble jackal so i'm using these two templates:

#
{{ (as_timestamp(state_attr('sun.sun', 'next_rising')) - ((12*60*60 - (as_timestamp(state_attr('sun.sun', 'next_setting')) - as_timestamp(state_attr('sun.sun', 'next_rising')))) / 2)) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}

{{ (as_timestamp(state_attr('sun.sun', 'next_setting')) + ((12*60*60 - (as_timestamp(state_attr('sun.sun', 'next_setting')) - as_timestamp(state_attr('sun.sun', 'next_rising')))) / 2)) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}
#

but the two values (currently) are:

2020-10-19 18:47:50
2020-10-20 06:47:50
#

so "rising" at 6:47pm tonight, and "setting" at 6:47am tomorrow

#

i'm guessing that's why i need to wait until after sunset?

#

so that both sunrise AND sunset are for the next day

inner mesa
#

I hope that lizard knows how much time and effort you're putting into this ๐Ÿ™‚

#

or maybe he's just annoyed that the lights are going on and off at weird times

buoyant pine
#

what the fuck is happening with the sun

fossil venture
buoyant pine
#

Sun 2.0โ„ข๏ธ

blazing burrow
#

i did look into sun2, but couldn't get it working right at the time ๐Ÿค”

#

but am i right that's why i need to set them AFTER sunset?

marble jackal
#

but am i right that's why i need to set them AFTER sunset?
@blazing burrow yes

marble jackal
#

They are 12 hours apart though, so that part is working ๐Ÿ™‚

distant plover
#

I have a custom component sensor with the 5 latest bank transactions. It's being updated every 20 minutes. Any ideas how I can make an automation that notifies me for every new transaction? I only want to be notified once of every new transaction. Here is the info I have in the sensor: https://pastebin.com/Fw4eb27K

blazing burrow
#

@marble jackal it turned my lights off at the right time last night (after I manually set them), and ran at midnight to update them, so as long as they turn on right (in about an hour), I think we got it ๐Ÿ‘๐Ÿ‘

bitter atlas
#

@distant plover you have an entity with the name "transactions" that list all that below it as attributes?

distant plover
#

The entity is called 'bankaccount' or something and it has the available funds and balance. But then it has an attribute called transactions that contains the last x transactions.

#

The pastebin only shows 2 transactions

bitter atlas
#

@distant plover ok so if you use "bankaccount" as the entity in a state trigger with the attribute "transactions" and leave the to and from fields blank it will fire that automation any change that takes place with that attribute like a new entry

distant plover
#

Hmm... ok. I think the transactions get updated though as they're probably first reserved or something and the finalizes. But maybe tackle that later. So if I listen for any change like you suggest, how would I grab the info from the latest new transaction into a push message?

bitter atlas
distant plover
#

They sent me here ๐Ÿ˜„

bitter atlas
#

the question i answered was an automations question lol

distant plover
#

Hehe... Well, I know how to send the push message, but I don't know how to get only the new transaction. And that's what Tinkerer suggested I'd go to templates for.

#

I made the transactions part of the custom component so I can modify it if that helps.

muted berry
#

So I hope this is the right place

#

I'm using this to scrape an rss feed for the menu at my kids school

bitter atlas
#

@distant plover this might work. is the entity name bankaccount or sensor.bankaccount?
{{ state_attr('bankaccount', 'transactions').accountingDate[0] }}

muted berry
#

The problem is that the lunch_2_merged sensor doesn't capture the entire menu but only one of two lines separated with </br>

distant plover
#

sensor.bankaccount

muted berry
#

and if I use the sensor.lunch_2 only for example, it captures the entire menu but shows everything in a line, including the </br>

blazing burrow
#

sounds like a job for regex imo

distant plover
#

@bitter atlas UndefinedError: 'list object' has no attribute 'accountingDate'

bitter atlas
#

@distant plover {{ state_attr('sensor.bankaccount', 'transactions').[0]accountingDate }} so what you should do is create a template sensor with this as the value that way you get a entity that has the result of this as the state and then use that in your state trigger

mighty ledge
#

[0] goes before accountingdate

bitter atlas
#

doh

distant plover
#

Then I got a date, yeah

bitter atlas
#

you can use that to create other sensors if need be or use something else as the trigger etc

mighty ledge
#

@distant plover the easiest way to handle this is to make a template sensor that produces the latest transaction

distant plover
#

Now I have a template sensor with the accountingDate as state

deft timber
#

@muted berry , {{ states('sensor.lunch_2_merged') | regex_replace("^(.*)<br\/>(.*)<br\/>(.*)$", "\\1 \\2 \\3") }} will show the 3 lines in a single line

buoyant pine
#

good lord

bitter atlas
#

regex is always fun to look at

buoyant pine
#

regex: for when you've exhausted all other available options

deft timber
#

or {{ states('sensor.lunch_2') | regex_replace("<br\/>", " ") }}, easier ๐Ÿ™‚

muted berry
#

@muted berry , {{ states('sensor.lunch_2_merged') | regex_replace("^(.*)<br\/>(.*)<br\/>(.*)$", "\\1 \\2 \\3") }} will show the 3 lines in a single line
@deft timber how would I go about making it so that it does line breaks?

mighty ledge
#
sensor:
- platform: template
  sensors:
    latest_transaction:
      value_template: >
        {% set transactions = state_attr('sensor.bankaccount', 'transactions') %}
        {% set dates = transactions | map(attribute='accountingDate') | list %}
        {{ dates | max }}
      attribute_templates:
        amount: >
          {% set transactions = state_attr('sensor.bankaccount', 'transactions') %}
          {% set dates = transactions | map(attribute='accountingDate') | list %}
          {% set maxdate = dates | max %}
          {% set transaction = transactions | selectattr('accountingDate', 'eq', maxdate) | first %}
          {{ transaction.amount }}
bitter atlas
#

its one of those things I always have to go back and refresh myself with everytime i have to use it. like my brain refuses to keep it stored in long term lol

buoyant pine
#

it's because it's trying to tell you something

mighty ledge
#

@distant plover then you just make a new attribute for each item you want using {{ transaction.xxx }} for whatever

deft timber
#

{{ states('sensor.lunch_2_merged') | regex_replace("<br\/>", "\n") }}

mighty ledge
#

if your latest transaction is always the zero slot... then this is easier

sensor:
- platform: template
  sensors:
    latest_transaction:
      value_template: >
        {{ state_attr('sensor.bankaccount', 'transactions')[0].accountingDate }}
      attribute_templates:
        amount: >
          {{ state_attr('sensor.bankaccount', 'transactions')[0].amount }}
distant plover
#

Latest will be the zero, but in an update there might be several new transactions

buoyant pine
#

big spender, eh?

distant plover
#

If I draw my card in a shop at 12:00 and then in another at 12:05 and the sensor is updated at 12:20 (every 20 minutes)

buoyant pine
#

look at quacked with his multiple transactions

#

๐Ÿง

mighty ledge
#

@distant plover then you're going to have a hard time

bitter atlas
#

@distant plover are you wanting an automation to notify you or something? would be alittle helpful to know what your end goal was

distant plover
#

Yeah, thats the intention SonomaGTS

bitter atlas
#

so you want it to text you the details or simply that a transaction was changed?

buoyant pine
#

your bank might have the ability to send you messages when transactions happen (usually over a certain amount you define)

distant plover
#

I need the details ๐Ÿ™‚

mighty ledge
#

do the transactions hold a history? I.E. are old ones in the list when it updates? When is that list purged

distant plover
#

@buoyant pine They don't. But they have this API, hehe.

buoyant pine
#

ah, gotcha

#

odd

bitter atlas
#

norwegian banks..

#

jk

muted berry
#

{{ states('sensor.lunch_2_merged') | regex_replace("<br\/>", "\n") }}
@deft timber this is what's actually in the template though value_template: "{{ states('sensor.lunch_3').split('<')[0] }}"

bitter atlas
#

you can get the details of the latest with what petro posted, otherwise you would have to settle for the entire 5 listings regardless if some were new or not

buoyant pine
#

is it always five transactions?

distant plover
#

@mighty ledge Hmm... well, in the custom component I only ask for the latest 5 but the API provide access to entire history I think.

muted berry
distant plover
buoyant pine
#

if so, if they're all under the 255 character limit, you could make an automation that writes each transaction to an input_text and notifies you when one of those changes...problem is you'd need logic that checks that one input text didn't just move to another input text (because of new transactions)

mighty ledge
#

You're going to need a way to store the last read transaction's date & another attribute after you send your notification. Then the next time you send a notification, you stop when you get to that transaction date & attr.

#

and you'll have to do that every time. Probably through an automation and an input_text

#

no template sensors

buoyant pine
#

thoughts on the message above yours petro?

mighty ledge
#

Yeah, that's a similar approach just slightly different

buoyant pine
#

bit of a PITA but it could possibly work

mighty ledge
#

it's alll the same, you basically need to track the last notification transaction you sent

distant plover
#

Headache incoming... I'm starting to think it's not worth the effort, hehe

#

Would it be easier to modify/add stuff to the python in the custom component?

mighty ledge
#

you should get that checked out

#

@distant plover yes

#

1000% easier

#

but you need to know python

deft timber
#

Not sure to follow @muted berry , value_template: "{{ states('sensor.lunch_3') | regex_replace('<br\/>', '\n')}}" doesn't do the trick?

bitter atlas
#

you couldn't get details of every transaction but you could get a count all the transactions made within each 20 minutes to display along with the latest

distant plover
#

@mighty ledge I know just enough that I added the transaction part to the original component ๐Ÿ˜›

muted berry
#

Not sure to follow @muted berry , value_template: "{{ states('sensor.lunch_3') | regex_replace('<br\/>', '\n')}}" doesn't do the trick?
@deft timber I'm saying that I have more stuff in that template than what you wrote. The split part is missing. Do you mean it should look like this? "value_template: "{{ states('sensor.lunch_1') | regex_replace("<br/>", " ").split('<')[0] }}""

deft timber
#

you don't need the split anymore

muted berry
#

Oh

#

I'll try it immediately

#

Yaay! It works! Would this produce a comma in between the items then? " regex_replace('<br/>', ',\n')}}"

deft timber
#

yes, it will

muted berry
#

โค๏ธ you're an angel! Much obliged

deft timber
#

๐Ÿ‘

muted berry
#

It doesn't result in a new line but that's fine, I have commas between lines now at least

deft timber
#

I guess the state is not multiline

muted berry
#

Not sure what that means lol

maiden jungle
#

hello, is there anyone that is good with mqtt value templates in yaml that could help me figure out how to get a json message from mqtt that sends a 1 or a 0 to translate into open or close for a window sensor?
i can pass the 1 or 0, i can pass the 0 for close i just cant get the open to pass when the sensor goes to 1

#

current yaml

#
  • platform: mqtt
    state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
    name: "Kitchen Window 1"
    value_template: '{% if value_json.id is equalto 381036 %} {{value_json.reed_open}} {% else %}
    {{states.sensor.kitchen_381036.reed_open}} {% endif %}'

    • platform: mqtt
      name: "Kitchen Window 1a"
      state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
      value_template: >-
      {% if is_state('sensor.kitchen_381036.reed_open','1') %}
      Open
      {% else %}Closed
      {%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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

buoyant pine
#

Either way, remove the quotes around '1'

maiden jungle
#

ah

#

let me give that a try, thank you

#

also is there a way to combine the 2 value templates so i dont have 2 sensors, or is it better to have them separated out?

buoyant pine
#

I don't really see why you have the two sensors in the first place

maiden jungle
#

id rather not have 2, but this was the only way i could figure out how to get data from these window sensors. im using the honeywell2mqtt pulling the json reed info which is 1 or a 0 which ive done, now id like them to report as open or closed in the ui

maiden jungle
#

still doesnt change states

#
    name: "Kitchen Window 1a"
    state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
    value_template: >-
      {% if is_state('sensor.kitchen_381036.reed_open', 1 ) %}
      Open
      {% else %}Closed
      {%endif %}```
inner mesa
#

this doesn't look like a valid entity_id: sensor.kitchen_381036.reed_open

hollow bramble
#

Also what is the point of making this an mqtt sensor?

maiden jungle
#

its coming from my mqtt json honeywell2mqtt window sensor

#
    state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
    name: "Kitchen Window 1"
    value_template: '{% if value_json.id is equalto 381036 %} {{value_json.reed_open}} {% else %}   
    {{states.sensor.kitchen_381036.reed_open}} {% endif %}'```
#

i can get the state to change from 1 to 0 i just want to now change the 1 and 0 to open and close

hollow bramble
#

@buoyant pine why would you remove the quotes around the 1?

buoyant pine
#

Integer vs string

hollow bramble
#

right. All states are strings

rugged laurel
#

for now

buoyant pine
#

Oh right, whoops. I was thinking it was coming from mqtt

inner mesa
#

@maiden jungle Still, sensor.kitchen_381036.reed_open is not a valid entity ID. If you stick that in devtools -> States, I expect you'll get nothing

#

is that an attribute?

#

reed_open

#

or is it just the state of sensor.kitchen_381036?

hollow bramble
#

@rugged laurel that sounds ominous

rugged laurel
#

it is what it is

maiden jungle
#

its one of the mqtt messages i see in the explorer - reed_open and its the only message that changes when the window opens or closes

hollow bramble
#

Is that actually being worked on or is that just an Eventually โ„ข๏ธ thing?

rugged laurel
#

Ignore the explorer, check the acual state object as instructed

inner mesa
#

I beleive it'll be in 0.117

rugged laurel
#

It's in dev allready @hollow bramble

hollow bramble
#

hmm. Sounds like it's going to break a lot of stuff

rugged laurel
#

nah, most will probably not notice, but you can clean up some places where you cast to other types

maiden jungle
#

the only sensor that i can see in the states dev tools are the 2 that i made

#

Kitchen Window 1, Kitchen Window 1a

hollow bramble
#

Well anyone that uses is_state for numeric comparisons is going to get burned

#

Or booleans? or are those still going to be 'on' and 'off'?

rugged laurel
#

I think is_state still does string compare

inner mesa
#

if it's intelligent about casting/coercing the state to be compared to the type of the entity, it should be ok, right?

#

right now, we're manually doing the opposite with filters on the entity state

maiden jungle
#

so ive tried this ( see code), changing the sensor that shows a state in the devs tools, still no joy - platform: mqtt name: "Kitchen Window 1a" state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036" value_template: >- {% if is_state('sensor.kitchen_window_1','0') %} Closed {% else %}Open {%endif %}

inner mesa
#

I don't really know what you're doing there - your value_template is ignoring the mqtt state

#

if your goal is to test the published value, then you need to test that

hollow bramble
#

What exactly are you trying to accomplish?

dapper aurora
#

I have this binary_sensor that doesnt seem to be working. Can anyone help?
platform: template
sensors:
binary_sensor_vacation_mode:
friendly_name: "Vacation Mode"
value_template: >
{% if is_state(" input_select.dm_status_dropdown_nodered", "Extended Away") and is_state("input_select.pk_status_dropdown_nodered","Extended Away") %}
on
{%- else -%}
off
{%- endif %}

hollow bramble
#

Just do {{ is_state("input_select.dm_status_dropdown_nodered", "Extended Away") and is_state("input_select.pk_status_dropdown_nodered","Extended Away") }}

#

also one of your sensor names had an extra space

dapper aurora
#

nice catch - how do you see that?

hollow bramble
#

With my ๐Ÿ‘€

dapper aurora
#

in the value_template?

hollow bramble
#

Are you asking where the extra space was?

dapper aurora
#

yeah sorry

hollow bramble
#

in your first is_state

dapper aurora
#

between the , and "extended away"?

#

that matters? Ugh yaml

hollow bramble
#

What? No. It was in your sensor entity_id string

dapper aurora
#

ohhh

#

yeah

maiden jungle
#

im trying to change the 1 and 0 that i can see in the states to open and close

hollow bramble
#

but why are you trying to make a separate sensor @maiden jungle ?

maiden jungle
#

im not sure how to do the formatting , id love not to create a separate sensor. as you can tell im not very well versed yet @hollow bramble

#

ive tried to to do but just cant figure out the right formatting to pass the info correctly to go from the 1 to open or 0 to close - platform: mqtt state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036" name: "Kitchen Window 1" value_template: '{% if value_json.id is equalto 381036 %} {{value_json.reed_open}} {% else %} {{states.sensor.kitchen_381036.reed_open}} {% endif %}' {% if is_state('sensor.kitchen_window_1','1') %} Open {% else %}Closed {%endif %}

hollow bramble
#

sensor.kitchen_381036.reed_open is not a valid entity, as you've been told several times ๐Ÿ˜‰

maiden jungle
#

yes i know, this was in my notepad as a quick copy paste, its more of the formatting in yaml to combine the to value templates that im struggling with updated

#

sorry for not replacing that

inner mesa
#

hello, is there anyone that is good with mqtt value templates in yaml that could help me figure out how to get a json message from mqtt that sends a 1 or a 0 to translate into open or close for a window sensor?
i can pass the 1 or 0, i can pass the 0 for close i just cant get the open to pass when the sensor goes to 1
Refreshing the question...

#

what you've got there is pretty jumbled up

#

you'd need to post the actual json value of that topic value, if it's json at all

#

if it's really just "0" or "1" (unformatted), then something like this should work:

#
    value_template: "{{ 'closed' if value == '0' else 'open' }}"
#

I don't know what the intent of the rest of that is

waxen rune
#

like

- platform: mqtt
  state_topic: 'homeassistant/sensor/window-door/Honeywell-Security_381036'
  name: 'Kitchen Window 1'
  value_template: "{{ 'closed' if value == '0' else 'open' }}"
maiden jungle
#

so this is my sample startup log on my sensors with the addon that i use to pull the info, this specific sensor is not a window sensor so its missing the reed open data but it shows you the raw info im working with, ```homeassistant/sensor/window-door/Honeywell-Security_111635

  • echo '{"time"' : '"2020-10-20' '15:33:47",' '"model"' : '"Honeywell-Security",' '"id"' : 111635, '"channel"' : 10, '"event"'+ : 132,/usr/bin/mosquitto_pub '"state"' -h : 192.168.1.149 '"open",' -u '"contact_open"' username : -P 1, password '"reed_open"' -i : RTL_433 0, -r '"alarm"' -l : -t 0, homeassistant/sensor/window-door/Honeywell-Security_111635 '"tamper"'
    : 0, '"battery_ok"' : 1, '"heartbeat"' : '1}'```
#

if this was a window sensor the reed_open would have a 0, and my yaml, pulls the reed_open data and gives that 1 or 0, which i can see in the states dev tools - platform: mqtt state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036" name: "Kitchen Window 1" value_template: >- '{% if value_json.id is equalto 381036 %} {{value_json.reed_open}} {% else %} {{states.sensor.kitchen_381036.reed_open}} {% endif %}'

#

hope this helps clears things up a bit on where i am at on trying to get the 1 and 0 to display open or close

#

i have tried RobC and boneheadfraggle suggestion with no joy

inner mesa
#

that's because that template assumes it's just a value and not json

#

I don't know how to read that raw data. is that coming from MQTT?

maiden jungle
#

yes it is

inner mesa
#

it looks like a command line

#

what part of that are you trying to read?

maiden jungle
#

the reed_open part

#

i know in this example there is nothing there, this example is not a window sensor

inner mesa
#

I can't identify the value of it from there. it doesn't look like valid JSON payload

maiden jungle
#

im using RTL433 to MQTT Bridge hass.io addon

inner mesa
#

then it'll be hard to help

maiden jungle
#

caught it

inner mesa
#

you need to get away from this "is equalto" stuff and start using real syntax

maiden jungle
#
+ echo '{"time"' : '"2020-10-20' '15:47:25",' '"model"' : '"Honeywell-Security",' '"id"' : 381036, '"channel"' : 10, '"event"' : 132, '"state"' : '"open",' '"contact_open"' : 1, '"reed_open"' : 0, '"alarm"'+  : 0,jq '"tamper"' --raw-output : .id 0,
 '"battery_ok"' : 1, '"heartbeat"' : '1}'
+ tr -s ' ' _
+ DEVICEID=381036
+ echo 381036
381036```
#

'"reed_open"' : 0

inner mesa
#

then, value_template: "{{ 'closed' if value_json.reed_open == '0' else 'open' }}"

fossil venture
#

A binary template sensor with an opening device_class and this template, value_template: "{{ value_json.reed_open == '1' }}" would be more applicable.

maiden jungle
#

ill try that as well, thank you, also thank you to everyone for trying to assist

inner mesa
#

Yeah, thatโ€™s a better solution

maiden jungle
#

why is it asking for an off delay, this is confusing me

buoyant pine
#

that's optional

maiden jungle
#

even when in red its saying missing property its still optional?

#

config passed, i just worry when i get those warnings

inner mesa
#

Where does it give you that error?

maiden jungle
#

same line as - platform: mqtt

inner mesa
#

No, what are you doing that says that? You said config check passed

maiden jungle
#

i was just typing in my binary sensor yaml , and as soon as i put in - platform: mqtt it came up with missing property off delay

inner mesa
#

In VSCode?

maiden jungle
#

yes

inner mesa
#

Ok, thatโ€™s all I wanted to know

maiden jungle
#

ok cool

inner mesa
#

What did you end up with?

maiden jungle
#
    name: Kitchen Window 1c
    state_topic: "homeassistant/sensor/window-door/Honeywell-Security_381036"
    qos: 0
    device_class: opening
    value_template: "{{ value_json.reed_open == '1' }}"```
inner mesa
#

Ok

maiden jungle
#

its not changing states

#

hmm, im going to have to come back to this after a bit. i appreciate your patience. thank you

jagged stag
#

hey, I new to HA, how to only show 1.1 W - and not 1.xxxxxxxxx
value_template: >-
{% if is_state('light.0x000b57fffe116813_light', 'on') %}
{{0.2 + state_attr("light.0x000b57fffe116813_light", "brightness") * 5 / 255}}
{% else %}
0
{% endif %}
best regards

inner mesa
#

"|round(1)"

#

{{(0.2 + state_attr("light.0x000b57fffe116813_light", "brightness") * 5 / 255)|round(1)}}

jagged stag
#

@inner mesa thanks a lot here, might be a side question are it also posible to do the same on a brightness group ?

inner mesa
#

light group?

jagged stag
#

yes

inner mesa
#

I'm not following what you're trying to do. In general, you can do anything to a light.group that you can do a light

jagged stag
#

i'm trying to get made so i can see an estimate of watt consumption on my light as my ikea bulbs do not have support it that kind of stats

inner mesa
#

ok

#

and you're calculating the wattage based on the brightness?

jagged stag
#

yes

inner mesa
#

clever

#

you can do the same calculation on a light.group, but I don't know how it decides what the brightness of the group is

#

based on the individual lights

#

if they can all be different, you may want to use a template that iterates through them all and adds up the brightness levels instead

jagged stag
#

dont know jet, did had a plan todo the calc on every brightness in the group. and the template stuff will be the way to go

inner mesa
#

shouldn't be too hard. just need to play around in devtools -> Templates

jagged stag
#

:) will do

oblique cloud
#

Need help with an if template.

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?
oblique cloud
#

{% if (trigger.entity_id == 'input_datetime.coffee_monday') %) doest seems to work for me

inner mesa
#

Need a bit more detail on what youโ€™re actually doing and expecting

oblique cloud
#

I have an automation with seven datetime trigger (each day of the week) in the condition section (template), I have an if statement for each day to look if an input boolean are active or not for this day, So if Now().weekday = today and input_boolean.today are active, go to the action, but I need to know which trigger have actually triggered the automation

inner mesa
#

Are you letting it trigger or are you manually triggering it with โ€˜executeโ€™?

oblique cloud
#

I am letting it trigger, I know it because my coffee maker doesnt trigger for the last few day when i've add the if trigger.entity_id = input_datetime ... in the condition section.

Without it.... the action will trigger the action even if its not the good day

#

And I need my coffe at 6 AM ^^ !

silent barnBOT
oblique cloud
inner mesa
#

the whole automation

oblique cloud
inner mesa
#

you don't get trigger.entity_id with platform: time

#

you do get trigger.now, which presumably you could compare to states('input_datetime.xxxx')

oblique cloud
#

trigger.now = the datetime object. Does the object are the entity_id ?

inner mesa
#

Does the object are the entity_id ?

#

?

#

you can test it

oblique cloud
#

The trigger.now are the timestamp. Ok, i'll have to find another solution

inner mesa
#

I'm pretty sure you could make it work

oblique cloud
#

The thing i'm trying to avoid is to have this automation split in 7 one.

inner mesa
#

it's no worse than what you already have

#

you already have now().weekday==xx, so you just need to use triggger.now.weekday() = xxx

#

actually, what is that even doing? You just care about what the day is, not what triggered the automation

#

just get rid of the whole trigger variable test everywhere in the condition

#

it all seems overly complicated

clear pulsar
#

Hi all, currently I have this setup for RM broadlink AC switch which work fine. However I want to make it better and also adding binary_sensor which will allow me to know the correct state of the AC. Need some help on reorganizing this yaml. Can somebody help?

oblique cloud
#

No, i've test it several week without this and i had false trigger. Need this part in the condition. But your last proposition is working. Thanks @inner mesa

clear pulsar
#

the new binary is called binary_sensor.real_ac_daikin_status

inner mesa
#

@clear pulsar I can't imagine that passes a config check

clear pulsar
#

@inner mesa huh? its been working since I start HA, that script never being change

#

anyway is there idea how should I rewrite the sequence so it will add my binary_sensor?

rare oyster
#

Is it possible to get friendly name of this: {{ states.sensor.sensorname.attributes.min_entity_id }}? I want to use it with google tts but not say sensor in it.

gusty nimbus
#

hi i have

  • service: tts.google_say
    entity_id: media_player.woonkamer
#

but how to have the
media_player.keuken added so it uses both ?

#

do i have to do
entity_id: media_player.woonkamer, media_player.keuken

#

?

buoyant pine
#

Yes, or

entity_id:
- media_player.woonkamer
- media_player.keuken
gusty nimbus
#

oh ok great

#

tx

buoyant pine
#

rx

paper nexus
#

Hi all. Having a bit of trouble with a script - I want the transition value of a scene.turn_on service call to be drawn from an input helper. currently I have this:

      transition: '{{(states('input_number.alarm_minutes')|float))*60}}'```
This seems to evaluate correctly in the template helper, but it's throwing an error "Invalid data for call_service at pos 2: expected float for dictionary value @ data['transition']" - am I missing something obvious? Thanks ๐Ÿ™‚
#

(there's a spurious line-break in there - the transition line is all one line in scripts.yaml)

deft timber
#

@rare oyster , states.sensor.sensorname.attributes.min_entity_idcontains the name of the entity of which you want the friendly name ? If so,
{{ state_attr(state_attr("sensor.sensorname", "min_entity_id"), "friendly_name") }} should do it

rare oyster
#

@deft timber Thank you very much!

deft timber
#

@paper nexus , you have a 2 "(", and 3 ")"

#

'{{(states('input_number.alarm_minutes')|float)*60}}'

paper nexus
#

@deft timber Oh yes, so I do! That's stopped the error showing up, but it's now transitioning instantly, rather than over a minute (the value of the input_number currently being 1) ๐Ÿค”

deft timber
#

which version of HA are you using ? I think you should use data: instead of data_template: if you are using 0.116

paper nexus
#

Using 0.116.4, and nil fix using data: instead of data_template:

#

Huh. This seems to have solved it:

  - data:
      transition: >     
        {(states('input_number.alarm_minutes')|int)*60}}

Many thanks for the assist @deft timber ๐Ÿ™‚

deft timber
#

๐Ÿ‘

little gale
#

An input_number goes from 70 to 100. How do I create a template light from it, where 70 is 1% and 100 is... well 100%?

deft timber
#

{{ ((states("input_number.id")|float) - 70)/30*99 + 1}} ?

wooden sonnet
#

Is there an equivalent to ansible's default(omit) filter for HA? I'm trying to make a service call the wraps light.turn_on. I want to be able to apply any of the data attributes from the caller that exist on the light.turn_on service. So like hs_color: "{{ hs_color | default(omit }}" rgb_color: "{{ rgb_color | default(omit) }}" where the caller would typically supply one or the other but not both... I'd like to actually not pass any parameters into the light.turn_on service where the value is not defined by the caller

mighty ledge
#

@wooden sonnet make a script called turn_on_light, then pass the values that you want to pass. Make all the fields in the data section of the light.turn_on service use templates with defaults. Then call the script wherever you want to use defaults.

wooden sonnet
#

Thanks. So I need copy the defaults in from the docs explicitly? Ideally I want to flow all of the supported light.turn_on params?

#

Also if so, how do I convey that the property doesnโ€™t have a default value? default(null)?

little gale
#

Does value_template inside a switch accept unavailable?

wooden sonnet
#

it works if I'm explicit about which light.turn_on attributes I want to support... but I really want to decide on a case-by-case basis.

#

err.. I just added default(null) now.. don't think that part works

#

Get voluptuous.error.MultipleInvalid: two or more values in the same group of exclusion 'Color descriptors' @ data[<Color descriptors>]

peak juniper
#

can someone just quick check something for me:

      value_template: "{{ (states.sensor.temperature_fermentfridge.state) | float < (states.input_select.fermenting_lower.state) | float }}"
#

this value template should only trigger if the temperature of the fridge is lower than my determined value in "input_select.fermenting_lower" right?

#

for some reason the automation keeps triggering even though input_select is set to 16, and the temperature has not dipped below that

#

is it possible this will trigger if the sensor goes to an unknown value?

amber musk
#

Hello, can I call Home Assistant Api trough Jinja2 templates like hass object in custom cards?

hollow bramble
#

What are you actually trying to do?

mighty ledge
#

@wooden sonnet Your hastbin post didn't work. You have to assign a default if you want to use default. Otherwise don't use a default, then it's required.

#

@amber musk No, what are you trying to do?

wooden sonnet
amber musk
#

@amber musk No, what are you trying to do?
@mighty ledge call api to get system metrics

pale idol
#

is there a way to convert a state attribute to a virtual "state" that I can track easier in my sql database?

#

right now the attributes all kick out as a long json string and I'm having trouble accessing the required value contained within

fossil venture
#

@amber musk are you using duckdns?

mighty ledge
#

@wooden sonnet What you are trying to do won't work. You should investigate a python script instead

amber musk
#

@fossil venture I use google ๐Ÿคฃ

fossil venture
mighty ledge
#

@pale idol make a template sensor that extracts the attribute

pale idol
pale idol
#

do template sensors appear in the recorder as well?

inner mesa
#

they create entities, so yes

pale idol
#

hmmm shows up in the "states" table, inside home assistant, but not in the sql database. maybe it needs to change state before it can populate?

amber musk
#

@fossil venture i know that method, I jist thought that I could access the api through jinja2 without that component

inner mesa
#

@pale idol the database stores state changes, so it may need to change to show up

pale idol
#

@inner mesa yep. thats the case. should work now for my needs.

rugged laurel
fossil venture
#

Nice. Thanks for the heads up.

sonic nimbus
#

hello, Im trying to setup my rotary encoder in accordance to my light brigthness and vice versa

#

is this a legite script to do it

#

this is setting up a rotary encoder based on the brightness of the light

somber island
#

{{ states('sensor.xagprice' ) | float * states('input_number.xagoz' ) | round(2) }} am i doing this wrong? should my value not be only 2 decimal places

#

oh nvm i figured it out

inner mesa
#

you'd need another |float and to surround the result with parens before rounding ๐Ÿ™‚

fossil venture
#

Missing casting the input number as a number too. {{ ( states('sensor.xagprice' )|float * states('input_number.xagoz' )|float )|round(2) }} should do it.

sonic nimbus
#

hello, I want to be able to put in my conditions if the inpuit parameter is != null or != empty

#

Is this the right way to go?

#

can a choose option has multiple sequences? Im not sure either if {{ custom_message != '' }} is a proper way to check if the input param is there or not

deft timber
#

you have an indentation problem in your choose

#

you are missing the conditions: before the condition: for the 2nd and 3rd condition of the choose

sonic nimbus
#

so each mini-section will have conditions?

#

right?

deft timber
#

yes

sonic nimbus
#

but this sequence is too left, I think it should be intended to the right

#

?

#

below value_template ?

deft timber
#

did you look at the link I pasted? the sequence is at the same level as conditions

sonic nimbus
#

yes,

#

I see

#

thanks

sonic nimbus
#

still I cant change my audio source

#
    entity_id: script.set_media_player
    data:
      variables:
        speaker: "media_player.zone_12"
        audio_source: "AVR Zone2"```
#

this is the calling example for my script set_media_player

#

and this is the set_media_player

#

pardon me

#

this is the correct script, but either, its not working

#

I mean it works, but it doesnt set appropriete audio source

deft timber
#

if the first condition of your choose is true, then the other conditions won't be evaluated. so if states.media_player.zone_12.state is off, the media_player.select_source will not be called

#

since your second condition is true (custom_message is not empty), you will never avaluate the 3rd conditions -> and never call the select_source

sonic nimbus
#

hm..obviosly I have "nested" conditions

#

but I dont need that, just each condition for itself

deft timber
#

so you should have several choose: statements

sonic nimbus
#

oh, for each input in the script I will have one choose:

deft timber
#

a choose is a if [cond1] then [...] elseif [cond2] then [...] elseif [cond3] then [...] else [...] statement. If you want if [cond1] then [...] ; if [cond2] then [...] yes you need several choose.

marble jackal
#

@sonic nimbus if you use template condtions, you can use the shorthand templates in the choose (as from HA 0.115):
So instead of :

  - choose:
      - conditions:
          - condition: template
            value_template: "{{ states.media_player.zone_12.state != 'on' }}"

you can use

  - choose:
      - conditions: "{{ states.media_player.zone_12.state != 'on' }}"
#

Not an answer to your question, but it does make your code a bit smaller

jagged obsidian
#

thanks, i keep forgetting about that ๐Ÿ™‚

elder quarry
#

Hi folks, am I correct that I can use a template to create a new climate entity that incorporates an external sensor for my thermostat? It's located in a hallway between 2 bedrooms, so I want the climate entity to read those (maybe an average?), rather than using the internal temp.

I'd love to see a thread or something, but I am coming up empty. I am sure this has been done many times before, so maybe I'm missing something here.

deft timber
#

which will give you the average of your 2 other thermostat

#

but not sure it will work is climate entity since it can't use the attributes of the entity it is associated to

#

so I would say a template sensor, were you can compute the average yourself using the attributes of your climate

elder quarry
#

thanks for the info

#

i'm starting to wonder if i should just engineer some node red monstrosity to raise/lower setpoint

#

ie drop to 60 or raise to 75

#

i would probably not even use the tstat temp because i only care about the 2 bedrooms. the hall will never be cold enough to matter, so maybe min_max will work?

deft timber
#

a min/max will give you the average of the states of the entity you are using. If the states are the temperature, you're good. If the states are statuses (on, off, ...), then it won't work

elder quarry
#

ah, i see

#

won't work in that case

pallid flower
#

Hi, is there anyway to catch an mqtt sensor update and ignore or discard it before HA processes it?

hollow bramble
#

Well you can filter what gets passed with the value_template

pallid flower
#

unfortunately it seems that as soon as the value_template is referenced the values will be written to the entity unless I overwrite them in the template itself. I would just like to not process the message at all.

sonic nimbus
#

is there a way, when I do a dimming via UI for the light entity, to setup my rotary encoder to brightness level?

#

Example: I have Xiomi Desk Lamp 1S , and I have a rotary encoder connected to esphome

#

so, I setup that I can dimm the light of the lamp via that encoder remotely

#

from another room for an example

#

but, when I dimm the lamp from lamp button, or via UI, after few minutes it goes to the state of that encoder

#

so, I need reverse automation, to set that encoder to value brightness lamp

#

is this doable?

turbid gate
#

If I use a value_template in a sensor, it doesn't set the sensor to that value (it worked before without a change, probably an update?), however, if I do it in the template dev tools, it gives the right output

sonic nimbus
#

Im after the similar solution

#

how to update sensor value

#

the only solution that I found is action: service: python_script.set_state data_template: entity_id: sensor.cold_water_rate state: 42

#

through python_script:

quiet niche
#

Hey folks, so I'm all about helping myself, but I'm coming up blank on how to deal with the end of the days of "entity_ID" - For example, I have a template switch and I'm calling services by entity_ID - Is there a document that says "Hey, you were doing this, but do this instead" anywhere?

#

service: climate.set_fan_mode data: entity_id: climate.thermostat_mode fan_mode: Auto Low

buoyant pine
#

That's still fine

#

It only applies to template sensors

quiet niche
#

huh.....so......hm... and the log doesn't say what yaml they're hiding out in.....

#

does it ๐Ÿ™‚

#

any suggested method for ferreting them out?

#

(and OK so the switch is still fine, no wonder I was confused)

#

thanks @buoyant pine you're always throwing me good bones

buoyant pine
#

Just gotta look where you've got template sensors I guess

quiet niche
#

Gracias amigo

#

aAAaaah... IT's this little gem, ain't it?
openevse_state: friendly_name: "OpenEVSE State" entity_id: - sensor.openevse_status icon_template: >- {%- if state_attr('sensor.openevse_status', 'state') | regex_match('^[01]$') -%} mdi:power-plug-off {%- elif state_attr('sensor.openevse_status', 'state') | regex_match('^2$') -%} mdi:car-electric {%- elif state_attr('sensor.openevse_status', 'state') | regex_match('^3$') -%} mdi:battery-charging {%- endif -%}

#

That's what I get for copy-pasting code ๐Ÿ˜›

#

OK..well, I guess that's it. Thanks again

buoyant pine
#

U welco

nocturne chasm
#

me

inner mesa
#

no, you

buoyant pine
#

no u

nocturne chasm
#

@buoyant pine and I are like this ๐Ÿคž๐Ÿป. Sometimes at parties, we find each other finishing the others sentences

nocturne chasm
#

You got it though right?

inner mesa
#

I do now

buoyant pine
#

Indeed โ„ข๏ธ

torn meteor
#

is there an elegant way to handle a None from state_attr() and output "not found" instead?

#

some kind of Jinja-jitsu like a ternary operation?

dreamy sinew
#

|default("not found")

torn meteor
#

aww yissss

#

๐Ÿช for you phnx

dreamy sinew
#

oh, maybe not

torn meteor
#

oh.

dreamy sinew
#

just tried it ๐Ÿ˜ฆ

#

{{ state_attr() if state_attr() else "Not Found" }}

torn meteor
#

i was hoping for a x = y ?: 'not found'

#

do i need to set the first statement as a var?

dreamy sinew
#

don't have to but it would make it smaller

#
{{ val if val else "Not Found" }}```
#

None is falsy

torn meteor
#

yeah. looks like default only evaluates on undefined

#

although i thought None == undefined

#

unless it's taking a string None

#

..

dreamy sinew
#

nah None is an actual thing

torn meteor
#

wait there's a thing:

#

If you want to use default with variables that evaluate to false you have to set the second parameter to true:

#

{{ state_attr('timer.empty_kitchen', 'remaining')|default('foobar', true) }} works!

dreamy sinew
#

oh neat

torn meteor
#

silly but works ๐Ÿ™‚

dreamy sinew
#

haha

#

is what it is

#

the set plus inline if is fairly compact though ๐Ÿ˜‰

torn meteor
#

you're not false

median mason
#

how can i get daily increase of covid19 confirmed case from sensor.worldwide_coronavirus_confirmed? This sensor coming from covid19 integration of HA.

deft timber
ivory delta
#

Probably simpler to find a decent API and just use the REST integration to pull the value you're after.

median mason
#

what I can think of is a Statistics sensor https://www.home-assistant.io/integrations/statistics. You configure a duration of 1 day, and you will have an attribute min & max which you can use in a template sensor to compute the difference.
@deft timber thanks i will check it

#

Probably simpler to find a decent API and just use the REST integration to pull the value you're after.
@ivory delta do you know any such API?

ivory delta
#

No because I don't have a morbid obsession with seeing how many people are dying ๐Ÿคทโ€โ™‚๏ธ

#

I'm sure plenty of them exist and it won't take much Googling to find one.

mighty ledge
#

pretty much all covid api's report accumulated totals. Always gotta do the math yourself.

desert quail
#

there is anyway to create a slider to change colors in light intead of circle?!

topaz walrus
#

Has anyone created a "real feel" sensor based off of temp and humidity?

buoyant pine
#

There's a custom integration that calculates the dewpoint from those two inputs

#

Not quite what you're looking for, but it can be used as an indication of comfort

topaz walrus
#

yeahs along the same track im looking yeah

#

i think, could be wrong. real feel temperature is based off of actual temperature and humidity

#

and dewpoint is the point at which air becomes saturated. which is why they use that number as a comfoort number like you said

buoyant pine
#

Yup

topaz walrus
#

idk if its a country difference thing or what

#

but its pretty cool

buoyant pine
#

Dewpoint is calculated from temperature and relative humidity. It's the temperature at which the relative humidity would be 100% if the amount of water in the air stays the same

#

Dewpoint less than 55F is generally considered very comfortable

topaz walrus
#

ahh ok i see how they use that now

#

its almost a scale rather than an actual temp. so 55+ gets more "sticky" humid feeling

#

pretty cool and honestly makes more sense than "real feel"

buoyant pine
#

"Real feel" and dewpoint have two different purposes

#

But yeah, dewpoint is a great indication of how humid it actually is outside

#

80F @ 70% RH will feel much more sticky than 50F @ 70% RH

topaz walrus
#

well think its cooler/more accurate now because say its 60โ€ข real feel outside based on wind, humidity and all.. that 60โ€ข means two different things when talking to someone from out west where its dry and FL where its humid.

#

using dewpoint it would be a more accurate indication

#

cool

#

learned something new today

#

that custom integration you speak of in "HACS"? searching dew point didn't turn up any results

buoyant pine
#

No clue, let me find the repo

topaz walrus
#

ill keep looking no worries

#

thanks for the help

brisk temple
#

you can setup a rest for the weather network which has a feels like

#

that has the code for the rest

#
- platform: template
  sensors:
    weather_network_temperature_feels_like:
      value_template: '{{ (states.sensor.weather_network.attributes["obs"]["f"] | int * 9/5) + 32 }}'
      device_class: temperature
      unit_of_measurement: 'ยฐF'
#

oh, that was 2hrs ago

#

@topaz walrus see above

brisk temple
#

I guess I pull dew point from another API of theirs which shows now conditions

warm needle
#

hi, trying to build a template {{ trigger.to_state.attributes.friendly_name if trigger.to_state.attributes.friendly_name!=None else "missing" }} that detects if friendly_name is present and puts a useful value if not

#

it's used in an automation trigger

#

this doesn't work because when you click execute, i think "trigger.to_state" isn't actually defined.

#

(it does when it's triggered normally, via state change)

#

how do i debug this?

inner mesa
#

if it works when trigger normally, what are you trying to fix?

#

as you say, there's no trigger when you just hit "execute", so it will never work that way. the trigger variable isn't defined because there's no trigger

warm needle
#

yeah, and that's what i've been trying to fix

inner mesa
#

you can't "fix" it

#

there's no trigger, so no trigger variable

#

what do you think the trigger variable should represent in that case?

warm needle
#

{{ trigger.to_state.attributes.friendly_name if trigger is defined else "missing" }}

#

heh

#

that works, i think

inner mesa
#

yes, that's better if that's what you're trying to do

#

initially, I thought you were trying to return the friendly_name if it's been set, or "missing" if not

warm needle
#

yeah, that's what i was trying to do, didn't realize trigger is completely undefined.

raw dust
buoyant pine
#

Yeah

thorny snow
#

is HACS supposed to show up in the Integrations list? (Container user)

inner mesa
#

if you've install the custom_component, yes

thorny snow
#

I don't recognize any custom_component[tm] from the prerequisit list for HACS... sorry if this is not the right channel

inner mesa
#

you just need to follow the instructions:

silent barnBOT
#

Home Assistant Community Store is the successor to the old Custom Updater, and can do so much more - you should check it out. They even have a Discord server for issues with HACS itself.

inner mesa
#

the fact that you had "integrations" in your question is a clue to the proper channel ๐Ÿ™‚

thorny snow
#

you are right of course

distant plover
#

Shouldn't this make sure I only get 2 decimals? {{ ((states('sensor.bad_led_over_speilet_power_2') | float) + (states('sensor.bad_taklampe_watt') | float) + (states('sensor.stuebord_taklampe_watt') | float) | round(2)) }}

#

Sometimes I get values like 45.010000000000005

lone sandal
#

hello, I tried to have a sensor of the temperature of my cpu but I don't see any add-ons for that. So I tried to create my own template :

  - platform: template
    sensors:
      temperature:
        friendly_name: 'Temperature proc'
        value_template: shell_command.temp_proc
  
shell_command:
  temp_proc: cat /sys/class/thermal/thermal_zone0/temp```
(I use hassio supervised so this cat command give me the temp of my pi)
but it doesn't work. Do you have any idea ?
lone sandal
#

ho thank you it's exactly what I want

#

@distant plover I think you have to round the 3 parameters and not just the third one

distant plover
#

But then the calculation could be incorrect, no?

lone sandal
#

no you just lost a little bit of precision

distant plover
#

Yeah, that's what I mean.

lone sandal
#

or you can do that :

#
        + (states('sensor.bad_taklampe_watt') | float)
        + (states('sensor.stuebord_taklampe_watt') | float)) | round(2))
        }}```
#

so you are sure that the round is on your 3 parameters

#

because I think your calculation without this parenthesis round only the third parameter

#

the | operation seems to be calculated before the +

distant plover
#

I see. Thank you ๐Ÿ™‚

lone sandal
#

๐Ÿ˜‰

pallid flower
#

Hi all, I'm using the following template to clean up mqtt input from a ble thermostat. It is perfectly functional but I get the feeling I should be able to shorten the syntax because I'm referencing the same value twice. ' {{ value_json['LYWSD03-24c956'].Humidity if value_json['LYWSD03-24c956'].Humidity != null else states('sensor.ble_temp.attributes.humidity') }} ' Any thoughts?

#

{{ value_json['LYWSD03-24c956'].Humidity if value_json['LYWSD03-24c956'].Humidity != null else states('sensor.ble_temp.attributes.humidity') }}

#

Sorry just realised it should be backticks

ivory delta
#

Where are you using this? I believe you can use variables in scripts/automations.

pallid flower
#

I'm using it in a sensor template

ivory delta
#

Then you'll probably add as much work/text making it a variable as you'd save by using that variable twice.

#

It might look messy right now but it's probably not worth refactoring.

pallid flower
#

I guess, just a bit ugly was hoping that a bit of 'Jinja-Fu' was available. Thanks anyway

dapper aurora
#

I have this binary sensor w/ this value template
value_template: "{{now().weekday() in (0,1,2,3,4) and states('sensor.date')}}"
any thoughts on why it wouldnt be working? i just want it to evaluate to true/on if tomorrow is monday - thurs

ivory delta
#

When you say it's not working, what's it doing?

dapper aurora
#

it seems to never be reevaluating

#

it currently says false but today is a saturday, so it should say that. but for the past week it never evaluated to true

ivory delta
#

If you put that into devtools > Templates, what does it tell you?

#

Then try this and repeat:
{{ states('sensor.date') and now().weekday() in (0,1,2,3,4,) }}

buoyant pine
ivory delta
#

Where's the fun in that? ๐Ÿ˜‰

dapper aurora
#

@buoyant pine i dont want it to evaluate as true if today is a friday

buoyant pine
#

You can define the days

ivory delta
#

The workday integration allows that.

dapper aurora
#

oh man

ivory delta
#

But first... you're going to learn something ๐Ÿ™‚

dapper aurora
#

well now i want my binary sensor to work ๐Ÿ™‚

ivory delta
#

Try your template, then try mine.

dapper aurora
#

seems to be working in the template

ivory delta
#

Yours shouldn't. The first half of your and statement won't evaluate.

#

The reason yours isn't working properly is that ands will shortcut. If the first half is false, it won't bother evaluating the second half.

#

Put the thing that changes all the time (sensor.date) first ๐Ÿ™‚

dapper aurora
#

ohhhh interesting

#

well it just says false, which probably is what it would do if shortcutting since its a saturday

#

thanks!

ivory delta
#

You can tweak the numbers to prove that ๐Ÿ™‚

dapper aurora
#

yeah i have been ๐Ÿ™‚

silent barnBOT
harsh anchor
#

hello wonderful people of the saturday evening templates
or am I the only one? ๐Ÿ˜‚
so I've got myself a iotawatt, and it outputs a lot of json
is there a json way so that I can have all single outputs under a single umbrella, like sub-entities?
I tried like so
https://paste.ubuntu.com/p/PNXjD5yKBS/
but it does not create sub-entites

#

moreover i did use the outputs[0] selector, but it still carries all the values without care for my selection

#

do I really need to create a separate entity for each value?

ivory delta
#

json_attributes is the right way to get certain fields from the response into attributes on the entity you're creating. What state/attributes do you get from your current configuration?

#

Also, what does the JSON actually look like?

harsh anchor
#

taken with curl and jq from commandline, and it's exactly the same I see in my device: its value is the entire json string

ivory delta
#

Yes, that's normal. What are the attributes of the entity it created?

#

Remember entities have state (one) and maybe attributes too (many). You can check them at devtools > States.

harsh anchor
#

honestly I'm not sure what I should tell you: what I see is what I showed you already in json form

#

I'm playing around with this now, and it's weird: if I use value_template: '{{value_json.inputs[0]}}' I get everything in the states, including also outputs as if the value template had no effect
but if I remove the value template, or leave just value_json then nothing shows
I'm baffled

ivory delta
#

You've said several times what the state is. What are the attributes?

harsh anchor
#

my last paste was the attributes, straight from the screen

ivory delta
#

So which piece of information do you want to be the state? You can only pick one.

harsh anchor
#

input voltage is fine

ivory delta
#

Which field is that? inputs[0].Vrms?

harsh anchor
#

yeah

ivory delta
#

So you should only need to do value.inputs[0].Vrms

harsh anchor
#

right

ivory delta
#

You can test if it works in devtools > Templates with something like this:

  {
    "channel": 0,
    "Vrms": 229.2475,
    "Hz": 50.00404,
    "phase": 1.48
 }]}' | from_json %}

{{ json.inputs[0].Vrms }}```
#

Feel free to experiment with the last line to extract different values.

harsh anchor
#

yes yours does do what I expect, but when I put it in my config it does not for some reason.... well I'll investigate more
you already opened my eyes on the developer tools ๐Ÿ™‚

#

now somehow I have a ton of attributes but no numerical values lol ๐Ÿ˜‚

#

so I wrote a sensor like this
iotawatt_input_5:
value_template: "{ states.sensor.iotawatt.attributes.inputs[5].Watts }"
but in the UI I don't see the state as a numerical value, but as a json property...

#

trying to put it in lovelace it says "entity is non-numeric

harsh anchor
#

nothing, looks like using states.sensor.iotawatt.attributes.inputs[n].Watts doesn't return a number

#

almost like the templated entity is missing a state variable, only has attributes

harsh anchor
#

got it, templating wasn't putting the right number of curly braces

high olive
#

Why do I get Failed to call service input_number/set_value. expected float for dictionary value @ data['value'] when trying to make a service call...
In this template (soon to be used in an automation)

value: {{ states('input_number.fan_speed_trickle') | int + 100 | round | float }}
entity_id: input_number.fan_speed_trickle

It does "resolve" in templates... But not in service calls..
it does work if I just input a number such as 1000 (rpm)

ivory delta
#

What service are you calling?

inner mesa
#

You need double quotes around it

high olive
#

Trying to call input_number/set_value

#

Double quotes you say.. ?

inner mesa
#

The template

high olive
#

No...

value: "{{ states('input_number.fan_speed_trickle') | int + 100 | round | float }}"
entity_id: input_number.fan_speed_trickle
inner mesa
#

Yes, that

high olive
#

Same error.

inner mesa
#

You also need some parens. Youโ€™re currently rounding 100

#

That float doesnโ€™t belong there either

high olive
#

Ummh.. Okay... ?
Yeah, I have tried a few different ways, non has really allowed me to call the service.

inner mesa
#

This wonโ€™t work in devtools -> services because of a bug

#

It should work in a script

high olive
#

... or an automation?

inner mesa
#

The dev tools donโ€™t properly cast the string output of a template

#

Yes, same thing

high olive
#

So this should work in an automation:

value: "{{ states('input_number.fan_speed_trickle') | int + 100 | round | float }}"
entity_id: input_number.fan_speed_trickle

?

inner mesa
#

I think it should be better in 0.117

high olive
#

Ahh, I didn't know about that bug..

inner mesa
#

You donโ€™t need the |float

#

Iโ€™ll see if itโ€™s fixed in 0.117. Templates return actual data types there

high olive
#

Cool, Yeah. it works in my automation! ๐Ÿ™‚ Thanks!
Much appreciated for your time and effort to help us!
๐Ÿ™‡

pale idol
#

so im trying to trigger an automation wehever a light state changes from unavailable. I've got this template {% if 'light.' in entity_id and old_state == 'unavailable' %} {% endif %}, but it doesnt seem to be triggering

inner mesa
#

where did those variables come from?

#

if looks like you grabbed a single line out of a larger template

#

or it's just completely wrong

pale idol
#

its probably the latter

inner mesa
#

ok, then random attempt ๐Ÿ™‚

pale idol
#

that thread was the inspiration

inner mesa
#

oh, nevermind. I haven't used that

pale idol
#

@inner mesa I'm not opposed to alternative methods though

inner mesa
#

at the very least, I think you'd want old_state.state == 'unavailable, but I'm still working through how that's supposed to work

pale idol
#

if it helps, im doing this through the webui

#

rather than directly editing the yml

inner mesa
#

doesn't really matter.

#

You're still typing it in

pale idol
#

ok

inner mesa
#

~share the whole

silent barnBOT
pale idol
inner mesa
#

yeah, I don't really get where that stuff in the thread is coming from or how it even works

#

this works:

#
- alias: 'Event Test'
  initial_state: true
  trigger:
    - platform: event
      event_type: state_changed
  condition:
    - condition: template
      value_template: "{{ 'switch.fr_' in trigger.event.data.entity_id }}"        
  action:
    data:
      message: foobar
    service: persistent_notification.create
#

and to test the state, you'd want trigger.event.data.old_state.state == 'unavailable'

#

that thread makes it sound like some other variables are being created, and I'm not familiar with them

pale idol
#

oh it doesn't like that. now i've got an endless stream of notifications

inner mesa
#

what do you have now?

#

it works fine for me when I switch switch.fr_* entities on and off

pale idol
inner mesa
#

you get a flood of notifications with that?

pale idol
#

yes

#

every 2s or so

inner mesa
#

is it possible that you have light.* entities suddenly going unavailable?

pale idol
#

its unlikely

inner mesa
#

or at least with a "from_state" that's unavailable

pale idol
#

i do have a large number of them, but the network is overall very stable and run by zigbee2mqtt

#

there is a 1minute timeout between the light disappearing and when it actually gets labelled unavailable too

inner mesa
#

once I add that "unavailable" check, I get nothing (as expected):

#
- alias: 'Event Test'
  initial_state: true
  trigger:
    - platform: event
      event_type: state_changed
  condition:
    - condition: template
      value_template: "{{ 'switch.' in trigger.event.data.entity_id and trigger.event.data.old_state.state == 'unavailable' }}"        
  action:
    data:
      message: foobar
    service: persistent_notification.create
pale idol
#

I have that in my last paste as well.

inner mesa
#

I changed "unavailable" to "on" and it notifies me whenever I turn something off (old state was "on")

#

everything is working exactly as I expect

pale idol
#

ok.

inner mesa
#

i really don't like the UI changing " in to '', but other than that ๐Ÿคท

pale idol
#

maybe I do have something flapping, but I'm not sure what. I bet there is a way to get the offending entity_id into the notify message

inner mesa
#

there is, by using exactly the same template in the message of a notification

#
  action:
    data:
      message: "{{ trigger.event.data.entity_id }}"
    service: persistent_notification.create
#

kinda sounds like it's doing its job and telling you about broken lights

pale idol
#

interesting. Its only the tasmota bulbs

#

seems like a bug thats happened before

inner mesa
#

try updating, I guess

pale idol
#

im already on 8.3.1 though

inner mesa
#

then I got nothin'

#

I'm going to declare the automation as "working as designed", though

pale idol
#

lol. thats fair. its definitely isolated to my setup

#

thanks for the help

silent barnBOT
next bluff
#

I have the template posted up in the paste bin, how I can turn off the entities based on that now?

buoyant pine
#
data:
  entity_id: "{{ state_attr('sensor.lights_turned_on_for_two_hours', 'light_entities') }}"
buoyant pine
#

@next bluff

#

Also...

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.

thorny snow
#

how would i get the values of a input_text and input_number and use it in a autonation

arctic sorrel
#
{{ states('input_text.banana') }}
#

See the docs linked in the channel topic ๐Ÿ˜‰

thorny snow
#

@arctic sorrel will that work with the input_number?

arctic sorrel
#

Have you read the docs yet?

thorny snow
#

ye but im dumb

arctic sorrel
#

TL/DR: Yes, it works with any entity

thorny snow
#

ok

#

sorry

arctic sorrel
#

There's a lot of details though

#

It depends on what you're trying to do, what version of HA you're on, and more

#

Hence why I keep commenting on the need for actual details ๐Ÿ˜‰

thorny snow
#

@arctic sorrel so i need to make this work

transition: input_text.fade_time
color_name: red
brightness_pct: input_number.end_brightness``` but im new to templates
arctic sorrel
#

Well, you don't have to keep tagging ๐Ÿ˜‰

thorny snow
#

sorry

arctic sorrel
#

See what I wrote before?

#
brightness_pct: input_number.end_brightness
``` won't work, you need that format I shared
thorny snow
#

ye i dont realy know bc im new to this

arctic sorrel
#
{{ states('input_text.banana') }}
#

That's how you get the state out, so...

#
brightness_pct: "{{ states('input_number.end_brightness')|int }}"
#

Same for the transition

thorny snow
#

so ```data:
power: true
transition: "{{ states('input_text.fade_time')|int }}"
color_name: red
brightness_pct: "{{ states('input_number.end_brightness')|int }}"

arctic sorrel
#

Should be good

thorny snow
#

didnt work

arctic sorrel
#

Where were you putting that?

#

That all goes in a script, or automation

thorny snow
#

can you send images

arctic sorrel
#

Nope

thorny snow
#

auto

arctic sorrel
#

Auto?

thorny snow
#

automation

arctic sorrel
#

If you dropped that lot in the Service data section, you need to remove data:

thorny snow
#

ok

arctic sorrel
#

Save the automation, and push Execute

#

If it doesn't work, check the log file

thorny snow
#

ok

#

Error executing script. Invalid data for call_service at pos 1: expected float for dictionary value @ data['transition']

arctic sorrel
#

Replace |int with |float then

thorny snow
#

so is it "{{ states('input_text.fade_time')|float }}"

arctic sorrel
#

Of course, you may want to swap that text for a number ๐Ÿ˜‰

thorny snow
#

i dont like the sliders

arctic sorrel
#

๐Ÿคท

thorny snow
#

is it correct like this service: lifx.set_state 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
#

Looks ok, go paste that into devtools -> Templates

thorny snow
#

done