#templates-archived

1 messages · Page 37 of 1

marble jackal
#

availability: "{{ 'sensor.shellyuni_e868e7f472ec_adc' | has_value }}" is probably what you want there

errant hinge
#

Would appreciate any advice on converting a select entity value to a time please? The values appear to be strings, with values being HH:MM:SS format.

  - '00:00:00'
  - '00:01:00'
  - '00:02:00'
  - '00:03:00'```
I'm looking to use the conversion in a binary sensor template:
```template:
    - binary_sensor:
        - name: "On GivEnergy Timed Charge"
          state: >
            {{ states('select.givtcp_ceXXX_charge_start_time_slot_1') | as_datetime | as_local <= now() 
            < states('select.givtcp_ceXXX_charge_end_time_slot_1') | as_datetime | as_local }}```

The above currently fails with `AttributeError: 'NoneType' object has no attribute 'tzinfo'`
marble jackal
#

today_at(states('select.bla'))

#

which will give issues if you compare 23:00:00 as start with 01:00:00 as end and expect it to be true

errant hinge
#

Excellent point, thank you.
Fortunately our off-peak tariff is 00:30 to 04:30 so not an issue currently.

marble jackal
#

if one starts at 00:30 the other must end at 00:30

#

but if it's only two tariffs, you can do the easy check

digital harness
#

i have build an alternative template, what do you think? template:

  • sensor:
    • name: "BatteriespeicherProzent04"
      state_class: measurement
      value_template: >-
      {% if states('sensor.shellyuni_e868e7f472ec_adc') | float(0) > 27.2 %}
      100
      {% else %}
      {{ ((states('sensor.shellyuni_e868e7f472ec_adc') | float(0)-20.0) / 0.222) | round(0) }}
      {% endif %}
      unit_of_measurement: "%"
      icon_template: "mdi:battery-charging-high"
mighty ledge
#

it's not correct if you're using >-. Your template is not moving to the next line

#

also, you can set a variable instead of converting to a float twice

obtuse zephyr
#

Also, your previous example was using the new style of template sensor, but this is kinda sorta the legacy format, as it uses value_template but is missing platform. I'd recommend using the initial way you had it w/ state

mighty ledge
#
{% set adc = states('sensor.shellyuni_e868e7f472ec_adc') | float(0) %}
{{ iif(adc > 27.2, 100, (adc - 20) / 0.222) | round(0) }}
obtuse zephyr
#

Also also, I have no idea about that formula, but it seems wildly different from your initial example. For example, if you use 27 in the equation, it results in 31.5.

mighty ledge
#

I would assume the eq would be

#
{% set adc = states('sensor.shellyuni_e868e7f472ec_adc') | float(0) %}
{{ iif(adc > 27.2, 100, adc / 0.272) | round(0) }}
obtuse zephyr
#

Sounds like 20 = 0 though

digital harness
#

yes its a LifePO4 Battery. 20V meins 0% and 27,2V means 100%

slate laurel
#

Can someone help me out with icon templates? This is my code, which I can't get to work:

switch:
  - platform: command_line
    switches:
      melody_1:
        command_on: '/usr/bin/curl -sS -X GET "http://192.168.1.10/?action=command&command=melody1"'
        command_off: '/usr/bin/curl -sS -X GET "http://192.168.1.10/?action=command&command=melodystop"'
        command_state: '/usr/bin/curl -sS -X GET "http://192.168.1.10/?action=command&command=value_melody"'
        value_template: '{{ value > "value_melody: 0" }}'
        friendly_name: "Melody 1"
        icon_template: >
          {% if value > "value_melody: 0" %} mdi:music-note
          {% else %} mdi:music-note-off
          {% endif %}```
mighty ledge
#

command line doesn't have icon_templates

#

and your value template isn't correct

slate laurel
mighty ledge
#

Ok, color me surprised, it's one of the few that mst have it

#

anyways, your templates isn't correct

#

you're comparing greater than with 2 strings

slate laurel
#

Then the template itself might be the issue. What is wrong about it?

#

the "value_template" is working

mighty ledge
#

ask yourself.... is a greaterthan or less than b?

slate laurel
#

The camera "command_state" is outputting: "value_melody: 0"

mighty ledge
#

ok, so then parse out the 0

slate laurel
#

Somehow this works value > "value_melody: 0"

#

for the command_state, but not for the icon_template.

mighty ledge
#

(value | split(':'))[-1].strip() | float(0) > 0

slate laurel
#

Let me try that

mighty ledge
#
value_template: "{{ (value | split(':'))[-1].strip() | float(0) > 0 }}"
icon_template: mdi:music-note{{ '' (value | split(':'))[-1].strip() | float(0) > 0 else '-off' }}
slate laurel
#

TemplateSyntaxError: tag name expected

mighty ledge
#

that error does not make any sense

#

post how you used it

#

maybe split isn't a filter

#

do this instead

#
value_template: "{{ value.split(':')[-1].strip() | float(0) > 0 }}"
icon_template: mdi:music-note{{ '' value.split(':')[-1].strip() | float(0) > 0 else '-off' }}
slate laurel
mighty ledge
#

can you post what you're using please

slate laurel
#

yes, one sec

plain magnetBOT
#

@slate laurel I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

You didn't copy what I wrote

#

you have single quotes outside your template

#

and single quotes inside

slate laurel
#

ah now I see it

mighty ledge
#

Notice how I have double quotes outside and single quotes inside?

slate laurel
#

Yes I do now

#

Next error 🙂

#

The system cannot restart because the configuration is not valid: Invalid config for [switch.command_line]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'value') for dictionary value @ data['switches']['babycam_melody_1']['icon_template']. Got "mdi:music-note{{ '' value.split(':')[-1].strip() | float(0) > 0 else '-off' }}" invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'value') for dictionary value @ data['switches']['babycam_melody_2']['icon_template']. Got "mdi:music-note{{ '' value.split(':')[-1].strip() | float(0) > 0 else '-off' }}". (See ?, line ?).

mighty ledge
#
icon_template: mdi:music-note{{ '' if value.split(':')[-1].strip() | float(0) > 0 else '-off' }}
slate laurel
# mighty ledge ``` icon_template: mdi:music-note{{ '' if value.split(':')[-1].strip() | float(0...

The system cannot restart because the configuration is not valid: Invalid config for [switch.command_line]: invalid template (TemplateAssertionError: No filter named 'split'.) for dictionary value @ data['switches']['babycam_melody_1']['value_template']. Got "{{ (value | split(':'))[-1].strip() | float(0) > 0 }}" invalid template (TemplateAssertionError: No filter named 'split'.) for dictionary value @ data['switches']['babycam_melody_2']['value_template']. Got "{{ (value | split(':'))[-1].strip() | float(0) > 0 }}". (See ?, line ?).

mighty ledge
#

that's an old error or you didn't update the template

#

split isn't being used as a filter

#

Did you undo a bunch of crap?

slate laurel
#

Nope, I just updated the "icon_template" that you just send me.

mighty ledge
#

sorry man, but you're lying somehow

slate laurel
#
        icon_template: mdi:music-note{{ '' if value.split(':')[-1].strip() | float(0) > 0 else '-off' }}```
mighty ledge
#

whether you know it or not

slate laurel
#

Hahahahaha

#

Everyone lies

mighty ledge
#

Ok, you just posted above

    value_template: '{{ value.split(':')[-1].strip() | float(0) > 0 }}'
#

and now you're using

    value_template: "{{ (value | split(':'))[-1].strip() | float(0) > 0 }}"
#

so which one are you actually using in your config?

#

because the | is not correct,

#

Please just copy and paste this, do not try to type it yourself. The whole thing

        value_template: "{{ value.split(':')[-1].strip() | float(0) > 0 }}"
        icon_template: mdi:music-note{{ '' if value.split(':')[-1].strip() | float(0) > 0 else '-off' }}
slate laurel
#

that worked

#

rebooting now

#

Thanks for helping and your patience 🙂

mighty ledge
#

np

slate laurel
#

Did not alter anything to it actually

#

The icon is still not working now

mighty ledge
#

but the state changes? because that makes no sense.

slate laurel
#

The state changes indeed

#

oh wait

#
  icon: hass:music-note
switch.babycam_melody_1:
  icon: hass:music-note```
#

that was my customize.yaml

#

dumb me 🤣

#

Might have been the issue all along... it works now. Thanks for your help!

#

Have a slightly smoother solution now anyways.

dusk sorrel
#

Is there any way to buffer serial data. I am using serial integration.

#
  • platform: serial
    serial_port: /dev/ttyUSB0
    baudrate: 115200
#

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

#

is working

#

Important need is to buffer

mighty ledge
#

Buffer in regards to what? Adding a buffer won’t do anything

#

If you want to get technical, the baud rate is equivalent to your buffer size on the serial port

dusk sorrel
#

my serial device sends data at every second then i can get data {{states('sensor.serial_sensor')}}

#

But this {{states('sensor.serial_sensor')}} can get one data end with /n or /r

#

9 9 0 900 5 /n
8 1 1 100 1 /n
7 600 7293 553 352 /n
6 100 2 1 1 1 1 2 30000 0 /n
5 9900 0 30000 50 65 /n
4 15000 1000 1500 1000 800 /n
3 90 500 0 0 0 /n

#

But i need above these all get simultanueous.

dusty hawk
#

The Attribute 'rain' is not provided when no rain is expected. Shouldn't the is defined catch that? I've also tried the new has_value() and it fails as well. The Template editor just says that 'dict object' has no attribute 'rain' (This works fine however when Rain is expected).

  {% if state_attr('sensor.openweather_report', 'hourly')[1]['rain']['1h'] is defined %}
   {{ ( state_attr('sensor.openweather_report', 'hourly')[1]['rain']['1h'] | float(0) / 25.4 ) | round(2) }}
  {% else %}
     0
  {% endif %}

So when no rain is expected, the state (that's fed by this template) reports as unavailable instead of zero.

mighty ledge
dusty hawk
#

Ah, since rain is not defined, rain.1h can't be. Got it. Thanks!

fiery mirage
#

Hi, I started with HA yesterday and a friend gave me a template for yaml to check my printer status, and now it's not working. It's returning Unknown, but when I test it on developer tools it works, can anyone help me?

obtuse zephyr
#

If you share it and the error it produces, someone can try and help

plain magnetBOT
#

@fiery mirage I converted your message into a file since it's above 15 lines :+1:

fiery mirage
#

on my views, power returned, returns a value, but hotend temperature returns: Unknown

#

if I check the sensor it shows OK and on its attributes, shows all json values correctly

obtuse zephyr
#

Looks like your unit of measure might be incorrect, but that doesn't seem like it'd cause that. What does your home-assistant.log say

fiery mirage
#

I don't see anything related to it

#

I'm going to delete it and restart HA to check

#

oh I figured it out.. the problem lied elsewhere:
switch:

Voron Power Switch

#

it seems that is breaking the rest

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

inner mesa
#

You need a line break after >-

tepid onyx
#

G'Day
I'm having problems converting this sensor to the recommended template sensor format:
`sensor:

  • platform: template
    sensors:
    last_alexa:
    entity_id:
    - media_player.kitchen_echo_dot
    - media_player.main_bath_echo_dot
    - media_player.office_echo_dot
    - media_player.lounge_echo_dot
    - media_player.bedroom_echo_dot
    value_template: >
    {{ states.media_player | selectattr('attributes.last_called', 'eq', True) | map(attribute='entity_id') | first }}`
#

Because it's got a list of entity_id

#

I read some posts on the forum where the recommended format is supposed to automatically pick the entity_id (which works fine if it's just one) but it doesn't seem to pick multiple entity_id

rose scroll
#

Well...you don't need to list out all the media_players you wish to track, since you're already filtering through all of them in the value_template.

tepid onyx
#

I tried removing the entity_id key in the new format but it didn't work

rose scroll
#

Because you need to change the format of the whole block to the new structure. It's still using the old one.

tepid onyx
#

yeah...i formatted accordingly to the new template sensor format but removed entity_id

#

as per the docs...I've converted all my other sensors this is the only one with a list

#

or maybe I fat fingered it...

rose scroll
#

That codeblock you posted above is still in the old format. Can you post what you have so far in trying to convert to the new format?

#

Point being...the new format can't have the entire entity_id: list in the first place. Just remove it in the new format.

tepid onyx
#

  - sensor:
      - name: "last_alexa"
        state: >
          {{ states.media_player | selectattr('attributes.last_called', 'eq', True) | map(attribute='entity_id') | first }}```
tepid onyx
#

son of a whore. I was hitting the "ALL YAML CONFIGURATION" button to reload but updating a template sensor appears to require a full HA restart

#

disregard it works fine

inner mesa
#

Only the first time you add template:

#

After that, you can 'reload all YAML'

visual matrix
#

Hi guys any way that would make it work?
attributes: !include dictionnaries/dog_food/{{ states('input_select.dog_food_list') }}.yaml

exotic grail
#

Would be nice if the reload could tell you what isn't going to be picked up

orchid oxide
#

is it possible to in to get a list of all integrations installed using templates

#

i know you can do the other way around

orchid oxide
#

not an exhaustive list 😦

shadow hatch
#

I want to convert my weather station output wind speed from m/s to knots can you please help
My information is comeing from the mqttbroker using rtl 433 esp32 bord

tepid onyx
plain magnetBOT
#

@dusk sorrel I converted your message into a file since it's above 15 lines :+1:

verbal mica
#

Hello, im trying to use smart plug sensor entity to trigger reload smart plug (binary_sensor.plug_problem reloads switch.plug using call service homeasisstant.reload_config_entity ).
Im currently using working "Choose" action with conditions in it for each plug but I wanna simplfy this with "trigger.entity_id".
How do I use templates to do "{{ switch+ 'trigger.entity_id' }}" without "_problem" in triggers name?

ebon yoke
#

what is the correct yaml syntax for a template sensor? is it under sensor: - platform: template or template: - sensor?

verbal mica
#

it's platform device
trigger:

  • type: problem
    platform: device
    entity_id: binary_sensor.test_plug_error
    domain: binary_sensor
prisma mason
#

This template used to work, but now i get "statistics_not_defined":

  • sensor:
    name: Solar Panel Production
    state_class: total_increasing
    unit_of_measurement: kWh
    device_class: energy
    icon: mdi:solar-panel-large
    state: >
    {{ states("sensor.helper_envoy_current_power_production_riemann")|float }}
#

And also, entity not available

marble jackal
prisma mason
#

Is "state_class: total_increasing" incorrect?

marble jackal
#

Most probably yes

#

But your template should be on the next line if you use >

prisma mason
#

I changed it to measurement, still the same error

#

When using dev tools it gives the error 'float got invalid input'unknown'

#

However when I check the helper, it has no problems in the statistics screen

#

ChatGPT found the problem, float should be float(0)

mighty ledge
#

if that's just an integration sensor, just set that up properly and you don't need the template sensor.

#

and chatgpt bandaided the problem, if you really want that template, it only needs to be {{ states("sensor.helper_envoy_current_power_production_riemann") }}

prisma mason
#

Because the energy dashboard wont take the helper as an input

mighty ledge
#

then you didn't set the helper up properly

#

if you set the helper up via the UI, it should just work as it will attach all the necessary attributes needed for long term stats

prisma mason
#

It does perfectly show the production in kwh

#

But for some reason, me and everybody else using enphase needs this template

mighty ledge
#

that doesn't make any sense, as enphase isn't creating the kWh sensor

#

it's creating the kW or W sensor which you're integrating

prisma mason
#

Yes, and the riemann helper turns it into kwh

mighty ledge
#

yes, and that would have state_class and device_class pre built into it

#

Can you post whatever guide you're using? because it's misleading you and everyone else using enphase

mighty ledge
#

Yeah, post 93 confirms that the template is not needed if you keep reading

#

So if you have a power sensor, just create a integration sensor and you're done

#

Keep in mind that you have to wait for the integration sensor to be placed into the database (takes about an hour)

#

regardless, if you're dead set on using the template sensor.... just remove | float(0)

#

it's not needed because you're not performing math

prisma mason
#

Missing*

#

But i'll have a look at the integration sensor

mighty ledge
#

did you add your integration sensor via the UI or yaml?

prisma mason
#

UI

mighty ledge
#

does your source sensor have device_class: power?

prisma mason
#

How do I check?

mighty ledge
#

same way you checked the other sensor

#

you just said device_class was missing on the helper

#

are you checking via

plain magnetBOT
mighty ledge
#

?

prisma mason
#

It doesnt have device class

mighty ledge
#

that's probably the root of the problem, does it have a unit_of_measurement?

#

this is for the source sensor, not the helper

prisma mason
#

Yes, W

mighty ledge
#

yeah, then it just needs a device_class and it should propagate. Personally, I'd write up an issue against your enphase integration.

prisma mason
#

There's 4 at the moment :p

#

Because the official one isnt working

mighty ledge
#

Yeah, write up the issue against whichever one you're using

prisma mason
#

Ok

#

Thanks for the help

plain magnetBOT
#

@dusk sorrel I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

@dusk sorrel you're accessing item 6 and 7 which sometimes do not exist

#

if you want the last 2, use -2 and -1 instead

dusk sorrel
#

mmhna i am test it.

#

mmm same ....

#

@mighty ledge same result.

#

is that possible parsing process slow than incoming serial data?

mighty ledge
#

@dusk sorrel what's teh actual error

silent seal
#

If your array doesn't have at least two items in it, accessing -2 and -1 will probably error too.

mighty ledge
#

it costs money?

silent seal
#

It's a Discord avatar decoration, part of nitro

plain magnetBOT
#

@woven folio I converted your message into a file since it's above 15 lines :+1:

woven folio
#

the question is, how the missing data did mess the template totals so badly? (i can assure i never used 16k kWh since started using that Shelly EM, in fact, the real total consumption of those 2 channels, since start, is around 850kWh, as per sum of middle graph channels).

mighty ledge
#

so when they jump from 0 to whatever they were before, that jump is added on

#

you should incorporate an availability template

woven folio
#

ah

#

i suspected something similar

#

think is enough if i use one of the two channel sensor availability, because it's one shelly alone.

#

thanks for the help, i'll see if it works in the next days

mighty ledge
#

You can use one or both

#

I'd probably do both

#

but that's up to you

woven folio
#

in the same line?

mighty ledge
#

yes, just need an and

#
{{ states('xxxx.xxx') | is_number and states('yyyy.yyy') | is_number }}
woven folio
#

ok, i'll give it a try
thanks again

marble jackal
silent seal
#

Ahh, I missed the context 🙂

marble jackal
#

Wait, directly accessing -2 doesn't

amber hull
#

Were there changes in the 2023.4x releases that changes template sensors? Several of my template sensors stopped working. They worked in beta and on the .0 release

mighty ledge
#

seems like you're having other issues unrelated to commandline or template sensors

marble jackal
#

There is new functionality, but nothing breaking

amber hull
#

No

mighty ledge
#

Well, nothing changed with command line or template sensors and you're having issues with both

marble jackal
#

Can you give an example of a non working sensor?

amber hull
#
sensor:
  # Sensor to track available updates for supervisor & addons
  - platform: command_line
    name: Supervisor updates
    command: 'curl http://supervisor/supervisor/info -H "Authorization: Bearer $(printenv SUPERVISOR_TOKEN)" | jq ''{"newest_version":.data.version_latest,"current_version":.data.version,"addons":[.data.addons[] | select(.version != .installed)]}'''
    value_template: "{{ value_json.addons | length }}"
    json_attributes:
      - newest_version
      - current_version
      - addons
silent seal
#

Why not use secrets in the sensor? 🤔

mighty ledge
#

packages?

amber hull
#

?

mighty ledge
#

are you running packages?

amber hull
#

Yes

mighty ledge
#

are other things in those packages working?

amber hull
#

I'll paste better info when I get home

mighty ledge
#

to me, it seems like somthing changed in configuration.yaml and things are loading

#

because you'd have errors

amber hull
#

Everything else works except the status of the updates

mighty ledge
#

what do you mean 'status of the updates'

amber hull
#

I changed nothing. HACS has update, version of core, etc

marble jackal
#

Can't you get all of this out of the update entities?

amber hull
#

Don't understand

amber hull
#

No. Mine would give me which HACS needed update, which addon etc

silent seal
#

But those all have update entities?

mighty ledge
#

I think there's some miss communication happening here

marble jackal
#

If you enable HACS experimental mode

mighty ledge
#

I don't think he's talking about update entities

amber hull
#

I'm talking about if a HACS integration or card update is available it would list which one and the version

mighty ledge
#

that's not working?

amber hull
#

Same with add ons, core su

marble jackal
mighty ledge
#

well, as an aside, about 4 major versions ago, HACS completely changed how update querying works

amber hull
#

Ok. Something to learn later. Still something changed as it worked until .3 was released

mighty ledge
#

it went from all the time, to every 6 hours, to every 48 hours with fancy code

#

FWIW, I'm on 2023.4 and all of the above are working normally

amber hull
#

Not only HACS, but core, su and other sensors stopped as well

silent seal
#

Wait a second, those are under sensor

mighty ledge
#

right, which circling back, you have template sensors and command line sensors that are not working as well. I.e. Something major is going on and everything you're listing is a symptom of the real problem.

silent seal
#

Template sensors should be updated and put under template

#

If you run a config check, what do you get out?

amber hull
#

I'll check it when I get home

mighty ledge
#

TBH it seems like your configuration isn't loading all of the integrations

#

and you may be in safe mode

marble jackal
amber hull
#

It doesn't look like safe mode.

silent seal
amber hull
#

Maybe after 10.0 release locked my system, something got hosed

peak juniper
#

Any idea how I can make a sensor that counts how many of a certain sensor are over a certain value

#

I have this so far:

        {{ states.sensor | select('search', 'plex_usage_monthly') 
        | selectattr('state', 'ne', '>0') | list | count }}
#

but something is wrong with that

inner mesa
#

there are a few things wrong

#

select('search', 'plex_usage_monthly') is trying to test a state object against a string

#

and this is using the wrong syntax: selectattr('state', 'ne', '>0')

#

{{ states.sensor | selectattr('object_id', 'search', 'plex_usage_monthly') | map(attribute='state')|map('float')|select('gt', 0) | list | count }}

peak juniper
#

ah I see. I tried to modify something that came up from a search where the person was counting sensors with a certain value, I guess a string in that case

#
TypeError: '>' not supported between instances of 'float' and 'str'
inner mesa
#

I edited it

peak juniper
#

ah

#

that's perfect - thanks so much

#

does the job entirely!

rose scroll
#

Just got my hands into the new Jinja macros capability mindblown Just to check though...for new macros and new .jinja files to be picked up, is a HA restart necessary?

inner mesa
#

You need to reload custom templates

rose scroll
#

Great, thanks for the pointer!

dusk sorrel
#

It can catch and parse 100% of the data coming in one second apart. However, since the data is hundreds of milliseconds apart, it can't be caught and parsed, or sometimes it can be

orchid oxide
#

is it possible to get the link from "Read release announcements" via template? Rightnow, for OS update it's different than the release_url attribute

marble jackal
#

@orchid oxide where do you see that link?

#

this one you mean?

#

and they look quite similar to me 🙂

thorny canyon
#

Thanks again @orchid oxide for your hint recently. I solved it by adding a separate sensor with correct value_template for the type of waste and added both sensor (date and type) states in the automation message. 🤗

plain magnetBOT
#

@crimson lichen I converted your message into a file since it's above 15 lines :+1:

crimson lichen
#

Home Assistant Operating System Update:
|-> Installed Version: 9.5
|--> Latest Version: 10.0
|--> 11:14:43 Wednesday 19-Apr-2023

plain magnetBOT
#

@crimson lichen I converted your message into a file since it's above 15 lines :+1:

floral shuttle
#

can we also reject device_attr('manufacturer','Fibargroup')? currently I set a rather extensive ignore liste verbosely, but it would be much easier if I could simply reject these

#

like this in pseudocode: {{expand('group.switches_sensors_actueel') |rejectdevice_attr('manufacturer', 'Fibargroup') |map(attribute='entity_id') |list}}

mighty ledge
#

| reject('is_device_attr', 'manufacturer', 'Fibargroup')

floral shuttle
#

right! thx. I also forgot the order of things.... but this does what I need: {{expand('group.switches_sensors_actueel') |map(attribute='entity_id') |reject('is_device_attr', 'manufacturer', 'Fibargroup') |list}}

#

nice

verbal mica
inner mesa
#

I don't see how that would work

#

You need to remove the quotes around trigger.entity_id

verbal mica
#

but now it does

mighty ledge
#

you can't test actions without a trigger

inner mesa
#

None of the things you're replacing are in that string

mighty ledge
#

so those "test actions" buttons won't work

inner mesa
#

That too

verbal mica
mighty ledge
#

you also have to make sure your trigger produces an entity_id key when it triggers

verbal mica
#

but if I specify enitity in developer templates it works too only with quotes

mighty ledge
#

for example, time triggers do not have entity_id

mighty ledge
inner mesa
#

It can't 'work'. You're not actually replacing anything

#

I would believe 'doesn't result in an error'

floral steeple
#

hi all, I have a numeric state trigger based on a device (Dyson fan with air quality monitoring) that does a self-check or reboot every mid-night. When the device comes back online, for the first 1 minute or 2, the values are 'null' or 'fail' something like that, basically its not a numeric value. So, I get error logs everyday telling me this. How can I create a not_from to exclude ALL non-numeric values, or do I have to specifically add 'null', and/or 'fail' to this

  - condition: template
    value_template: "{{ trigger.from_state.state not in [none, 'unknown', 'unavailable']}}"
marble jackal
#

trigger.from_state.state | is_number

floral steeple
#

oh that makes sense! so this would also exclude none, 'unknown', 'unaviable'?

#

or, I would have to create a second condition

marble jackal
#

Yes, because those are not numbers

orchid oxide
# marble jackal this one you mean?

i click on this link and it takes me to the ha blog page, not the github paage. unsure what the discrepancy is there. (release_url is the github link same as yours)

marble jackal
orchid oxide
#

nono, the latest os update took me to a blog page

#

i updated since so i dont have it anymore, but im quite sure the link took me strqaight to the blog on version 10

marble jackal
#

Hmm, strange, for me both the URL in the text and the URL in the attributes are the same and send me to GitHub

orchid oxide
#

odd indeed

gloomy horizon
#

Anybody willing to help me out with handling an error in a template? For whatever reason, Environment Canada's weather station near me is down, and so all weather entities are throwing "unavailable" which doesn't work well in a template that I'm using. I wonder if there's a way to revise my template so that while the thing is down, my template can render an integer to actually work with my automations rather than just have them error out.

Template below:
{% if ((states('sensor.weather_high_temperature')|int) -
(states('input_number.yesterday_high_temperature')|int)) > 10 %}
{{ (10 * 17.35) + 326.5 }}
{% elif ((states('sensor.weather_high_temperature')|int) -
(states('input_number.yesterday_high_temperature')|int)) < -10 %}
{{ (-10 * 17.35) + 326.5 }}
{% else %}
{{ (((states('sensor.weather_high_temperature')|int) - (states('input_number.yesterday_high_temperature')|int)) * 17.35) + 326.5 }}
{% endif %}

obtuse zephyr
#

For your |ints you can add a default like |int(0) to use 0 as a default if the state isn't an int

#

or you can add a top level if something like {% if not 'sensor.weather_high_temperature' | has_value %} and do something completely different

gloomy horizon
#

Love that template - might be the first "advanced" use of HA I ever did. It sets the color_temp of a Hue bulb at the front door of our house every morning and evening. By comparing yesterday's stored high temperature with today's forecasted high temperature, it makes the bulb change colour to give the differential temperature from yesterday. So the first light I see in the morning tells me whether today's going to be warmer or colder than yesterday and by how much (+/- 10°C). Let's be honest: -10 right now feels a heckuva lot warmer than it will in say July, so I rarely care about the actual temperature forecast.
...that is, as long as HA can get a forecast for the weather.

marble jackal
#

@mighty ledge
I have something strange here. I created a macro to find the cheapest consecutive block of hours for dynamic engery prices, this works fine. The output is an isoformat() string of a datetime object.
However, if I want to convert that to a datetime again, it doesn't work

  {% set d = cheapest_energy_hours('sensor.nordpool_kwh_nl_eur_3_10_021', 3) %}
  {{ d }} output: 2023-04-21T12:00:00+02:00
  {{ as_datetime('2023-04-21T12:00:00+02:00') }} output: 2023-04-21T12:00:00+02:00
  {{ as_datetime(d) }} output: null
#

do you have any idea why?

marble jackal
#

as_timestamp also doesn't work on it

marble jackal
#

It does work if you create a template sensor using the macro, and use as_datetime on the state of that sensor. So there is something strang going on with that output. However d is string returns true

mighty ledge
#

leading spaces would be my guess

#

anyways, when making macros, use - at the beginning and end of every line if it's returning a datetime

marble jackal
#

jep that was it

mighty ledge
#

yep, leading whitespace

#

so make sure all your lines that don't output code start with {%-

#

at a minimum

#

if you put the

xxx
#

before it, you can see the leading and trailing whitespace

#

TLDR: as_timestamp and as_datetime have a regex search func that uses ^ meaning leading whitespace fucks it up

marble jackal
#

Thanks a lot, I added a - everywhere now 🙂

mighty ledge
#

Yep, that's what I did when I ran into this last week

marble jackal
#

{%- -%} {{- -}}

mighty ledge
#

yah, I only do it on time macros though

marble jackal
#

makes mental note

mighty ledge
#

well, I do it on most

#

lol, yup

#

it was a PITA to find

#

because the template editor removes the whitespace

#

that's why I've always done testing with

#
xxx
{{ ... }}
#

cause that will show you your whitespace without the editor 'cleaning it'

marble jackal
#

I have to stop making changes to the repo, like this it will never get approved 😛

mighty ledge
#

what repo you working on now? Energy one?

marble jackal
#

no, the one with this macro I meant, but Ludeeus sorts on last changed and uses that to approve. So everytime I make a change, I will be back at the end of the list

mighty ledge
#

Lol

#

it is what it is!

compact robin
#

(was unaware discord post links now did that hyperlink thing, pretty cool)

obtuse zephyr
#

You can and conditions together

ex. {% if states('binary_sensor.occupancy_hall') == 'on' and states('binary_sensor.presence') == 'on' %}

compact robin
#

Figured it out yeah:

blue-grey
{% elif states('input_boolean.room_hall') == 'on' and states('input_boolean.room_office') == 'off' %}
red
{% else %}
disabled
{% endif %}```
#

Thank you!

#

Is there any way to "simplify" the two "ON" line?

#

As in something like {% if states('input_boolean.room_hall','input_boolean.room_office') == 'on' %}

marble jackal
#

is_state('input_boolean.room_hall', 'on')

#

oh, wait, for the two combined

#

[ 'input_boolean.room_hall','input_boolean.room_office' ] | select('is_state', 'off') | list | count == 0

#

but I don't think that is more simple, maybe if you have 20 input booleans it is 🙂

floral shuttle
#

what am I missing here:```
- unique_id: saldo_totaal_dag_energie_afname_of_levering
name: >
{% set saldo = this.attributes.saldo %}
{% set phrase = 'levering' if saldo < 0 else 'afname' %}
Saldo: {{phrase}} vandaag
state: >
{% set saldo = this.attributes.saldo %}
{{saldo if saldo > 0 else saldo|abs }}
attributes:
saldo: >
{% set saldo = expand('sensor.grid_energy_teller_1','sensor.grid_energy_teller_2')
|selectattr('state','is_number')
|map(attribute='state')
|map('float')|sum %}
{{saldo}}

#

I get an Error rendering name template for sensor.saldo_totaal_dag_energie_afname_of_levering: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'saldo' but I do have that attribute??

#

before you ask what I am doing.... I need the net saldo to be a positive number, to be able to show it in a sankey chart.... thats why I use a template also on the name. normally returning to grid would be negative (the attribute saldo is)

compact robin
obtuse zephyr
floral shuttle
#

yes, Ive considered that, but its a trigger template and should update each minute. wouldnt it re-render at that moment? Besides that, checking startup while all individual template are displayed on dev templates show them all available, except this composite template sensor... ive added this.attributes.saldo|float(0) now just to be sure it is not a Type issue.

obtuse zephyr
#

Ah, didn't have the trigger section 🙂

floral shuttle
#

no change. and consider this: during startup: unknown

#

after startup: unavailable

#

same result using this.attributes.get('saldo') btrw

marble jackal
#

that will probably give a different error about comparing a nonetype object againts an integer

#

try this.attributes.get('saldo', 0)

floral shuttle
#

this does work: name: > {% set saldo = this.attributes.get('saldo')|float(0) %} {% set phrase = 'levering' if saldo < 0 else 'afname' %} Saldo: {{phrase}} vandaag state: > {% set saldo = this.attributes.get('saldo')|float(0) %} {{saldo if saldo > 0 else saldo|abs}}

#

a right, crossposted, sorry

#

this.attributes.get('saldo', 0) returns the same, so probably the better syntax when using the get function. thx

#

and now for the most difficult question.... what state_class would this be. it's an energy sensor, and have settled for state_class: total now? because of The state represents a total amount that can both increase and decrease, e.g. a net energy meter....

#

not sure if the |abs throws that logic overboard (normally it would be negative)

stray tulip
#

Hi how can I implement this python script with HA? I have tried Http request but no luck! The python script is from idigo domotics and works. import requests
payload = {"activity_uuid":"AFDF357D-23C0-45FC-8109-1E89C1B8B4B9"}
requests.post("http://192.168.1.97:47147/api/v1/runactivity", json=payload)

stray tulip
#

Hi thank you for your reply I have tried that I can’t get it to work!

obtuse zephyr
#

You'll need to provide what you've tried along w/ the errors you're seeing to get help making it work

inner mesa
#

And hopefully you understand what the original code was doing

stray tulip
#

Im new to HA sorry for the trouble! I have added the rest command to my Yaml folder with the http url!

stray tulip
#

I have tried this

#

Never mind I’ve got it working thanks for your help

thorny snow
#

I have a date_time helper, in which I want to write the date of today or tomorrow after pressing a button. I succeeded in writing today with the following Action:
service: input_datetime.set_datetime data: date: "{{ now().strftime('%Y-%m-%d') }}" target: entity_id: - input_datetime.xxxx

My question is: how can I write the date for tomorrow?

obtuse zephyr
#

date: "{{ (today_at('00:00') + timedelta(days=1)).strftime('%Y-%m-%d') }}" should work

thorny snow
#

awesome, much appreciated

stray tulip
#

Is it possible to have more than one rest_command in your yaml file?

inner mesa
#

Sure

#

There's an example at the link I posted earlier

stray tulip
#

That is correct!

marble quiver
#

is there a way to set an input_number in a template?
something like: {% set input_number.rain_house_last.set_value(10) %}

inner mesa
#

please don't crosspost

#

I'll say again - templates can't do anything, you need to use a service call

marble quiver
#

can you please say again, where I can find an example of that?

inner mesa
#

in the docs for input_number

plain magnetBOT
inner mesa
marble quiver
#

yea I was looking at them.. What I want to do is watch the state of a sensor (VL53L0X) for a distance value, but the sensor at times sends a -1 for unknown, and I want to grab the last known good value > -1 and store that, and if then in a template if the state of the sensor is a -1 then use the input value. if the value > -1 then use the currently sending value. am I going about this correctly?

inner mesa
#

no

#

that is not the best way to accomplish that

#

a simple template sensor like this would do it:

template:
- sensor:
  - name: positive_test
    state: "{{ this.state if states('input_number.test')|float < 0 else states('input_number.test') }}"
marble quiver
#

sweet thank you I will play with that

cursive totem
#

Any one got any tips on how to calculate the energy consumption of my home between 4pm and 2am 7 days ago? I do have a sensor that records live consumption so I assume I either need to read it’s history or create some kind of helper?

rose scroll
restive flume
#

I currently have the following template switch for controlling a light

#
switch:
  - platform: command_line
    switches:
      office_monitor_ambilight:
        command_on: "curl -s -o /dev/null 'http://192.168.1.189/cmd?ledstripenabled=on'"
        command_off: "curl -s -o /dev/null 'http://192.168.1.189/cmd?ledstripenabled=off'"
        command_state: "curl -s 'http://192.168.1.189/ssi/toolpage.ssi' |jq -r '.ledstripenabled'"
        value_template: '{{ value == "1" }}'
#

I want to do something almost identical but that taggles between a value of 1 and 2. IS there a better way to do that than this or is this exactly the way I should do it? what happens when the value is 2?

inner mesa
#

It will be off

restive flume
#

in my case it would be more correct to interpret 2 as on and 1 as off.

inner mesa
#

Then test for that

restive flume
#

but really it's a toggle between static colour and following what's on screen

#

more of a mode switch

#

has more modes but these are the only 2 i use

#

is there an equivalent multimode switch template?

#

or not really switch.. selector

#

if I trest for 2 won't it always be on and thus never toggle?

inner mesa
#

No?

#

Not if it's 1

restive flume
#

do I have to do if 2 then 1 and if 1 then 0 or something?

inner mesa
#

No

#

What you have is true or false

restive flume
#

well I need 1 to be false

inner mesa
#

It's not 2

#

Look, test for what you want to be true and anything else will be false

#

That is boolean logic

restive flume
#

so is value_template the value that will always be considered to be on/true?

inner mesa
#

If the expression evaluates to true, it's on

#

Else, false == off

restive flume
#

I don't understand that. I will just have to see what happens

inner mesa
#

Ok

#

I don't know what's confusing

restive flume
#

hmm.. does reloading templates not reload template switches?

#

how will 1 ever be false?

inner mesa
#

What?

#

It's the test

#

{{ value == '1' }} is a boolean expression

restive flume
#

looks like I have to restart home assistant to relaod a switch template

inner mesa
#

That is not true

restive flume
#

well I reloaded/restarted templates and it didn't come up

#

maybe it's a command line entity instead

#

it is

#

doh

inner mesa
#

Indeed

restive flume
#

toggling doesn't appear to work

#

and manually setting the state also does not appear to work.. or at least it does not affect the device

#

I'll try directly from the command line

#

works from the command line

#

same issue whether I set the value template to 1 or 2. No idea why it doesn't work with either.

#

doesn't seem to be triggering the switch. that seems to be the crux of the problem

#

and triggering the switch by setting it's state also has no effect

#

works from the command line.. doesn't work in home assistant

#
  - platform: command_line
    switches:
      office_monitor_ambilight_mode:
        command_on: "curl -s -o /dev/null 'http://192.168.1.189/cmd?ledprofilevideo=2'"
        command_off: "curl -s -o /dev/null 'http://192.168.1.189/cmd?ledprofilevideo=1'"
        command_state: "curl -s 'http://192.168.1.189/ssi/toolpage.ssi' |jq -r 'ledprofilevideo'"
        value_template: '{{ value == "1" }}'
#

so I guess it's an unsolvable mystery.. nothing to debug. just doesn't work. no errors.

obtuse zephyr
#

Sure you aren't missing a . in your JSON path? jq -r '.ledprofilevideo'"

restive flume
#

thanks.. looks like it.. I literallyt would have never noticed that. but it doesn't seem to have fixed the behaviour

#

got it to work using the dashboard.. but trying to trigger it via switch doesn't work for some reason. even though I've done it the same as all the other switches. that's a seperate problem and not to do with templates though

obtuse zephyr
#

Well also... are your commands switched or is your template wrong? It'd make me believe from your commands that on is 2 and off is 1, but your template is testing for 1

inner mesa
#

We went through that. I agree that it's still wrong

azure rain
#

{% set text = namespace(list=[]) %}
{% set show_pressure=true %}
{% set color_pressure = "#asdf" %}
{% set test="Hallo" %}
{%- if (show_pressure) -%}
{% set text.list = text.list + ["{ "t": "{{test}}", "c": "{{color_pressure}}" }"] %}
{%- endif -%}

{{text.list |list}}
What is wrong with this syntax?
How can i sho the value of the variables, and not the variables if self?

marble jackal
#

Remove the {{ and }} around test and color_pressure in this line {% set text.list = text.list + ["{ "t": "{{test}}", "c": "{{color_pressure}}" }"] %}

#

And remove the quotes before and after the dict

azure rain
#

thanks that works

naive quiver
#

Hi! I have a little problem currently and I'm pretty sure somebody has an idea here how I can solve this 😄
I have a input_number helper with min 5 and max 100. Now I want to increase that value by automation by 10 for example which works fine with that:

data:
  value: "{{ states('input_number.wrpower') | int + 10 }}"
target:
  entity_id: input_number.wrpower```

UNTIL the new value would go above 100. So if it was at 95 it won't increase to 100. It stays at 95. Any idea how I could solve this?
obtuse zephyr
#
service: input_number.set_value
data:
  value: >-
    {% set wrpower = states('input_number.wrpower') | int %}
    {{ wrpower + 10 if wrpower <= 90 else wrpower }}
target:
  entity_id: input_number.wrpower

should work

naive quiver
#

Replaced the "else wrpower" with "else 100" and it does then. Thank you very very much! 🙂

obtuse zephyr
#

You said: So if it was at 95 it won't increase to 100

naive quiver
#

Ah no. I wasn't clear enough. I wanted it to go to 100 then. 🙂

#

It tried to go to 105 what of course wasn't working because the maximum value was set to 100. So it was stuck at 95 then. That was my problem 🙂

obtuse zephyr
#

Then it could just be value: "{{ min(states('input_number.wrpower') | int, 100) }}", either will work

naive quiver
#

"{{ min(states('input_number.wrpower') | int + 10, 100) }}". Now it does. Looks even cleaner. ty again 🙂

obtuse zephyr
#

Ah, yeah, right. Np

boreal panther
#

Hi all - I'm trying to build an automation that depends on the state of a sensor. This is the first time I've tried building an automation that uses a template, and something in my syntax isn't registering well with HA at all. The line that HA doesn't like says is_state('sensor.weatheralerts_1_alert_1_most_recent_active_alert', ['Freeze Warning', 'Severe Thunderstorm Warning'])

#

When I try to enter that, HA returns with " required key not provided @ data['condition'][0]['value_template']"

#

What I'm trying to do is test the value of that sensor so I can trigger a scene.

obtuse zephyr
#

Can you provide the whole automation? I'd imagine your condition isn't surrounded in "s

boreal panther
obtuse zephyr
#

Hmmm.... there's no actual template there

boreal panther
#

That's all I have so far. I know. It won't let me save it. 🙂

#

That line that I referenced above, when I try to build the automation as a "Template condition" is what throws the error.

obtuse zephyr
#
condition:
  - condition: template
    value_template: "{{ is_state('sensor.weatheralerts_1_alert_1_most_recent_active_alert', ['Freeze Warning', 'Severe Thunderstorm Warning']) }}"
boreal panther
#

So in the visual editor, I needed to make sure I added the {{ at the beginning and end... that's where I was screwing this up?

#

(Trying to learn...)

obtuse zephyr
#

Well, templates need to be surrounded in {{ and }} that's what makes them a template. I don't know exactly how you got to the point w/ no value_template whatsoever via the UI though

#

When you add a template condition via the UI, you should see the condition w/ the value_template text box. Just defaults to ""

boreal panther
#

Gotcha. My very first attempt was in the UI, and that was all kinds of wrong. I wasn't even looking at the right sensor. So, after doing some digging around and (trying) to figure this out with reading, I got to the right sensor and came up with that syntax. Evidently, though, I missed the memo on doing the {{ }} for the template.

obtuse zephyr
#

Keep in mind, that automation you have w/ the above condition will only ever activate the scene when you start home assistant

boreal panther
#

I'd like it to be running at all times. Checking constantly for any value in that sensor.

obtuse zephyr
#

Right, so you should move that to be a trigger instead

#

Also, while perfectly fine, you don't even need a template to do that, you can use a state condition/trigger

boreal panther
#

👀

#

OK, so I've made that change (at least I think I've got it down now....)

#

Now I'll need to wait until that sensor changes. It's already set to "Freeze Warning" currently, so it's not going to trigger with a "change" trigger. 🙂

#

I appreciate all of your help.

orchid oxide
buoyant dirge
#
Source: components/template/fan.py:393
Integration: Template (documentation, issues)
First occurred: 8:49:08 PM (1 occurrences)
Last logged: 8:49:08 PM

Received invalid percentage: None for entity fan.livingroom_fan```
#

littleraly I just copy and paste the last example, and only change the name from "preset_mode_fan" to "livingroom_fan"

obtuse sky
#

i am using config template card, and i want to get the device name using device_attr, but error is throw that device_attr is not available, how i get the device name in JS

rose scroll
buoyant dirge
#

Nop.

#

My setup is with 433mhz fans , I have to send a code with the rf bdrige with esphome. So, basically I have a button for each spd, that’s why I want to make a template (never did before) and will love to use the tile card for fan.

#

I still trying ro understand them but is confusing!

rose scroll
#

That last example fan is for converting a fan that does % speeds (fan.percentage_fan) into one that does preset modes.

#

Does your fan natively do modes or speed numbers?

#

If the latter, have a look at the first example instead (helper fan).

buoyant dirge
#

Ok, I’ll try 1st

fallow gulch
#

any idea why this wouldn't be working?

#

The icon isn't changing when the state changes to 'running'

template.yaml
 - binary_sensor:
    - name: "Dishwasher"
      icon: >
        {% if is_state("binary_sensor.dishwasher", "running") %}
          mdi:dishwasher
        {% else %}
          mdi:dishwasher-off
        {% endif %}
      state: "{{ states('sensor.smart_plug_3_current_consumption')|float(0) > 2 }}"
      device_class: running
      delay_off:
        minutes: 10
orchid oxide
#

it seems awfully redundant here to have to do as_datetime here before as_local. is there a better way? {{{{('2023-04-23 23:34:52.973651-02:00')|as_datetime|as_local}}

orchid oxide
#

its a binary sensor, running is just the human friendly "translation" of the value

compact robin
#

Good morning,

      {% if states('light.candeeiro_cozinha') == 'on' %}
      #F5C02F
      {% elif states('light.lightstrip_kitchen_light') == 'on' %}
      'rgba({{ (state_attr('light.lightstrip_kitchen_light', 'rgb_color') |
      join(',')) }},0.1)'
      {% endif %} ````
#

that formula works for backgrounds, but I can't seem to make it work on icon_color. What am I doing wrong?

#

It's a custom:mushroom-template-card

#

This on the background, works perfectly: {% elif is_state('light.candeeiro_cozinha', 'on') %} background: rgba(245, 192, 47, 0.1); {% endif %} }

visual dune
#

Good morning. I'm working on a script to apply standardized logic to all my notifications. I'm trying to figure out if it's possible to template the extended data options for a notification. Something like this:

#

- service: notify.mobile_app_starfury data_template: title: "{{ input_title }}" message: "{{ input_message }}" data: > {% if input_priority == 'H' %} importance: high {% elif input_priority == 'C' %} ttl: 0 priority: high channel: alarm_stream {% else %} channel: "{{ input_channel }}" {% endif %} tag: "{{ input_tag }}"

marble jackal
#

What you are doing now for the additional data section won't work

#

You need to provide it like this:

data: >
               {% if input_priority == 'H' %}
                 {{ { 'importance': 'high' } }}
visual dune
#

Okay, think I get it. Was not finding that clearly in the docs. Thanks

hybrid merlin
#

Is there a way to pull info from Calendar Events (other than the next event) into templates? I'm trying to replace Garbage Collection with a "Home Maintenance" calendar including two different types of pickup events. I want to be able to template out how many days there are until each of those two events. I think I could do it by creating a separate calendar for each type of event, but I don't really want to do that.

junior moth
#

im trying to create a sensor template that monitors the degree of angle of a sensor and then returns results based on that:
{% if states("vibration_sensor.garage_door_angle_z")|int(0) <= 0 %}
Closed
{% else %}
Open
{% endif %}
seems pretty simple yea? the state = -82, so it SHOULD show as closed. well it does if i use <=
BUT then it won't show open when i change to state to say 12

#

it makes no sense at all.

#

its driving me crazy

obtuse zephyr
#

Probably should be {% if states('sensor.vibration_sensor.garage_door_angle_z')|int(0) <= 0 %}

#

you forgot the domain sensor.

junior moth
#

ok, will give that a shot. thanks for the response!

junior moth
obtuse zephyr
#

Oof, so has Home Assistant, quite a bit. Even things a year old can be risky

#

Docs are the best place to start

junior moth
#

lesson learned. appreciate it!

#

seemingly unrelated to templates, but this new custom sensor doesn't trigger the icon color to change based on its state like the non-custom sensors. is that expected behavior?

marble jackal
torn ivy
#

frontend

obtuse zephyr
marble jackal
#

No, it was indeed already wrong

junior moth
inner mesa
#

One that doesn't involve multiple '.' 🙂

junior moth
#

Lol. Thanks and will do.

narrow quiver
#

I'm looking to make a pretty complicated template for a fireplace. My skills are very limited and the closest thing I've done to this is create a simple garage door cover template. Anyone care to help me out with this? Will send all the details.

obtuse zephyr
#

Best to share them here and if someone's able to help, they will

narrow quiver
#

I am attempting to make a dumb fireplace smart. I currently have the fireplace plugged into a smart plug(for energy monitoring) and put a IR blaster inside it to make it smart. I’m wanting to make a device in HA for this that has an on/off switch(a cover that reads the energy monitoring to know if its on and off because the remote command is a toggle), a timer entity(when pressed, turns the fireplace on, and then turns heat on for a set amount of time), A flame color button(sends ir command copied from remote), flame speed button(sends ir command copied from remote), dimmer button(sends ir command copied from remote), speed button(sends ir command copied from remote), high heat button(sends ir command copied from remote), and low heat button(sends ir command copied from remote). I want it to report power, and report low or high heat(by reading energy monitoring).

I have all of the remote codes copied, but have no clue where to start with the templates.

obtuse zephyr
narrow quiver
#

What I meant by that is, the only similar template I have is a garage door cover. Opens only if another sensor reads that is is closed, and vise versa. The garage door and the fireplace are both momentary.

#

But if I can do the same thing for this with a switch template, I’ll go that route. How would I get these separate entities into a device?

obtuse zephyr
#

With the switch itself, that'll just allow you on and off control with the ability to detect state via your plug energy monitoring

#

I'm assuming the buttons you referred to above are more so #frontend-archived buttons you'll be creating?

narrow quiver
#

I’d prefer the switch and all the buttons to be entity’s of the same device if possible. I have plans for front end remote, but want to finish everything before I start thinking about that.

obtuse zephyr
#

To my knowledge, you can't go and create completely custom devices... they must be provided by an integration. So if you're wanting to do that, you'd either need to take on creating an integration or working within the confines of an existing one. I think an intermediate option would be to create your own via MQTT, but that'd be outside of the templates realm.

narrow quiver
#

Hmmm, I’ll dive into that a little and see if it’s something I can figure out. Probably will just stick with templates though.

obtuse zephyr
#

You definitely can make it "look" like a single thing on your dashboard though, even if it isn't a single device

narrow quiver
#

My plans for that is to create a remote. I have it created in photoshop, just need to learn how to get that image into HA as a card and make the buttons control the entities. Thats for another day lol.

orchid oxide
#

TemplateSyntaxError: Encountered unknown tag 'marco'.
this kind of spelling error is going to be the death of me

compact rune
#

As a user of the name 'mian' I figure I'm in good company alongside 'marco' and 'defalut' and similar 😆

orchid oxide
#

lmaoo

#

is there any difference between
- conditions: {{template}}
and

  value_template: {{template}}```
other than the fact that one is ui friendly?
marble jackal
#

you need to add quotes in both, but there is no difference in how they are handled

#
choose:
  - conditions: "{{ template }}"
    sequence: []
  - conditions:
      - condition: template
        value_template: "{{ template }}"
    sequence: []
  - conditions:
      - "{{ template }}"
    sequence: []
#

@orchid oxide these are all valid, but if you need multiple conditions the first one will make that hard 🙂

#

and talking about typos, I generally miss the first i in condition

orchid oxide
#

lol

#

but that makes sense ty

compact robin
#

Hello friends, I'm struggling with this template:

    icon_color: >
      {{ iif(is_state('light.lightstrip_kitchen_light','on'), "'#%02x%02x%02x' %
      state_attr('light.lightstrip_kitchen_light','rgb_color')", 'grey') }}

Images for context: https://imgur.com/a/TnOnC5c - Also screenshots of the states. That sometimes are BRIGHTNESS and not RBG_COLOR.
I have success making the background follow the RGB with this:

         background: rgba({{ (state_attr('light.lightstrip_kitchen_light', 'rgb_color') | join(',')) }},0.1)
      {% elif is_state('light.candeeiro_cozinha', 'on') %}
         background: rgba(245, 192, 47, 0.1);
      {% endif %}```
#

It shows the "grey" properly, but the moment the lightstrip is on, it'll break (and show that black color thing). Both on Brightness and RBG.

#

What am I screwing up?

marble jackal
#

you are using double quotes around the true statement of the iif

#

so that will alwasys be the string '#%02x%02x%02x' % state_attr('light.lightstrip_kitchen_light','rgb_color')

#

which will not be a valid input for icon_color

compact robin
#

I don't think I understand what you mean 😓

#

Okay, I figured this works:

      {{ '#%02x%02x%02x' % state_attr('light.lightstrip_kitchen_light',
      'rgb_color') if states('light.lightstrip_kitchen_light') == 'on' else
      'disabled' }}```
#

But if the color isn't really RGB, and is doing a "brightness" only color, it still shows the "broken black".
Can you help me fixing that?

#

I don't know which state I should look for tho, would brightness work?

#

Or even, show a SOLID COLOR, if the lightstrip isn't on rgb_mode, is that possible?

paper hazel
#

I'm a bit stuck. The templates renders correctly when testing it in dev tools giving me a *true * result, but when executing a script and using it as a condition with *choose *it results to *false *and skips the sequence. Any help will be appreciated.```
- choose:
- conditions:
- condition: template
value_template: "{{ (((now() | as_timestamp ) - (state_attr('automation.test_automation_1', 'last_triggered') | as_timestamp)) | int) > 240 }}"

#

I have also tried, the following, but with the same result.```
{{ (as_timestamp(strptime(states.sensor.date_time.state, '%Y-%m-%d, %H:%M')) - as_timestamp(state_attr('automation.test_automation_1', 'last_triggered'))) > 240 }}

marble jackal
marble jackal
compact robin
#

That creates the hexadecimal code for the RGB color. I actually don't know hahaha but on the forums people used that and it ended up working with some tweaks.

paper hazel
#

I think I see what you are getting at...

marble jackal
#

test it in developer tools > template. you will be doings something lik '#%02x%02x%02x' % [ 0, 0, 255] which will give an error

compact robin
#

The issue now, is it possible to add something that would also use the brightness when there's no RGB color? It's a yeelight lightstrip and sometimes the color doesn't have RGB-Color in the states.

marble jackal
compact robin
paper hazel
marble jackal
marble jackal
#

but if you use it in a choose, you are in the action part, so it has been triggered

paper hazel
#

Ah, that will make sense, I have only used it there in the past, first time using it in under actions. Appreciate the explanation.

floral steeple
#

hi all, I'm trying to make a binary sensor from a cover. The cover sensor has 2 true states, 'open' and 'opening' but when I try to capture 'opening' it does not like it. How can I capture both states as true?

#

{{ is_state('cover.overhead_garage_door_controller', 'open', 'opening') }}

#

there is also closed and closing which would be false

obtuse zephyr
#

{{ is_state('cover.overhead_garage_door_controller', ['open', 'opening']) }}

floral steeple
#

thank you sir!

marble jackal
#

are you sure you don't want it to be true while it's closing? Technically it is still open then 🙂

floral steeple
#

oh, yeah that is a good point. I should add closing to the state

#

thanks!

hearty verge
#

Does Jinja/HA support a Mod % function?

#

ChatGPT has answered my inquiry

mighty ledge
#

why didn't you just try instead of asking?

#

you already knew the symbol

#

you didn't even need to ask chatgpt as it probably has no clue either

inner mesa
#

Of course Jinja has a frobnication operator

pallid pewter
#

Hello! Guys is possible to apply operator to state_filter ? I am only able to set matching value to sensor, i want to ad operator such “>=“ or “<“

#
    entity: sensor.0x00158d0002c4ccb9_device_temperature
    state_filter:
      ">28": brightness(50%)```
marble jackal
floral steeple
#

Is this like a way to save cpu? Use the inverse?

#

Since it's only checking one state as opposed to 3?

mortal rose
#

How do I put "last-changed" on the secondary information of a Mushroom Template Card?

marble jackal
#

did you provide an entity: in the config of the card? And how do you expect it to be displayed?

#

if the answer of the first question is yes, you can use {{ states[entity].last_changed }} to get it as a datetime string

mortal rose
#

Yes I did . Getting closer. It provided me a format of "2023-04-24 14:55:40.059324+00:". I was expecting two hours ago. Any ideas?

marble jackal
#

and {{ relative_time(states[entity].last_changed) }} to get that

mortal rose
#

Thanks, TheFes!!! You rock. Been goofing with that for an hour!

rancid trout
#

is there a way to get the current temperature from a climate entity using a sensor?

marble jackal
#

most probably yes

rancid trout
#

how do i do that

#

ive been looking at community posts and the template docs for about 20 mins and my brain cant comprehend that

marble jackal
#

I'm not sure what you mean with using a sensor though

rancid trout
#

i want a graph to show the current temperature returned by my aqara thermostat

marble jackal
#

you want to create a template sensor with the current temperature of the climate enitty as it's state?

rancid trout
#

and i cant just use the climate entity for the input of the graph

marble jackal
#

okay, I assume it is in an attribute (I don't have climate entities in my setup). Can you check in developer tools > states what that attribute is?

rancid trout
#

its current_temperature

marble jackal
#

and what is the entity id of your climate entity?

rancid trout
#

climate.hkt_zone_1

marble jackal
#
template:
  - sensor:
      - unique_id: current_temp_climate_hkt_zone_1
        name: Current temperature HKT Zone
        state: "{{ state_attr('climate.hkt_zone_1', 'current_temperature') }}"
        device_class: temperature
        unit_of_measurement: "°C" # or "°F"
        state_class: measurement
#

put that in your configuration.yaml

#

unless you are already using the template: integration

rancid trout
#

thank you very much, ill try it

marble jackal
#

if this is your first template entity, you need to restart HA, otherwise you can reload template entities in developer tools > YAML

mortal rose
#

Okay thanks again!'

marble jackal
#

there was a typo in the entity_id of the state template

rancid trout
#

is the unique id linked to anything in any way or can you freely change it?

marble jackal
#

you can freely change it, I usually use randomly genereated UUID's

rancid trout
#

cool cool

marble jackal
#

it's not used for the name or entity_id

#

the name is converted to the entity_id

#

but by adding a unique_id you can change the name and entity_id in the GUI, among other settings

rancid trout
#

ah

rancid trout
#

forgot to thank you 👍 works flawlessly

fallow sand
#

What's the correct syntax that allows me to use the state of input_number.hvac_ds_cool_away like so?:

    {"hvac_mode": "heat_cool", "target_temp_high": states('input_number.hvac_ds_cool_away'), "target_temp_low": 68 }
plain magnetBOT
#

@grand robin I converted your message into a file since it's above 15 lines :+1:

fallow sand
#

ChatGPT beat y'all to the punch this time 😉

haughty cradle
#

Im having issues making a separate temp sensor to convert C to F. I think I have to make a template but I am not sure. I put the following in a the config.yaml but im still not seeing the new sensor. is there something else I need to do??

Loads default set of integrations. Do not remove.

default_config:

Load frontend themes from the themes folder

frontend:
themes: !include_dir_merge_named themes

Text to speech

tts:

  • platform: google_translate

automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

sensor:

  • platform: template
    sensors:
    sonof_temp_f:
    unique_id: "Sonsof temp f"
    friendly_name: "sonsof temp f"
    unit_of_measurement: '°F'
    value_template: >-
    {% set t = states('sensor.1000574c0e_t') | float %}
    {{((t)*9/5)+32}}
#

FYI the templete works in the template checker

obtuse zephyr
#

Put it on a new line

#
value_template: >-
  {% set t = states('sensor.1000574c0e_t') | float %}{{((t)*9/5)+32}}
haughty cradle
#

would the matter if the syntax works in the template cheacker

obtuse zephyr
#

Yes

#

If you format the YAML incorrectly, it's not going to work

haughty cradle
#

it is on another line, I guess it didnt paste correcty

obtuse zephyr
#

I think it's cut off

#

Paste it on a code sharing site

haughty cradle
#

sensor:

  • platform: template
    sensors:
    sonof_temp_f:
    unique_id: "Sonsof temp f"
    friendly_name: "sonsof temp f"
    unit_of_measurement: '°F'
    value_template: >-
    {% set t = states('sensor.1000385c0e_t') | float %}
    {{((t)*9/5)+32}}
#

thats from studio code

obtuse zephyr
#

There's no line break there...

inner mesa
#

Please format your code

haughty cradle
#

lol nm it didnt copy corrtly, wish i could just use a screen shot

inner mesa
#

No, just share it properly

haughty cradle
#

how do I do that?

#

i just used copy and paste?

inner mesa
#

That gets you what you provided above

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

haughty cradle
#

i guess i dont know what message share is

inner mesa
#

it was my broken attempt to do that on my phone

haughty cradle
#

sensor:

  • platform: template
    sensors:
    sonof_temp_f:
    unique_id: "Sonsof temp f"
    friendly_name: "sonsof temp f"
    unit_of_measurement: '°F'
    value_template: >-
    {% set t = states('sensor.1000385c0e_t') | float %}
    {{((t)*9/5)+32}}
#

ahh

inner mesa
#

gack

haughty cradle
#

i used the dpaste site

inner mesa
#

not evident from the paste above

#

dude

haughty cradle
#

i guess im not getting how to copy it over from dpate

inner mesa
#

make a new snippet on dpaste, share the link

haughty cradle
fallow sand
#

sometimes I miss Gitter lol

haughty cradle
obtuse zephyr
#

Did you reload after updating ?

haughty cradle
#

lol not sure, I did a core reload and also restarted HA

obtuse zephyr
#

HA restart would cover it for sure... there's no sensor.sonof_temp_f is what you're saying? Or there's an error in your log?

haughty cradle
#

yes no sensor

#

and in the template tester output I get sensor:

  • platform: template
    sensors:
    sonof_temp_f:
    unique_id: "Sonsof temp f"
    friendly_name: "sonsof temp f"
    unit_of_measurement: '°F'
    value_template: >-

       87.08000000000001
    
#

so it should be correct as its getting a temp value and seems to be correctly converting it

obtuse zephyr
#

I'd check your log to be certain... but that config looks fine

#

You're certain you restarted after saving your config?

haughty cradle
coarse tiger
#

I'm in need of a automation condition where I check a precipitation sensor if there was a certain amount of rainfall, anybody know a easy way to achieve this?

marble jackal
#

you mean in the past?

coarse tiger
#

yes

marble jackal
#

how far in the past?

coarse tiger
marble jackal
#

you can use an sql sensor to get the last 24hr of data out of the database

#

but I'm not an SQL query expert, so I can't help you with that

coarse tiger
#

so alternative is a boolean which gets reset every 24h then ?

#

too bad, I thought there is something new where one can check "min/max/avg" over x time

marble jackal
#

oh wait

#

there is history stats

coarse tiger
#

looks like what I need, awesome

#

thanks

thorny snow
#

Hello - how can i add 0.025 to my resultant state in this code? (I.e. after the * 1.21. I tried to just add (+ 0.254) but it didn't work..... many thanks,

- sensor: - name: epex_spot_price_ct_per_kWh_with_vat unit_of_measurement: "€/kWh" availability: '{{ states("sensor.epex_spot_nl_price") != "unavailable" }}' state: '{{ states("sensor.epex_spot_nl_price") | float / 10 * 1.21 }}' unique_id: "my_unique_id_epex_spot_price_ct_per_kWh_with_vat"

floral steeple
#

((10 * 1.21) + 0.0254)
maybe

#

or
((float / (10 * 1.21)) + 0.0254)

inner mesa
#

it's just normal order of operations

#

"float" is not a number

#

this is just basic math

floral steeple
#

corrected 🙂

inner mesa
#

state: '{{ (states("sensor.epex_spot_nl_price") | float / 10 * 1.21) + 0.025 }}'

floral steeple
#

ahh, yes, that makes more sense. The whole thing has to be brought into the bracket

thorny snow
#

thank you. works now!

orchid oxide
#

chatgpt is perfect for summarizing what old templates do so i dont have to parse my own chicken scratch to remember lmao

marble jackal
sturdy yarrow
#

Does anyone know why my result of this template gives me +1 month than what the helper is? If helper is set to 26 April the result of this template gives me 26 May.. And if I add -1 in the sensor it only works if the month in the helper is in this month.. If I set the helper to be 26 May the result of the sensor will be 26 April..

{% set months = ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"] %}
{% if now().date() < input.date() %}
{{ input.strftime('%d ') + months[now().month] }} 
{% endif %}  ```
#

The if statement is meant to show a date if the date hasn't passed yet

crimson lichen
#

Sorry,
After update lastest ver of HASS.
I can not play music on local .

With error:
homeassistant.components.cast.media_player
['Failed to cast media https://khaisilk1910.duckdns.org:8123/local/media/children/Con Heo Dat.mp3?authSig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIwMjBjYjIxYThjNGY0NmM3OTk4ZmY1ZjE1ZWNjNmE5MSIsInBhdGgiOiIvbG9jYWwvbWVkaWEvY2hpbGRyZW4vQ29uIEhlbyBEYXQubXAzIiwicGFyYW1zIjpbXSwiaWF0IjoxNjgyNDk3MDk0LCJleHAiOjE2ODI1ODM0OTR9.btepsrdwMYu73KDjnNK07IoahCIvk59esZ5NiiBeDyc from external_url (https://khaisilk1910.duckdns.org:8123/). Please make sure the URL is: Reachable from the cast device and either a publicly resolvable hostname or an IP address']

Can someone help to me

#

alias: Play Music At Morning
sequence:

  • service: media_player.play_media
    data_template:
    media_content_type: audio
    media_content_id: >-
    media-source://media_source/local{{state_attr('sensor.children','file_list')|random}}
    entity_id: media_player.phong_ng_speaker
    mode: single
    icon: mdi:playlist-music
cursive ice
#

This is a template question, is there anyway to template my venetian blind so that if 0-30% state is considered closed, 30-70% state is considered open and 70% to 100% state is considered closed? the state_attr is current_tilt_position: 53

plain magnetBOT
#

@thorny snow I converted your message into a file since it's above 15 lines :+1:

thorny snow
#

Hello - is it possible to manipulate sensor data which is used in a chart (as it has attributes) to add my VAT (21%) and some additional cost (2.54 euro cents)?
So, for example - with one sensor, I am able to add VAT and additional costs like this:
- sensor: - name: epex_spot_price_ct_per_kWh_with_vat unit_of_measurement: "€/kWh" availability: '{{ states("sensor.epex_spot_nl_price") != "unavailable" }}' state: '{{ (states("sensor.epex_spot_nl_price") | float / 10 * 1.21 + 2.54)/100 }}' #add vat and extra costs, then into 0.00 cents that can be understood by threshold input unique_id: "my_unique_id_epex_spot_price_ct_per_kWh_with_vat"

However - this sensor (sensor.nl_energy_prices_average_electricity_price_today) is where my chart data is - and I'd quite like to add VAT and additional costs (like above) to each attribute for the hour in this sensor. - therefore so each bar int he chart is correct.
You can see a screenshot of the attributes here: https://ibb.co/z60cfHY
And the code for the chart, which uses the sensor is here: https://wtools.io/paste-code
The end result I would like is a chart that includes the original data but with VAT added (21%) and 2.54 euro cents.
thanks!

plain magnetBOT
#

@vernal pawn I converted your message into a file since it's above 15 lines :+1:

vernal pawn
#

Huh? ok, I did not expect that to happen.

#

Ok again:

#

Hmm, something weird which I hope you can help me with.

I want to get a timer working on the Ulanzi Pixel clock and therefore I need the time to be updated every second. I try to do this with the below template. The resulting time display however is always 1 hour above the actual remaining time.

#
{% set duration = 7200 %} 
{{ duration }}
{% set end_time = as_timestamp(now()) + duration %}
{{ end_time | timestamp_local }}
{{ now() }}
{% set remaining = end_time - as_timestamp(now()) %}
{{ remaining | timestamp_custom('%H:%M:%S')}}
#

results in:

7200
2023-04-26T16:35:00.308053+02:00
2023-04-26 14:35:00.308112+02:00
02:59:59
#

As you can see remaining is one hour up on the duration of 2 hours, while the end_time and now() are exactly 2 hours apart.
What's going on and how can I fix this?

#

No, i do not want to use the timer function of Home Assistant. That only works with a set time. I want to define the duration of the time based on a calendar item.

obtuse zephyr
#

remaining isn't a timestamp any more and that's what you're formatting at the end

#
{% set duration = timedelta(hours=2) %} 
{{ duration }}
{% set end_time = now() + duration %}
{{ end_time }}
{{ now() }}
{% set remaining = end_time - now() %}
{{ remaining }}
#

Depends on what you want to do w/ it

#

But there remaining will be a timedelta object

vernal pawn
#

I want to calculate the time of a calendar item by doing something like:

{% set duration = as_timestamp(state_attr('calendar.robin', 'end_time')) - as_timestamp(state_attr('calendar.robin', 'start_time')) %}
mighty ledge
#

timestamp_custom assumes a local time

#

when you use a timestamp integer/float with timestamp_custom, you must supply the timezone, otherwise it will be off by your timezone

#

otherwise use what NSX said, which is a timedelta object

vernal pawn
#

With that time difference (of lets say 30 minutes) i want to set a timer of 30 minutes, which is started by the press of a button. So the end time is not the end time of the calendar item.

mighty ledge
#

Er, well, It can't do time differences between things yet. So nevermind

vernal pawn
#

Hmm thanks.

#

This seems way more complicated than I thought.

#

Too bad the timer helper of Home Assistant only has the option to set a fixed default value which cannot be updated. That would be ideal.

obtuse zephyr
vernal pawn
#

Ah!

It was a bit hidden to me. Thanks!

#

I came up with another solution which might have worked. The duration was in seconds, so a timedelta could be set with seconds.

vernal pawn
#

Too bad the remaining attribute doesn't seem to update that often. It stays on the duration time, while the timer is running down.

#

A well found this solution:

{% set remaining = state_attr('timer.robin', 'finishes_at') | as_datetime | as_local - now() %}
{{ (remaining|string)[:-7] }}

This results in something like: 0:09:54 and is what I need.

Thanks for the help 🙂

marble jackal
#

But this will only update once per minute

hearty verge
#

If i want to store a JSON Message in a text helper, is there an easy way to add/remove/update specific fields using templates?

#

I'm trying to see if i can get away with less helpers and more complex templates

#

For example i can sort of reconstruct a json with:

{% for key in  (states('input_text.scene_controller') | from_json | list )  -%}
  {'{{key}}': {{(states('input_text.scene_controller') | from_json )[key]}}}
{% endfor %}
hearty verge
#
{% set j = {"Basement Remote":1, "kids_remote": -1}    %}
{% set update_value = dict({'Basement Remote':2}) %}
Inital Dictionary: {{j}}
Update packet: {{update_value}}
Merged: {{ dict(j, **update_value)}}

That kind of worked...

hearty verge
#
{%- macro remove_field(json_data, field) -%}
  {{ dict( json_data.items() | rejectattr('0','eq',field) | list ) }}
{%- endmacro -%}


{%- macro update_or_add_field(json_data, field, value) -%}  
  {{ dict(json_data.items() | rejectattr('0','eq',field) | list, **dict({field:value})) }}
{%- endmacro -%} #}
mighty ledge
#
{%- macro update(data) %}
{{ dict(data.item() | rejectattr('0', 'in', kwargs.keys() | list) | list, **kwargs) | to_json }}
{%- endmacro %}
#

use

{{ update(data, x=1, y=2) | from_json }}
#

that's if you're replacing

narrow knot
#
binary_sensor:
  - platform: template
    sensors:
      wouter_iphone_home:
        value_template: >-
          {% if states('sensor.wouters_iphone_ssid') == "WWWiFi" %}
            home
          {% else %}
            not_home
          {% endif %}
        friendly_name: "Wouter's iPhone Home"```
#

is there anything wrong with this? because despite my SSID changing, the sensor stays the same.

inner mesa
#

Yes, it's a binary_sensor and they can only be on or off

#

You're trying to assign home and not_home

narrow knot
#

hm, okay, apparently that used to work based on the article I copy/pasted it from

inner mesa
#

Nope

#

Doesn't sound like a useful article

inner mesa
#

Meh, it's just wrong

narrow knot
#
binary_sensor:
  - platform: template
    sensors:
      wouter_iphone_home:
        value_template: >-
          {% if states('sensor.wouters_iphone_ssid') == "WWWiFi" %}
            on
          {% else %}
            off
          {% endif %}
        friendly_name: "Wouter's iPhone Home"
#

so this will work?

inner mesa
#

So, that's a sensor

narrow knot
#

or is there a way to make it work with home/not_home? similar to the usual presence detection?

inner mesa
#

You have a binary_sensor

#

You didn't copy well

narrow knot
#

ah, I see.

#

I copied it from the blog, which didn't mention the type of sensor.

still quiver
#

I have 10 of the same type of sensor, I want to create template sensors that run a calculation on each sensor with different offsets variables in order to well calibrate it. Is there a way to have a reusable function i can call for each template sensor so when i modify it, it affects all the sensor instances?

tepid otter
#

Not sure if this is even possible. Currently when my mic active sensor becomes active it turns on a light then off when mic sensor is off. I have it start a timer helper which counts down from 10 minutes. Firstly would love to express the time remaining as a percentage. Unsure on where to even start?? Next if the call runs over from the 10 minutes how can I determine call time? Is there a way to start a counter at the beginning to “log” the whole time?

fickle kettle
#

Is there a quicker/better way to access values that may not exist (unavailable) than
(states('sensor.pv_power')|float|round(1) if has_value('sensor.pv_power') else 0.0)
?

marble jackal
#

Just use | float(0) to let it default to 0

fickle kettle
#

Ah I didn't spot it had an arg, thanks

plain magnetBOT
#

@thorny snow I converted your message into a file since it's above 15 lines :+1:

thorny snow
#

Is this even possible

mighty ledge
#

@thorny snow

  - trigger:
      - platform: time_pattern
        minutes: '/1'
      - platform: state
        entity_id:
          - sensor.charger_power
        attribute: charger_amps_actual
    sensor:
      - name: template_ev_consumption_home
        state: >-
          {% if trigger.platform == 'state' %}
            {{ trigger.to_state.attributes.charger_amps_actual }}
          {% else %}
            {{ states('sensor.template_totalexcesssolarforcharging') | float(0) * 24 / 100 }}
          {% endif %}
        unit_of_measurement: kW
        device_class: power
#

keep in mind, if you want the charger_amps_actual as the output, the code will change the 2nd line to

  {{ trigger.to_state.attributes.charger_amps_actual }}
thorny snow
#

I dont think the if statement is evaluating correctly

            {{trigger.to_state.attributes.charger_amps_actual }}
          {% else %}
            {{(states('sensor.template_totalexcesssolarforcharging') | float(0) * 24/100  ) }}
          {% endif %}```
If I paste this in the template tool it errors with 'UndefinedError: 'trigger' is undefined'
Do the trigger entities work for a template sensor?
fossil venture
#

There are no trigger events in the template editor. Trigger events only occur in automations, where the template will work as expected.

mighty ledge
#

You can just Copy/paste what I wrote and it'll work out of the box.

short parrot
#

guys, could I make a template that triggers an automation with a logic similar to this? When the state of a sensor is under a value trigger the automation once and when the state of a sensor is over a value trigger the automation based on a time pattern (like /5)

plain magnetBOT
#

@lofty mason I converted your message into a file since it's above 15 lines :+1:

lofty mason
short parrot
lofty mason
#

basically use triggers to trigger any time number falls below and every five minutes, and then use conditions to carve out the triggers you didn't want.

inner mesa
#

That is the way

short parrot
#

Thank you both! I've implemented this - will have to test it in time to see how it works 🙂

ember cloud
#

Hi, how can I cover the whole subnet 10.10.10.0/24 in the following template

{{ state_attr('persistent_notification.http_login','message').split('(')[1].split(')')[0] != '10.10.10.30' }}
inner mesa
#

Use [0][:-3] != '10.10.10'

ember cloud
inner mesa
#

I suggest debugging

#

Remove != '10.10.10' and see what's wrong

ember cloud
#

just forgot the '.' in the end. it needs to be

[0][:-3] != '10.10.10.'

Thanks a lot for your help.

inner mesa
#

Or change -3 to -4

#

I always end up off by one with that stuff

ember cloud
#

Thanks.

thorny snow
inner mesa
#

they are

#

as long as you're actually loading the template sensor and letting it trigger, rather than just sticking the template itself into the template dev tool

celest tinsel
#

Q: With this new found template power, is there a way to create a custom filter to use in a template? I have a simple python function I need to use in a filter

import struct
def float_2_ieee(f):
    binary_string = ''.join(f'{b:08b}' for b in struct.pack('>f', f))
    return hex(int(binary_string, 2))

inner mesa
#

Unfortunately not

#

You can't create filters at all

#

The only new capability is to make Jinja declarations global

orchid oxide
#

the fact that if you dont format templates it auto fomrats them like this {{((area_entities('Living Room')|select('match', 'lock'))|list, (area_entities('Living Room')|select('match', 'switch')|list))|reject('search', 'bun_cam_v2_notifications')|reject('search', 'bun_cam_v2_motion')|list}} drives me insane

#

cause naturally 'Living Room' and 'Living Room'

are not the same thing

marble jackal
#

Don't use the GUI for automations, scripts and dashboard creation 😜

orchid oxide
#

i like the immediate feedback 😦

marble jackal
#

Well, that's what causes the reformatting of the templates.
If you use YAML only, it will stay exactly as you wrote it

grizzled grove
#
- name: "pE"
  unique_id: pe
  state: >
   {{(((states('sensor.eth_hourly') | float(0) / 1000) / 3600) * 1000) | round(7)}}
  unit_of_measurement: "m/s"
#

Any ideia, of how to make this calculation happen hourly? Without an automation, I mean...

grizzled grove
#

But that would need an automation, right? As in:

#
  trigger:
      - platform: time_pattern
        minutes: '/60'
mighty ledge
#

no, templates accept triggers

plain magnetBOT
pale star
#

hello, if I have this
mqtt: sensor: - name: "Battery_SOC_Imeon_1" state_topic: "imeon_1/battery_SOC" unit_of_measurement: "%"
is there any way I can add a tag to this? I would like to filter later on based on tags. Would like a tag like "imeon_1"

hazy yacht
#

Hi, I have a current meter, which returns sensor values for all three phases (L1,L2,L3). Those are differentiate by the entity-id being sensor_a_voltage, sensor_b_voltage, etc. same goes for other units. If I want to write a template to show all of them, I can use {{ states("sensor_a_voltage") }} but how can I loop throw all three sensors replacing the id by a, b and c?

queen perch
#

when using the IMAP sensor to scan subject in the email how do you scan for partial text instead of the entire subject has to be perfect.. if i have subject "Fedex <track number>: Your Package Is On The Way" but i only wanna search for "On The Way" but i cant get it do it.. it only works if the entire subject line is correct and only want to search part of it
{% elif 'out for delivery today' in subject %}
thats what i have out of the email subject.. the subject is
FedEx Shipment 00000000: Your package is now out for delivery today

mighty ledge
queen perch
#

what i get is blank for the sensor.... but if i click on the sensor and click attribute the email is in there

mighty ledge
#

if the full string works, but partials do not, that indicates subject is not a string but a list

queen perch
#

this is what i got

#

cant seem to uplkoad my pics

plain magnetBOT
#

Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

mighty ledge
#

or just share the text if it's code.

queen perch
mighty ledge
#

please copy/paste the attributes from developer tools -> states page

plain magnetBOT
#

@queen perch I converted your message into a file since it's above 15 lines :+1:

queen perch
#

only pasted some of it unless you want the entire thing

mighty ledge
#

it looks like a string, so it should work. Post your code

#

the full code

plain magnetBOT
#

@queen perch I converted your message into a file since it's above 15 lines :+1:

queen perch
#

so far the first 3 dont work either cuz i copy and pasted it from my Intelcom delivery so i tweaking it for fedex

#

so instead of making the sensor say on_the_way it makes the sensor blank as you see in the pic

#

and it works for my intelcom delivery.. but that one i use the entire subject line so its exact.. as it doesnt use a tracking number but when i try to search part of the subject line thats when it doesnt wanna work

#

so i figured maybe its like a windows search? you gotta do like *out for delivery then it searchs for the star

mighty ledge
#

just output the subject as the state of that sensor to see if it's a list please

#

it's literally only going to be that

queen perch
#

not sure whaty a mean or how do that

mighty ledge
#

unless there's special characters in the subject, even then searching for a single character would work or single work

#

make your value_template: "{{ subject }}"

queen perch
#

so erase the >-

mighty ledge
#

you can make it

value_template: >
  {{ subject }}

too if you want

#

then paste the state here please

queen perch
#

doesnt like that code

#
in "/config/yamls/sensor.yaml", line 566, column 0```
mighty ledge
#

post what you tried again

queen perch
#
  value_template: { { subject } }
#>-
#   {% if 'Your package has been received!' in subject %}
##     received
#   {% elif 'Your package has been delivered!' in subject %}
#     delivered
#    {% elif 'Your order has been delivered!' in subject %}
#      delivered
#    {% elif 'out for delivery today' in subject %}
#      on_the_way
#    {% endif %}
mighty ledge
#

yeah, that's not what I wrote

queen perch
#

thats what studio code changed it to

mighty ledge
#
value_template: "{{ subject }}"

or

value_template: >
  {{ subject }}
#

literally just copy/paste what I wrote

#

don't try to write it yourself if you don't understand templating

queen perch
#

neither work

mighty ledge
#

you're doing something wrong. Here, I'll write the whole thing out...

queen perch
#

end of stream pr a document seperator is expected

mighty ledge
#

Yes cause you're not honoring yaml or jinja

queen perch
#

i just copied what you wrote

mighty ledge
#
#######################################
### FedEx       Deliveries Template ###
#######################################
- platform: imap_email_content
  server: outlook.office365.com
  name: FedEx Delivery
  port: 993
  username: @@@@@@@@@@@@@
  password: @@@@@@@@@@@@@
  senders:
    - TrackingUpdates@fedex.com
  value_template: "{{ subject }}"
#

well, ya did it wrong 🤷‍♂️

queen perch
#

nope

mighty ledge
#

I'm not sure what to tell you. There isn't much to this

#

it's a single template

#

there's only so many rules

#

what you posted above violated yaml rules

queen perch
#

\https://imgur.com/a/wr5VCOS

mighty ledge
#

dude

#

fFs

#

copy exactly what I wrote

queen perch
#

i just copied what you wrote

mighty ledge
#

no you didn't

queen perch
#

i did

mighty ledge
#

No, you literally removed 2 fucking spaces

queen perch
#

i copied value_template: "{{ subject }}"

#

u see in the pic it does not work

mighty ledge
#

Right, but where was value_template before?

#

was it indented by 2 spaces?

#

is it indented by 2 spaces on the full thing I just posted?

queen perch
#

no idea i just replaced my entire code to your code

#

as you seen

mighty ledge
queen perch
#

k i spaced it

mighty ledge
#

ok, so paste the state here please

queen perch
#

FedEx Shipment 0000000000: Your package is now out for delivery today

#

i replaced the number with 0's

mighty ledge
#

Ok, this is working in the template editor w/o issues

#
{{ 'out for delivery today' in 'FedEx Shipment 0000000000: Your package is now out for delivery today' }}
#

so there's no special characters and it's not a list

#

so your original code should work whenever the imap sensor updates

queen perch
#

ya its just leaving it blank. i have a automation to set it say "unknown" on boot up of home assistant. so the sensor has something but as soon as the email comes in the state goes blank wont put in "on_the_way"

#

as you seen in the orginal pics

#

ill re add the if statesments and do a full home assistant restart maybe that help?

mighty ledge
#

probably not, the code is fine including your yaml & spacing so it should just be working.

queen perch
#

ah ok i did it anyways.. so be 5 min or so before it comes back up sometimes 10 min... would clearing the cache work? like when home assistant reboots in my automation it sets it to unknown so i know that part is working then not too long it flips it to blank and and then i can see the email in the attribute

mighty ledge
#

No clearing cache only fixes frontend issues.

queen perch
#

ill try clearing cache cant hurt right?

#

oh ok

queen perch
#

so i tried full subject line didnt work.. i looked in the logs i get this error.. maybe its the issue dunno how to fix that? ```Logger: homeassistant.components.recorder.db_schema
Source: components/recorder/db_schema.py:585
Integration: Recorder (documentation, issues)
First occurred: 12:42:46 PM (4 occurrences)
Last logged: 12:42:49 PM

State attributes for sensor.fedex_delivery exceed maximum size of 16384 bytes. This can cause database performance issues; Attributes will not be stored```

#

is that because of the body of the email is large?

mighty ledge
#

that's telling you it's not going to store the attributes in the database

queen perch
#

so would that possibly reason why its not storing it then why i get blank? and is there a way to not load the body of the email in the imap sensor

#

i dunno i just asking as i have no idea

#

cant post the entire attribute either discotrd says like -4200 lines or so

mighty ledge
#

You don't need the whole attributes, all you care about is the subject

#

and your code for the subject is good aside from not having an else case

queen perch
#

well if have the elseif's but doesnt seem to be working

mighty ledge
#

which is why you're getting a blank result, but that doesn't explain why 'xxx' in subject is not working yet the full string does. Either you're unknowingly lying about the full string working or something else is going on. You've output the subject directly in the state and that gave you a subject without list indicators. Therefor 'xxx' in subject should work every time. I don't use that integration, so I can't comment on it's behavior.

plain magnetBOT
#

@queen perch I converted your message into a file since it's above 15 lines :+1:

queen perch
#

and thats ok i appreciate the help so far..

#

and ya it says canada post i made it for canada post too... but they all the same

#

so i thinking its like that database overflow issue but i just guessing..

#

guess ill play with it later..

marble hazel
#

Trying to get a home built GPS sensor to send Latitude/longitude data to HA through MQTT. The sensor publishes to a topic called "car/gps/attributes" a string that looks like {"latitude":-50.34724,"longitude":199.21634} and I'm using the following in configuration.yaml to try to get the sensor into HA:

mqtt:
  device_tracker:                    
    - unique_id: car_mqtt_gps        
      name: "Car GPS Sensor"         
      state_topic: "car/gps/state"   
      json_attributes_topic: "car/gps/attributes"
      json_attributes_template: "{{ value_json.latitude }}, {{ value_json.longitude }}"

The sensor is found by HA and shows as an entity under MQTT. The sensors state changes with the "car/gps/state" topic but I'm not getting the lon/lat data anywhere, at least no where I can find, and the entity wont show on a map card.

I'm sure I'm making a really dumb mistake but I can;t work out what it is, any help would be great....

inner mesa
#

I suggest removing the json_attributes_template line entirely as the content is already a JSON dict

#

You're not generating proper json there, so I'm sure it's confused

marble hazel
#

Man, I both hate and love when this happens. Love it b/c my sensor is now working and it only took one quick question, one simple answer and 5 mins.... Hate it b/c I always feel so dumb for not thinking of trying that myself...

Thanks for the help, I'm smiling again....

loud mountain
#

is this correct ? i want to add a binary sensor for quick automation trigger

      name: "Nobody home"
      state: {{states('zone.home') | float(default=0) == 0  }}```
inner mesa
#

You're missing a -

#

And you need to surround your template in quotes

#

And you need to nest the whole thing under template:

#

But that sensor is unnecessary if all you want to do is trigger on an empty zone. Just use a state or numeric_state trigger

loud mountain
#

is there a check for Visual code, i always miss small quote

inner mesa
#

?

#

There's a Home Assistant extension if that's what you mean

loud mountain
#

i mean extension for visual code that does checking for quote?

inner mesa
#

For quote?

loud mountain
#

yes

inner mesa
#

I don't think it will catch not surrounding the template in quotes

#

Otherwise I don't know what you mean by 'for quote'

loud mountain
#

so i wonder why not working

inner mesa
#

The things I said above

loud mountain
#

yeah i should have check the docs before

#

thanks @inner mesa

silent vector
#

I have 2 wait for triggers 1 after another. If the second one times out and continues on timeout. I am unable to avoid the error when wait.trigger none from the second wait for trigger.

second_wait_to_state: "{{ iif(wait.trigger != none,wait.trigger.to_state.state,'null') }}"
#

UndefinedError: 'None' has no attribute 'to_state'

marble jackal
#

An iif always renders both the true and false statement

#

Don't use it if the false statement can generate errors

silent vector
#

How would you recommend getting around this? I guess using ```py
{% if wait.trigger is not none %} {{ wait.trigger.to_state.state }}
{% endif %}

marble jackal
#

To replicate what you had:
{{ wait.trigger.to_state.state if wait.trigger is not none else 'null' }}

#

Which will give the string 'null' if the wait trigger is none

silent vector
#

That's cleaner thank you.

silent vector
#

Does wait for trigger not accept templates in the entity_id field?

- wait_for_trigger:
     - platform: state
        entity_id: "{{ room_lights | reject('eq',first_wait_entity_id) | list }}"
continue_on_timeout: true

I would rather use wait for trigger vs wait for template to get the to_state without having to get complex with wait for template.

#

Ignore my spacing

mighty ledge
#

it's all over the place

silent vector
#

Well I know it's because I'm on mobile and pasting from a code editor but spacing isn't the issue it doesn't like a template it appears.

mighty ledge
#

yeah but if you're posting code from the editor entity_id and platform would be aligned at least

#

literally every row is messed up

#

But in regards to templating entity_id for triggers, that's also not possible. The only thing that can be templated in triggers are template triggers

silent vector
#

Message malformed: Entity {{ room_lights | reject('eq' is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
I attempted to align them and failed lol

#
      - wait_for_trigger:
          - platform: state
            entity_id: "{{ room_lights | reject('eq',first_wait_entity_id) | list }}"
        continue_on_timeout: true
#

There you go lol those 2 are aligned.

silent vector
#

Yeah I figured it's not allowed just wanted to be sure. I have another idea for handling this.