#templates-archived

1 messages · Page 64 of 1

marble jackal
#

is that correct?

sullen osprey
#

Is it possible to format the output ? Like add a carriage return at the middle or something like this. Because in my lovelace the value go over the card and i miss some info

marble jackal
#

I'm not sure what the actual ouput of that attriubte is

sullen osprey
#

Its a adress

#

So i would like the overflow make a automatic carriage return

mighty ledge
#

that's handled by your frontend

#

because only your frontend knows when it overflows.

cinder lotus
#

No the media player was on

mighty ledge
#

does it change when you use the number outside mushroom cards?

merry furnace
#

Thansk for spotting it, was not in my code anymore and should not have been either. Could have become a real headbreaker 😂

reef pecan
#

Hi! I hope to be right here. I am pretty new and try to add a fhem esprgbww controller using mqtt. Unfortunately I can not get hs(v) working and no help in the community forum. However, according to sir_goodenough (forum name), there should be several ways to add hs to a mqtt light template. but whatever I try, I am only getting yaml errors. so far I am having the following config:

plain magnetBOT
#

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

reef pecan
#

hs_command_template does not work in template schema, but I need this for on/off because of the strange json-format used here...

#

I would be very happy to get some hints as this is a major show-stopper for me when migrating from fhem to HA

sonic ember
#

How do I reference a helper entity in an automation if I'm using the UI? Is it correct if I just use "Edit in Yaml" for my action, and then use this yaml for the value of the entity?

data:
  temperature: {{ states('input_number.my_entity') | float(2) }}
#

I ask because I think it's right, but when I go into the automation again the data is gone again.

inner mesa
#

Surround the template in quotes

sonic ember
#

Ahh thanks!

sullen osprey
#

I took the attribute into a automation when i leaving Zones and my automation was not trigger. I believe the Zones attributes didnt change ?

inner mesa
#

You could check that

fleet viper
marble jackal
#

do you have it working without templates? So with a static name and static image?

reef pecan
#

seems that no one knows about templates with mqtt/hs/lights 😦

fleet viper
mighty ledge
#

post what you've tried

#

and post the working call w/ static name and image

#

@fleet viper

fleet viper
#

I've tried message with just "test" and its fine

mighty ledge
#

I suggest you take a look at the pins in this channel first and try again

mighty ledge
#

take a look at the 2nd pin

visual matrix
#

Just wondering the way to abbreviate a sensor string? ex: a sensor with the text : Spotify - K-POP (feat. Bad Bunny & The Weeknd) I would like to limit it to like 20 characters

mighty ledge
#

same as slicing a list [:20]

visual matrix
#

thanks for the tip! looking into it

#

And would there be away to remove the brackets and whats between them?

mighty ledge
#

you mean the parenthesis?

visual matrix
#

yeah haha mybad

mighty ledge
#

you can use regex replace

#

value | regex_replace('\(.*\)', '')

fleet viper
visual matrix
#

thanks very much

mighty ledge
fleet viper
#

Im confused why this doesn't work

#

"{{sensor.p1s_01p00a382700721_task_name}}"

#

when it seems it should just be an expression in Jinja

#

does template editor not pull in HA sensors by default?

inner mesa
#

that's just not how you extract a state

fleet viper
#

It's a string value. is that still a state?

inner mesa
#

you're not using the right syntax

fleet viper
#

i know, thats what its telling me 🙂

#

should it just be " {{ states.sensor.p1s_01p00a382700721_task_name }} "?

mighty ledge
#

that gives you the state object

fleet viper
#

figured it out i think " {{ states('sensor.p1s_01p00a382700721_task_name') }}"

mighty ledge
#

that will get you the state

fleet viper
#

which is returnnig the string i want

willow prism
#

Hello team! I have a question: I try to extract the value when my dishwasher is finished. I´m halfway through but I want to remove the date from my output. Can someone help me? Currently value_template: "{{ states('sensor.bosch_smv4hde33e_remaining_program_time') }}" has an output of value_template: "2024-01-12T21:09:20+00:00". I would only need the time and in CET time (so one hour on top of the output). Is this possible?

inner mesa
#

something like: {{ (states('event.repair')|as_datetime|as_local).time().replace(microsecond=0) }}

willow prism
unkempt burrow
#

have a odd question that maybe someone can help me out with. Trying to setup an automation in homekit where if a switch changes state to ON that it will play a warning on the homepods in the house. To do this think i need to change the type of sensor from occupancy to switch in HA (using home assistant to Homekit Bridge). This is the sensor: "binary_sensor.driveway_person_occupancy

#

Homekit wont let me automate on the type occupancy

#

plus it triggers on the entire room for any occupancy sensor.

inner mesa
#

you could just do that with an HA automation

#

unrelated to templates

unkempt burrow
#

I didn't think you could play audio directly from HA to Homepods

inner mesa
#

I've done it

unkempt burrow
#

have any links on how you accomplished that ?

inner mesa
#
test_good_morning:
  sequence:
    - service: persistent_notification.create
      data:
        message: Good Morning!
    - service: tts.google_translate_say
      data:
        entity_id: media_player.homepod
        message: "Morning Passed"
#

just like that

unkempt burrow
#

interesting, well that is way less Janky that the path i was trying to take.

inner mesa
#

haven't used it in a while, but I just test it and it works

unkempt burrow
#

do i need to do anything to configure the tts.google service ?

unkempt burrow
#

been ussing node-red for too long 🙂

inner mesa
#

this is a service call:

    - service: tts.google_translate_say
      data:
        entity_id: media_player.homepod
        message: "Morning Passed"
#

you would call something like it wherever and however you make service calls

#

my script is just an example

#

you could probably do it all in Node Red if you want, but I know nothing about it

unkempt burrow
#

Thanks for the help, ill kick it around this weekend.

spice current
marsh cairn
#

Unlikely, because very few people are motivated to fix stuff GPT breaks.

#

But... you could have a look at the sensor group helper in the UI.

spice current
marsh cairn
spice current
dreamy sinew
#

no, its a read some docs and try to work out your own solution using your own system. There are tools built into the product to help you test things

marsh cairn
#

And you got a free hint

dreamy sinew
#

GPT really doesn't understand what's going on so you are even worse off using that as a base than if you tried on your own

spice current
spice current
fallen kernel
spice current
marble jackal
#

Things to understand

  • All states are strings, average doesn't automatically convert that for you
  • You need to ensure the state is numeric, otherwise you'll get errors when a sensor is unavailable
  • Instead of the state template returning unavailable you should use the availability template option
  • ChatGPT isn't aware a modern template sensor format has been introduced, it's still using the legacy format
#

@spice current more hints 🙂

lyric comet
#

Before I go and reinvent the wheel, does anyone have a macro to process the new output from the calendar.get_events service and get a nice date and time ordered list from multiple calendars. Thanks in advance.

marble jackal
#

I don't, but it sounds like a good idea💡

marsh cairn
spice current
proud cradle
#

Can't I move trigger based template sensors into an include file?

marble jackal
marble jackal
halcyon dawn
#

Hey guys, quick Question. I use a template sensor to extract one value from an thermostat.
Template:
{{ state_attr('climate.nspanel_buero_thermostat', 'temperature') }}

Is there a way to make it "re-usable" I have multiple devices to extract it an would like reuse the same template and just change the "'climate.nspanel_buero_thermostat" id.

In this specific example, it is not necessary to specify a different ID. However, I may have more complex templates and would like to know what I should pay attention to in order to keep them as "general" as possible and to be able to reuse them.

inner mesa
#

not in a meaningful way

#

You could use an input_text entity for the entity_id, but then it would change everywhere you use it. Or you could use a template with a macro wherever you need it, but that's not always possible and it's probably even more typing

#

it's such a simple template that there isn't anything to optimize

#

Create a template sensor with a custom event trigger and then use the event data in the template for the state? It all seems unnecessarily complicated

woven zealot
#

I am fairly new to HA. Coming from CQC. I am working on a template to announce (TTS) the time and temperature on the hour and half hour. I have it working mostly, but the announcement of the minute comes out as "zero zero" and

#

" three zero" instead of thirty. How can I correct that?

#

Here is the tmeplate The time is {{ as_timestamp(now())|timestamp_custom ('%-I %M') }}, and the temperature is {{ states('sensor.openweathermap_temperature') | round(0) }} degrees, but it feels like {{ states('sensor.openweathermap_feels_like_temperature') | round(0) }}"

#

Also, how can I do a return when writing a message without it immediately posting?

halcyon dawn
marble jackal
woven zealot
#

Thanks

marble jackal
#

Which TTS integration are you using?

lyric comet
#

If you paste your template into the Dev Tools does it resolve correctly?

woven zealot
#

media_player.vlc_telnet and tts.google_en_com

marble jackal
#

BTW, you can replace {{ as_timestamp(now())|timestamp_custom ('%-I %M') }} with {{ now().strftime('%-I %M') }}

#

Those are entity_ids, not an integration. Are you using Google Translate Say?

woven zealot
#

I'll try that replacement and test it when the time is at 40

#

Jany_t yes it does

marble jackal
#

It will give the same result, it's just a more efficient template

lyric comet
#

If might also be worth adding the : eg %-I:%M

marble jackal
#

That will help a lot probably

lyric comet
#

So it looks like a time

marble jackal
#

The TTS integration will understand it's a time then

#

(just wanted to actually finish my sentence, I was already too invested in swiping it)

woven zealot
marble jackal
#

No, it doesn't

#

Use ('%-I:%M')

woven zealot
#

This is what I changed it to: {{ now().strftime('%-I %M')

#

'Should it be different?

marble jackal
#

You still don't have the : between the hours and minutes

#

Which a normal time string has

#

You have a space

woven zealot
#

Ah, I missed that.

#

Yes, just tested it and it woks correctly. thank you both

narrow surge
#

Can a template sensor replace the actual sensor?

marble jackal
#

no

wanton sapphire
#

hi all, the templates {{ as_timestamp(now()) }} {{ as_timestamp(utcnow()) }} both render the same timestamp, although {{ now() }} {{ utcnow() }} are different (1 hour apart). Is that on purpose or it might be a bug?

lyric comet
wanton sapphire
#

thanks!

dry narwhal
#

Quick question. Is it possible to run services in a template?
Rather than calling a script which then writes to a helper, directly call the service, write to a variable and proceas that variable inside the template?

haughty breach
dry narwhal
#

Too bad. I was hoping to make it a bit faster and more direct... and without additional helpers.

mighty ledge
dry narwhal
#

Well, since todo lists have no search feature I wanted to use an input_text as search string field and then use a markdown card with template to get the items, store them in a variable, filter the result according to the search string (input_text) and then create a list of matching results or links matching the results.

#

I think I know how to do it with scripts/automations, but not without (and without anything but the initial input_text).

onyx tapir
#

If I'm adding this to my templates.yaml I get an error: can't figure out what is wrong.

- sensor:
    - name: "TempAircoZolderSchuur"
      unique_id: TempAircoZolderSchuur
      value_template: "{{ state_attr('climate.airco_zolder_schuur', 'current_temperature') }}"
      friendly_name: "Temp Werkkamer Zolder Schuur Airco"
      unit_of_measurement: "°C"

    - name: "NordPool Energyprices"
      unique_id: 9e773602-c9d2-4e91-9753-3cdf9d7e6aaf
      unit_of_measurement: "€"
lofty mason
#

value_template I think should be state instead. Value template is the legacy template format

onyx tapir
#

Thanks I changed value_template to state. It's not that I don't try to read the manual... more that I fail to spot the error.

marble jackal
#

friendly_name is not valid for the modern format

#

name already determines that

onyx tapir
#

Thanks, I noticed I had one more error and was able to isolate this one. It works as intended now: ```- sensor:

  • name: TempAircoZolderSchuur
    state: "{{ state_attr('climate.airco_zolder_schuur', 'current_temperature') }}"
    unique_id: TempAircoZolderSchuur
    unit_of_measurement: "°C"````
#

It gets the temperature from an airco unit for a graph that accompanies an thermostat entity for the airco unit.

plain magnetBOT
#

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

bright quarry
#

why isn't my above frontend card colorized in has anymore after updating ?

marble jackal
#

Probably because you updated card-mod, which has a breaking change

slow vine
#

can I have a newline inserted in a template. this example works but on one line.:

- service: persistent_notification.create
  data:
    title: "heat"
    message: >
      prev temp:{{ states('input_number.previous_upstairs_local_temp_heat') }}
      cur. temp:{{ state_attr('climate.2nd_floor', 'temperature') }}

inner mesa
#

message: "{{ states('sensor.aarlo_battery_level_catbox') ~ '\n' ~ states('sensor.aarlo_battery_level_family_room') }}"

slow vine
#

I just changed the > to | and it worked. I tried without the ~ it didn't work, i guess that would work.
Which is better?

#

well the ~ '\n' ~ didn't work either so I guess i'll use message: |

inner mesa
#

it's works fine, I tested it

#
service: persistent_notification.create
data:
  message: "{{ states('sensor.aarlo_battery_level_catbox') ~ '\n' ~ states('sensor.aarlo_battery_level_family_room') }}"
#
unavailable
24
#

but whatever works for you..

slow vine
#

yeah I just tried again. I had the closing }} for each line. I guess it boils down to personal pref of what is clearer to read.

inner mesa
#

to some degree, yes

rustic raft
#

I noticed ChatGPT (4) is pretty good at helping debug, find syntax errors, and resolve HomeAssistant template string issues (And yaml issues) 👍

plain magnetBOT
#

ChatGPT and other "AI" systems do a fantastic job of generating well structured, convincing looking answers... that are either totally garbage or, if you're lucky, have subtle flaws. Don't use them to "help" others, and don't use them yourself.

heavy crown
#

Side-note: I have seen this message before but that does not mean it should not be used.... I use it frequently just to get me in a certain direction. As long as you know that this has to be treated with care DO use it....and for sure donot come asking for support if it did not help 🙂

fickle sand
#

You can certainly use it for your own system. If you are able to adjust the output to something working.

But to use AI to give advise to others is something different as not everyone has the knowledge or the ability to see if the code is not (fully) correct or to adjust it accordingly

lyric comet
# lyric comet Before I go and reinvent the wheel, does anyone have a macro to process the new ...

In case anyone needs it:

    {%- from "easy_time.jinja" import easy_time, big_time -%}
    {% set ns = namespace(items=[]) -%}
    {% for c in calendars %}
    {% for i in calendars[c]['events'] %}  
    {% set ns.items = ns.items + [ {'start':
    i.start, 'summary': i.summary} ] %}  
    {% endfor %} 
    {% endfor %} 
    {% for item
    in ns.items|sort(attribute='start') %}
    {{ easy_time(item.start)}} {{item.summary}}
    {% endfor %} 

You need Petro31's excellent easy_time macros installed to get a nice read. It takes the variable provided by the calendar.get_events service.

silent vector
#

Is there a var in jinja that contains all defined variables?

#

Something like vars and it's all defined variables in the context.

plain magnetBOT
#

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

marble jackal
#

You need to assign the input to a variable first to use it in a template

pallid pike
#

Thanks, @marble jackal . I had tried that, but it wasn't having it. Let me dig deeper into that

marble jackal
#
action:
  - variables:
      camera_label: !input camera_label
  - service: script.camera_brightness
    data:
      camera_name: "{{ states(camera_label) | replace('_cam.', '') }}"
      command: brightness
      brightness: 4
pallid pike
#

Same problem, sadly.
The trace shows

data:
  camera_name: '{{ states(camera_label) | replace(''_cam.'', '''') }}' ```
marble jackal
#

That's not an issue. That's just something which happens when it's parsed to json

pallid pike
#

Ah, damn. So it was probably working all this time. Cheers, Fes

worldly spindle
#

Trying to have a sensor value set to the name of the AP a phone is connected to. This template is filtering access points down to the one whose mac address matches the mac address the phone is connected to. Nothing gets returned (the phone is connected to an access point, I checked). Maybe comparing mac addresses like this isn't correct? Any ideas?

# Phone locators                                
  - platform: template                          
    sensors:                                    
      tim_phone_location:                       
        friendly_name: Tim Phone Location       
        value_template: >                
          {% set ap = states.device_tracker | selectattr('source_type', 'eq', 'router') | selectattr('mac', 'eq', state_attr('device_tracker.tim_s_s21', 'ap_mac')) %}
          {{ ap.friendly_name }} 
inner mesa
#

are "source_type" and "mac" attributes of the device_tracker entities you want to filter?

#

if so, you wanted attributes.source_type and attributes.mac

worldly spindle
#

Yes they are. So it will look like this?

{% set ap = states.device_tracker | selectattr('attributes.source_type', 'eq', 'router') | selectattr('attributes.mac', 'eq', state_attr('device_tracker.tim_s_s21', 'ap_mac')) %}
inner mesa
#

yes. does it work?

worldly spindle
#

No, this is in the logs

Logger: homeassistant.helpers.template
Source: helpers/template.py:2318
First occurred: 7:33:57 PM (2 occurrences)
Last logged: 7:33:57 PM

Template variable warning: 'generator object' has no attribute 'friendly_name' when rendering '{% set ap = states.device_tracker | selectattr('attributes.source_type', 'eq', 'router') | selectattr('attributes.mac', 'eq', state_attr('device_tracker.tim_s_s21', 'ap_mac')) %} {{ ap.friendly_name }}'
inner mesa
#

oh, you didn't actually extract the device_tracker

#

and "friendly_name" isn't part of the state object

#
{% set tracker = states.device_tracker | selectattr('attributes.source_type', 'eq', 'router') | selectattr('attributes.mac', 'eq', state_attr('device_tracker.tim_s_s21', 'ap_mac'))|list|first %}
{{ tracker.name }}
worldly spindle
#

I'll try that

inner mesa
#

you can just stick it right in devtools -> Templates and debug there

worldly spindle
#

That worked, thank you! Why 'name' and not 'friendly_name'?

inner mesa
#

name will use friendly_name if it exists, and otherwise falls back to name

#

it's more robust

worldly spindle
#

Got it. Thanks for your help!

inner mesa
#

it will error out if it doesn't find one that matches

worldly spindle
#

That's fine. Thanks

inner mesa
#

something like this will fix it:

{% set tracker = states.device_tracker | selectattr('attributes.source_type', 'eq', 'gps')|list|default(['No Device'], True)|first %}
{{ tracker.name if tracker.name is defined else tracker }}
torn meteor
#

for media_player, how on earth does the Lovelace UI show current position of a TV show time, when none of that data is changing in the state? i'm trying to get time remaining/current percentage played

#

i see a position attribute for my apple TV media player, but it doesn't change as time progresses. it's always something like 9

#

duration doesn't change, either

lofty mason
#

As a general rule we don't want the state machine changing every second to track time elapsing, too much churn. That's how the timer works too.

torn meteor
#

hmm. but media_position_updated_at doesn't change either

#

unless i run update_entity on it

lofty mason
#

it doesn't need to change

#

it probably changes only when you play/pause

torn meteor
#

yeah. i my guess was it compares last time when state changed play/pause vs duration, etc

lofty mason
#

otherwise if you have a 10 minute video, and you were at media position 5 minutes, and the updated_at was 2 minutes ago, then you can infer you're at 7 minutes.

torn meteor
#

the whole reason is i'm trying to add a trigger to wait until an episode is finished (not just paused or idle)

marble jackal
#

If you know when it was last updated, and what the total duration of the media is, you can calculate how long it will take to end

#

oh, Discord cache strikes again

dull prairie
#

hi, i want a template wich i can use in a glance card to show if my washer is on. i want to do it with a power sensor. someting like:

  - sensor:
      - name: "Status_Waschmaschine"
        state: >
           if (states['sensor.waschmaschine_power'].state > 2)
            return "on";
            else
            return "off";

but i cant get it to work.

plain magnetBOT
#

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

dull prairie
#

is this even possible? i only want to see it when its "on" (this is possible with the entity filter card right?

marble jackal
#

you are not using Jinja, which is used for templates

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

marble jackal
#

you should also use a binary sensor, that will return on on true and off on false

#
template:
  - binary_sensor:
      - name: "Status_Waschmaschine"
        state: "{{ states('sensor.waschmaschine_power') | float(0) > 2 }}"
#

also, all states are strings, so you need to convert it to a float or int to compare it with 2

dull prairie
#

ah okay thank you!

#

i will try an give you an feedback 🙂

#

it works (Y)

thin pivot
#

If I wanted to display the last time a climate entity was changed from "off" to "heat" in days how might I do that? I want to know how long a heater has been running

#

I can see it in the logbook.

#

I want to display it in Lovelace

untold void
#

how do I list all my lights like this?
['light.bagno', 'light.bagno_rf', 'light.bagno_sx']

lyric comet
inner mesa
#

{{ states.light|map(attribute='entity_id')|list }}

silent vector
#

How would I remove kvp from a list of dictionaries if the key is search foo for example

inner mesa
#

you have to create a new dict or list and reject it

silent vector
#

Do you have a quick example?

inner mesa
#

do you have an example of your "list of dictionaries"?

silent vector
#
[{"SantaFoo":"moon","EveFoo":"mars","Description":"ha"]}

foo is always at the end.

mighty ledge
#

rejectattr

silent vector
#

But how would you rejectattr if the key isn't static?

#

As in if there's a bunch of keys with Foo at the end?

mighty ledge
#

you'd have to convert it to kvps w/ .items() and reject based on searching the key

#

then turn it back into a dict

inner mesa
#

I assume that you wanted to flip the order of ]} at the end

silent vector
#

Yep I did

silent vector
#

Figured it out thank you

paper mortar
#

is there a date function of some sort that could return the 'next Thursday' from now() or do I have to do some maths with day of week

marble jackal
#

@paper mortar yes, you'll need to do some math with day of week

#
{% set date = now() %}
{{ date.date() + timedelta(days=(11 - date.isoweekday()) %7) }}
paper mortar
#

thanks ya I did something similar but offsets to the next week if it lands on a Thursday. Just wanted to see if there was a simpler function.

thin pivot
lofty mason
#

I thought last_changed was the most recent state change, and last_updated was any state or attribute.

lucid thicket
lyric comet
opaque marten
#

I'm sorry if this is the wrong place.
I'm very new to HA, have a home assistant green running since last week and love it. But I'm by no means a programmer or understand what I'm doing.
Here's my current question:

I have a GPS tracker for my dog. I can see a lot of entities from it. One is a device_tracker that has in it's history exactly the data I want to have displayed on my dashboard (and trigger an automation with it, but that's not as important right now.)
I want to see a card in the dashboard that displays how long ago my dog was outside for the last time.
The data is there. I can click the device_tracker, hover over the history and it shows me exactly what I want to see on the dashboard. But I have no idea how to get it out of there.

#frontend-archived sent me here:

Ah, okay, so a normal HA device tracker. I don't have any, so I have not done it yet.
But I could think of two options (both not so simple):

  1. Create a card that accepts templates for the state and then using templating to calculate the time between state change from not_home until home.
  2. Create a template sensor ( menu item devices & services -> helper -> template -> sensor) and do the calculation there.
    Option two being a bit simpler and I am sure that someone in ⁠templates can help you with the syntax

Here is the original screenshot that I included
https://media.discordapp.net/attachments/460846676358332417/1197118083056291870/Bildschirmfoto_2024-01-17_um_10.50.51.png?ex=65ba1a18&is=65a7a518&hm=4f848ccfeab496105ab0e13f6ea80efad5758b8217a0ac1f0702e639906e7fb0&=&format=webp&quality=lossless&width=479&height=622

lucid thicket
lucid thicket
#

That will give you a datetime of when the dog last came inside. In the front end you can decide how to display it. Some cards will show past datetimes in a relative format (‘2 hours ago’) or if you want something more specific you can use a template card to calculate the time. The reason that I didn’t provide a template to calculate the time difference directly is because it’s generally poor practice to create a sensor that changes every minute because it clogs up your history database with useless data. If you calculate the time delta in the frontend then it is only calculated when someone looks at it, and it doesn’t store that data.
It is more efficient to store a few datetime states each day as opposed to 1440 time deltas each day.

lyric comet
#

You could also use 2 date time helpers, one set in an automation when the dog goes out and one when he comes back. Then you can use a simple time difference template on your card to show the last time he came in from outside and how long he was out.

sick ice
#

Can someone help me get my head around this?

{{(as_timestamp(now()) - as_timestamp(states.binary_sensor.ac_running.last_changed)) | timestamp_custom("%-d days and %-H hours", false) }} {{(now() - states.binary_sensor.ac_running.last_changed) }} {{now()}} {{states.binary_sensor.ac_running.last_changed | as_local}}

1 days and 8 hours
8:50:44.670461
2024-01-17 22:47:00.321749+11:00
2024-01-17 13:56:15.651231+11:00

Why is the first output showing the time difference as 1 day 8 hours when the difference is just 8 hours?

#

I managed to get the right output by totally changing my approach but I still want to know why I'm getting an extra day on this

lofty mason
#

%d is "day of the month", not number of days.

#

If you printed out the full timestamp custom after your subtraction it would probably be something like Jan 1 1970, 8:50AM.
So that's "day 1, 8 hours"

lofty mason
sick ice
sick ice
# lofty mason Maybe you want something like this: ``` {% set delta = (now() - states.binary_...

Thanks - I got the output I wanted with this:

{%- set last_change_time = states.alert.garage_door.last_changed -%}
{%- set time_difference = current_time - last_change_time -%}
Garage door open for {{ '' if time_difference.days == 0 else time_difference.days ~ ' day' ~ ('s' if time_difference.days != 1 else '') ~ ' and ' }}{{ time_difference.seconds//3600 }} hour{{ 's' if time_difference.seconds//3600 != 1 else ''}} and {{ time_difference.seconds//60 }} minute{{ 's' if time_difference.seconds//60 != 1 else ' ' }}```

Obviously extra fluff in there now, but the real question was why the first attempt didn't do what I expected. thankyou
#

Garage door open for {{ time_difference.days ~ ' days and ' }}{{ time_difference.seconds//3600 }} hours
Without the fluff

#

I'm sure someone will tell me a way less convoluted way to remove 0 days and use friendly singular/plural language in strings.

plain magnetBOT
#

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

vague dawn
#

Sorry I was asking why this works:

#
      hours_till_2am:
        friendly_name: "Hours Till 2am"
        unit_of_measurement: 'hours'
        value_template: >
          {% set t = today_at("02:00:00") %}
          {% set s = t if now() < t else t + timedelta(hours=24) %}
          {{ ((s - now()).total_seconds() / 3600) | round(2) }}                   ```
#

but this does not:

#
        friendly_name: "Hours Till Charge Start"
        unit_of_measurement: 'hours'
        value_template: >
          {% set charge_start_time = states('input_datetime.calculated_charge_start_time') %}
          
          {% if charge_start_time not in ['unavailable', 'unknown', 'None'] %}
            {% set t = strptime(charge_start_time, "%H:%M:%S") %}
            {% set s = t if now() < t else t + timedelta(days=1) %}
            {{ ((s - now()).total_seconds() / 3600) | round(2) }}
          {% else %}
            0
          {% endif %}```
sick ice
haughty breach
# vague dawn ``` hours_till_charge_start: friendly_name: "Hours Till Charge Star...

Assuming the input datetime is time only... {% set t = strptime(charge_start_time, "%H:%M:%S") %} returns a time zone naive datetime object for the rendered time on January, 1 1970... now() is non-naive, and you can't compare non-naive and naive types. Just use the same function as the first example {% set t = today_at(charge_start_time) %}.

quartz heron
#

how to add an icon to this please

#

steamos_pc:
friendly_name: "SteamOS PC"
value_template: >-
{{ states('sensor.steamos_pc_electric_consumption_w') | float > 10 }}

inner mesa
#

Sigh, cross post. Please don't do that

sick ice
#

can someone help me with this template syntax in an automation?

wait_for_trigger:
  - platform: template
    value_template: "{{ now() - states.trigger.to_state.last_changed >= timedelta(seconds=5) }}"

I'm trying to get my action to wait for x time after the entity has stopped changing.

#

automation is keeping the power and brightness state of multiple zigbee dimmer switches instate. the hardware behaviour of dimming to turn off upsets the automation when I'm trying to sync brighness, so need it to wait.

fickle sand
#

That template only updates once a minute. So at the moment of triggering it's false to turn to true at the beginning of the next minute

sick ice
#

oh, so is there a way to achieve this without just having a generic 5 seconds or so (which is what I do now)?

fickle sand
#

by triggering on state change of the entity that triggered the automation

wait_for_trigger:
  - platform: state
    entity_id: <replace with the trigger entity>
    for:
      hours: 0
      minutes: 0
      seconds: 5
sick ice
#

is that different to just using the for: delay in the trigger?
Because that would still trigger after the brightness had changed, but hadn't stopped changing.
I'll plug it in and see how i go 🙂

For context, this is my automation: https://hastebin.com/share/hoyasofagi.yaml

fickle sand
#

Yes you can ditch the wait_for_trigger in the sequence if you add the for: value to the brightness initial trigger

sick ice
#

oh, i doesn't accept this:

wait_for_trigger:
  - platform: state
    entity_id: {{trigger.entity_id}}
    for:
      hours: 0
      minutes: 0
      seconds: 5
fickle sand
sick ice
#
  - platform: state
    entity_id:
      - light.living_room
      - light.dining
    for:
      hours: 0
      minutes: 0
      seconds: 5
    attribute: brightness
continue_on_timeout: false```
trying with this but still not proceeding past the wait
#

I may just use the for: with the trigger a long delay liek 10 seconds. then it works, it's just speed optimised 🙂

vague crag
#

Not sure if the right place, but i've noticed there isn't a service for + or - the temperature of a climate entity.

#

Is it still possible, did someone managed that?

rugged laurel
#

While there are no dedicated increase/decrease services, you can use the climate.set_temperature service with a template that has the current target temperature and a desired delta.

service: climate.set_temperature
data:
  temperature: "{{ (state_attr('climate.awesome_climate_entity', 'temperature') | float) + 1 }}"
target:
  entity_id: climate.awesome_climate_entity
service: climate.set_temperature
data:
  temperature: "{{ (state_attr('climate.awesome_climate_entity', 'temperature') | float) - 1 }}"
target:
  entity_id: climate.awesome_climate_entity
vague crag
#

Fine by me! Thanks man!

rugged laurel
#

If you want to get real fancy you can use the target_temp_step attribute as well to determine the jump

vague crag
#

Cool, will check that out!

vague crag
#

I also tried {{ (state_attr('climate.awesome_climate_entity', 'temperature')) - 1 | float }} but same error.

marsh cairn
#

You have to convert to float before subtracting 1

vague crag
#

Yeah I did, that was the original code from Ludeeus, but that also didn’t work. Same error.

fickle sand
#

Have you checked if the climate entity has a temperature in the devtools

marsh cairn
#

And if that entity exists at all

marble jackal
#

That attribute should already be a float though

fickle sand
vague crag
#

Yeah ofc I checked and did 😄

#

By default it returns 19.0

#

I could try without the | float

fickle sand
#

Where did you run the service? in some card? in the devtools?

vague crag
#

In a custom:button-card in a custom_fields

fickle sand
#

Aha, that explains it

#

Than you will need to convert the template to a JS variant

#
"[[[ return states['climate.awesome_climate_entity'].attributes.temperature - 1; ]]]"
#

or

"[[[ return entity.attributes.temperature - 1; ]]]"
vague crag
#

Ah you are right! That works...

#

Should've thought about that. Thanks! Really appreciate all the help!

warped cloak
#

Any plc programmer👨‍💻

plain magnetBOT
#

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

marble jackal
#

It probably expects a number, and all states are strings

#

So convert the state to a number using the int filter

#

I can imagine you would expect that, but all states are strings

#

Yes

#

That's it. A Jinja filter is preceded by a pipe symbol

#

So | int uses the int filter

plain magnetBOT
#

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

marble jackal
#

Where are you calling this service call from?

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.

marble jackal
#

That doesn't do anything sensible

#

What happens if you issue the service call from developer tools > services

#

With the template

#

What does the template show in developer tools > template

#

Okay

#

Executing it with command: 0 had the same effect

#

So the template is resolved correctly, but the service call doesn't work with 0

#

I'm testing with it now on my Pixel 7 Pro

#

It seems to go from 1 to 7

#

7 is 100%

#

But for music stream it goes to 25

#

That's still a string

#

No, all states are strings, I just explained that

#

The template editor parses it to a number though if it's the only value

#

That can be confusing

#

But the service call also works for strings

#
service: notify.mobile_app_pixel_7_pro
data:
  message: command_volume_level
  data:
    media_stream: notification_stream
    command: "1"
#

This works fine for me

#

So it shouldn't be a problem without the filter

#

This doesn't work because you need quotes around your template

#

You had them initially

#

This doesn't work because you are using double quotes inside and outside your template

#

You had single quotes outside the template before

#

No problem

#

It's going from 1 to 7

#

7 is 100%

#

And 0 should work

#

0 works for music stream and ring stream

#

Oh, now it also works for me for 0 with notification stream

#

It works with the string "0"

#

Not with the integer 0

#

Then don't apply the int filter

#

Hmm, that doesn't work

#

HA will convert it to int

#

Wait a second

#

Use this

service: notify.mobile_app_pixel_7_pro
data:
  message: command_volume_level
  data: >
    {{
      {
        'media_stream': 'notification_stream',
        'command': states('input_number.test') | int | string
      }
    }}
#

This will send it as a string

#

Replace the input_number and notify service with yours

#

You could still file a bug that 0 only works with a string, while the other values work as integer

#

Oh wait, that's for Android 7 and below

#

Hmm okay

fierce hawk
#

Morning all,
I'm having some issues with templating and rounding:
sensor.edf_tempo_prix_actuel = 73.24

I am doing this:
value: "{{ states('sensor.edf_tempo_prix_actuel') | float / 100 | round(2) }}"

but it gives me: value: "0.7323999999999999"
any idea why?

marble jackal
#

Because you are only rounding 100

#

Add parenthesis around the formula, so the round filter is applied to the formula result

fierce hawk
#

mmm where would you add the parenthesis?

fickle sand
#

Around the full statement you want to round up

marble jackal
#

"{{ ( states() | float / 100 ) | round() }}"

fierce hawk
#

yay thanks 🙂

floral shuttle
#

my rest sensors somehow moved to output another timeformat, causing my template to take the wrong turn.... the rest sensors value_template: > {% set today = now().strftime('%Y-%m-%d') %} {% set data = value_json.result.watts.items() |selectattr('0','search',today)|sort(attribute='1',reverse=True) %} {{(data|first|default(('Unknown',0)))[1]}} json_attributes_path: "$.result" and this template {% set nu = now().replace(minute=0,second=0,microsecond=0).isoformat() %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts_z','watts') %} {% if watts %} {% set data = watts.items() %} {{watts[nu] ~' W' if watts and nu in watts else 'No production estimated'}} {% else %} Offline {% endif %} which is supposed to pick the item 'now' dont match anymore

#

maybe a bit small, but the equation breaks on the timezone which is +00:00 in the dict items, and +01:00 in the template sensor... which would be the best way to fix this? supppose manipulating the template sensor would be optimal?

#

string manipulating {% set nu = now().replace(minute=0,second=0,microsecond=0).isoformat().replace('+01','+00') %} works, but it is ugly and probably dumb....

mighty ledge
#

I have no idea what you're asking

#

are you just trying to get a list of dateteimes & values?

floral shuttle
#

I need the template sensor to use the +00:00, to be able to match the dict of items that use that format

mighty ledge
#

Or just show what the date format is from your rest endpoint

mighty ledge
#

so utcnow().isoformat()

floral shuttle
#

yes but I use UTC, it moves an hour...

#

{% set nu = now().replace(minute=0,second=0,microsecond=0)|as_timestamp|timestamp_local %} has the correct hour, but with +01, and {% set nu = now().replace(minute=0,second=0,microsecond=0)|as_timestamp|timestamp_utc %} is an hour earlier, with the correct +00 as used in the rest sensors items...

mighty ledge
#

marius

#

use utcnow

#

or post the format of your timestamp, the full format.

#

I highly doubt the endpoint would show utc time format with the wrong time.

#

you're either requesting the wrong information the wrong way, or you're mistaken about the hour offset

floral shuttle
#

{% set nu = utcnow().replace(minute=0,second=0,microsecond=0).isoformat() %} makes it happen

#

so now my template sensor picks the correct item from the dict using the same offset.

#

and this would bring it back to the correct local hour{% set nu = (utcnow()+ timedelta(hours=1)).replace(minute=0,second=0,microsecond=0).isoformat() %}...

mighty ledge
#

And that does not make any sense

#

A bug should be written against the API or your need to change your rest endpoint call to get the correct timezone.

#

if you get UTC values, your result should be UTC

#

You should not have to add or subtract anything, the display will be UTC which should auto format as local when you view it in the UI

#

TLDR: You're doing it wrong and it will break when DST is applied.

#

@floral shuttle ^

floral shuttle
#

aarrgghhh

#

hitting myself here, so wait a second...

#

I had copied the following..... solar_forecast_api_zo: https://api.forecast.solar/estimate/<lat>/<long>/21/-40/1.740?time=utc #ZO so ws explicitly requesting the urc format..

mighty ledge
#

Right but if it really reports that, then the times are correct as in UTC

#

so you don't want to add anything, you just want to convert it to your local time

floral shuttle
#

yes, Ill await the next update (at the hour) and see what it returns, and whether I need to adjust my template sensor, or all is good now

mighty ledge
#

can you just post the complete template sensor so I can see what it's doing. I really don't think you need the +1 hour bs

floral shuttle
#

I took that out now, only this```
{% set nu = now().replace(minute=0,second=0,microsecond=0).isoformat() %}
{% set watts = state_attr('sensor.solar_forecast_estimate_watts_z','watts') %}
{% if watts %}
{% set data = watts.items() %}
{{watts[nu] ~' W' if watts and nu in watts else 'No production estimated'}}
{% else %} Offline
{% endif %}

mighty ledge
#

Yes, You are definitely making a mistake then

#

keep everything in UTC and you should be fine without adding the +1

#

if you add the +1, you'll be off by 1 hour.

floral shuttle
#

restarting to be sure, but I believe taking the time=utc from the rest sensor api call didnt make a difference. Maybe I should add time=cet .

mighty ledge
#

That would work, but utc will work better

#

I'm still not convinced you understand the issue

#

if you request UTC information, you just need to use the current UTC time to get the current hour.

#

even though the hour doesn't look current, it is

#

you're incorrectly thinking that the current hour is +1, when it's not.

floral shuttle
#

no I am aware of that.... I had hoped to get all data in my local time, and wouldnt need to bother with anything further. I admit not being confident that when I plot these data to a current time sensor in a chart, it picks the right time if I use utcnow() in my template sensors, and the time=utc in the api call

mighty ledge
#

that's how time works

#

@floral shuttle put this in your template editor and then look at the actual times

#
{% set x = utcnow().replace(microsecond=0) %}
{% set y = now().replace(microsecond=0) %}
{{ x }} == {{ y }} == {{ x == y }}
#

the hours will be different but the times are identical

floral shuttle
#

ha, yes, that is very clear. cool. you should add this to the time template docs, never saw it as clear as that.

#

things is I also have this which was updated 10 minutes ago, so at my local time of 14:00. and check the time in the attributes for that value...

marble jackal
#

There's no timezone information there

#

The current state value matches the 12:00 timestamp, which doesn't make much sense for both UTC or GMT +1 (unless you made this screenshot more than 26 minutes ago)

floral shuttle
#

no, it was from after the change of the hour to 14 (local time) . I figured that it shows the utc hours, and because it is a trigger based template takes the previous state.. thus accounting the 2 hours difference

#

the T and Timezone were gone from that output, so the api call did get changed when I took out the time=utc

#

it could probably be even simpler, but just taking out the complete timezone bit there in the template sensor, and just compare on the '2024-01-20 17:00:00' string. the api returns it like that without anything set on that time= option.

mighty ledge
#

Sorry work got busy

#

Just post both of your template sensors

#

Rest sensor and the template. You can remove the resource if it’s private

floral shuttle
#

no its fine, and dont apologize!

#

I think I made it work now with this simplification using just the format that is output in my last screen above and this time format: {% set nw = now().replace(minute=0,second=0,microsecond=0) %} {% set nu = as_timestamp(nw)|timestamp_custom %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts_z','watts') %} {% if watts %} {% set data = watts.items() %} {{watts[nu] ~' W' if watts and nu in watts else 'No production estimated'}} {% else %} Offline {% endif %} this makes the 2 identical using `'2024-01-19 14:00:00``

#

also, given the fact the default for the resource is supposed to be local (and not utc) I can use now() again in the template sensor.

mighty ledge
#

Can you just post both please?

#

the rest sensor and the full template sensor that uses the rest sensor

floral shuttle
#

rest sensor is:```
rest:

  • resource: !secret solar_forecast_api_z
    scan_interval: 86400
    sensor:
    • unique_id: solar_forecast_estimate_watts_z
      <<: &estimate_watts
      unit_of_measurement: W
      value_template: >
      {% set today = now().strftime('%Y-%m-%d') %}
      {% set data = value_json.result.watts.items()
      |selectattr('0','search',today)|sort(attribute='1',reverse=True) %}
      {{(data|first|default(('Unknown',0)))[1]}}
      json_attributes_path: "$.result"
      json_attributes: watts
#

template sensor: - unique_id: solar_forecast_estimate_current_hour_z state: > {% set nw = now().replace(minute=0,second=0,microsecond=0) %} {% set nu = as_timestamp(nw)|timestamp_custom %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts_z','watts') %} {% if watts %} {% set data = watts.items() %} {{watts[nu] ~' W' if watts and nu in watts else 'No production estimated'}} {% else %} Offline {% endif %}

#

the rest api resource: solar_forecast_api_z: https://api.forecast.solar/estimate/<lat>/<long>/12/0/6 # ?time=utc

#

but I exceeded the api limit now... so have to wait another hour. they did return the correct value just before that hit though...

#

only thing I need to check is whether because of the missing “T” separator now, the Frontend still represents that as a correct value.

mighty ledge
#

this is all you need

#
rest:

  - resource: !secret solar_forecast_api_z
    scan_interval: 86400
    sensor:
      - unique_id: solar_forecast_estimate_watts_z
        <<: &estimate_watts
          unit_of_measurement: W
          value_template: >
            {% set today = now().strftime('%Y-%m-%d') %}
            {% if value_json is defined %}
              {% set data = value_json.result.watts.items() |selectattr('0','search',today)|sort(attribute='1',reverse=True) | first | default %}
              {{ data[1] if data else 'Unknown' }}
            {% else %}
              Unknown
            {% endif %}
          json_attributes_path: "$.result"
          json_attributes: watts
      - unique_id: solar_forecast_estimate_current_hour_z
        value_template: >
          {% set nw = utcnow().replace(minute=0,second=0,microsecond=0).isoformat() %}
          {% if value_json is defined %}
            {% set production = value_json.result.watts.get(nw) %}
            {% if production %}
              {{ production }} W
            {% else %}
              No production estimated
            {% endif %}
          {% else %}
            Offline
          {% endif %}
#

you can get rid of your template sensor

#

but you'll lose history

#

and if you need to make selections because the first sensor is providing wrong data (offset by 1), then the first template needs to be altered.

mighty ledge
#

back, that would look like

{% set start = today_at().astimezone(utcnow().tzinfo) %}
{% set end = start + timedelta(hours=24) %}
{% if value_json is defined %}
  {{ value_json.result.watts.items() | selectattr('0', '>=', start.isoformat()) | selectattr('0', '<', end.isoformat()) | map(attribute='1') | sort(reverse=True) | first | default('Unknown') }}
{% else %}
  Unknown
{% endif %}
willow wing
#

Hey guys, i want read out a input value and build a new string to check the state, someone can assist me here where is the problem?

{% if is_state("input_select.advanced_heating_control_wohnzimmer_{{scheduler_value}}", "on") %}
Comfort
{% else %}
Minimal
{% endif %}```
inner mesa
#

You didn't construct the new string properly. You nested the templates

#

{% if is_state("input_select.advanced_heating_control_wohnzimmer_" ~ scheduler_value, "on") %}

willow wing
#

perfect thank you rob

plain magnetBOT
#

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

mild venture
#

Hi everyone, I am trying to take a response from OpenAI and put that into an automation template, but getting the error: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
My template to grab the library_name value and do an if/then for what plex is looking for:

data:
  media_content_id: '{{response_from_ai.response.speech.plain.speech|from_json}}'
  media_content_type: >
    {% if (response_from_ai.response.speech.plain.speech|from_json).library_name
    == "Movies" -%}
      movie
    {%- else -%}
      EPISODE
    {%- endif %}
plain magnetBOT
#

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

mild venture
#

Sorry was trying to make it not a file and ended up making it 2 files...

floral shuttle
mild venture
#

Got my issue resolved. If was the '{{response_from_ai.response.speech.plain.speech|from_json}}' from media_content_id. Had to remove the from_json to get it to work with Plex

slender adder
#

Is there a way to track if a light went on or off in a specific room ?

cerulean vortex
#

is there not a way to set delay_on and off in the UI for a binary sensor template?

marsh cairn
#

No. Everything more than a state's template (or a static icon after setup) has to be done in YAML

cerulean vortex
#

and I cannot edit the YAML for a UI-created template, right? so I need to delete from the UI and recreate in configuration.yaml?

marsh cairn
#

Correct

cerulean vortex
#

cool, thanks for confirming.

#

can I get away with just a yaml reload or do I need a full HA restart when testing these yaml templates?

honest ravine
#

What are % and %- called, and how do I search for their description/use?

round coral
#

Rant:
I would like to say, jinja is an extremely lousy way to do templates.

Convenient in simple cases, but anything more, it's a giant pain.
I wish we had something built in without resorting to custom components or hacs integrations that allows us to do native scripting with another type of template that can properly manage data, data types and variables without jumping through hoops.

What I mean:
native scripting - directly in scripts and automations
another type of template - or script block, using python or lua or heck even elixir
hoops - without having multiple lines of if else endif, and piping things through filters and using namespaces or dynamic dicts or creating an entire custom component to do what I need

That's all. Have a nice day all.

Edit: make things clear to myself.

cinder lotus
#

Found this as part of 'a project' that I had to put it in configuration.yaml

    sensors:
      lights_on:
        friendly_name: "Lights On"
        value_template: >
          {{ states.light | selectattr('state', 'eq', 'on')
          | map(attribute='entity_id')
          | list | count }}```
In my ``configuration.yaml`` I have ``template: !include template.yaml``so in this template.yaml file I added:
```  - sensor:
    - name: lights_on
      value_template: >
        {{ states.light | selectattr('state', 'eq', 'on')
        | map(attribute='entity_id')
        | list | count }}```
Restarted HA but no sensor.lights_on when using dev tools
fickle sand
marble jackal
#

BTW there is no need to map it to entity_id if you are only going to count it

cinder lotus
#

So my final template is:

   - sensor:
    - name: lights_on
      state: >
        {{ states.light | selectattr('state', 'eq', 'on')
        | map(attribute='entity_id')
        | list | count }}```
It counts all the lights. I also made some grouprs I'd llike to exclude for this template.
Any help would be appreciated how to exclude for example ``lights.all_lights``
cinder lotus
cinder lotus
#

stupid question: do I have to replace something in the code by my entity_id. I I think it's now unique_id for a group instead of entity_id?

turbid mural
#

Hi, I want to write a value from an input_text. to another input_text.

data:
  value: "test"

does work, but

data:
  value: "{{ states(input_text.stored_value) }}"

does not.
What am I missing?

cinder lotus
#

Initial state is:

        {{ states.light | selectattr('state', 'eq', 'on')
        | map(attribute='entity_id')
        | list | count }}```
I changed to
```state: "{{ states.light | selectattr('state', 'eq', 'on') 
        | rejectattr('attributes.entity_id', 'defined') 
        | list | count }}"```
and
```state: "{{ states.light | selectattr('state', 'eq', 'on') 
        | rejectattr('attributes.alle_lampen', 'defined') 
        | list | count }}"```
but in both last examples the template becomes 'unavailable'
marsh cairn
lyric comet
#

Go back to the first format with the > and no quotes and just add in the reject.

turbid mural
marsh cairn
#

So you haven't created an input text helper named stored_value

obtuse zephyr
#

It needs to be quoted {{ states('input_text.stored_value') }}

turbid mural
terse slate
#

hi guys, i added a simple switch template in my configuration.yaml file. i then renamed it. now i see both switch-templates in my entities, even though the first one doesnt exist in the configuration.yaml anymore. why is this? i have restarted ha multiple times

marble jackal
terse slate
#

is there a way i can put all the code for my different switches in a separate yaml file? so my configuration.yaml doesnt get so packed?

inner mesa
#

Yes, with !include

#

You probably already have examples in your config

turbid mural
#

I don't know where to put this, but it ist Templates related, hence I'll try it here.
Running this line in dev tools does produce the correct link.

https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/{{ states('input_text.coords') }}?include=fcst%2Cobs%2Chistfcst%2Cstats%2Chours&key=<my_api_key>&lang=de&unitGroup=metric&options=beta&contentType=json

but I cannot store this in another input_text (though' the result is only 249 characters long), nor use this as a resource in

rest:
  - scan_interval: 300
    resource:

Any ideas how to narrow the problem down? (Or how to make it work even?)

turbid mural
#

oh, pasting the final link into the rest part does work. It's only the dynamic thing that doesn't

lyric comet
#

You need to use resource_template if you want to use templates.

turbid mural
#

@inner mesa @lyric comet Reading the documentation thoroughly actually DOES help 😅 That was an unexpected distinction. Thanks again!

loud ridge
#

I'm sure this is simpler than I'm making it. I want to display an icon of my choosing for the state that I set on some "thing". I assume I need to define a helper toggle as my thing. Then make a template that monitors the toggle state and displays an icon based on the state. But all the template examples are using some physical device.

#

That is display an icon in a dashboard.

lyric comet
#

If you just want it for the dashboard, you could simply use a Mushroom template card and template the icon.

loud ridge
lyric comet
#

You could define an Input_boolean helper, then just override the icon on the desktop, or define a template switch from scratch in Yaml

terse slate
#

can i only use the !include command in the configuration.yaml for 1 "type" of code, for example scripts? i cant for example put all the different code for 1 product, like switchbot in one separate yaml file and then include it?

inner mesa
#

That's called a package

plain magnetBOT
#

To enable packages, add packages: !include_dir_named packages to your configuration.yaml so that it looks similar to this:

homeassistant:
  ...
  packages: !include_dir_named packages

Important: The packages: line must be nested under homeassistant:!

For more information on packages, please refer to the packages docs: https://home-assistant.io/docs/configuration/packages/

terse slate
spice linden
#

I am trying to create a template that will show battery powered entities that state < 31.
I've created a group and an input number
the following it doesn't return an error, neither correct results.

{{ expand('group.zigbee_nodes_battery')
| rejectattr('state', 'in', ['unavailable','unknown'])
| selectattr('state', '<', states('input_number.zigbee_low_battery_threshold'))
| map(attribute='entity_id')
| list | join('\n')
}}

What am doing wrong?

loud ridge
inner mesa
#

All states are strings. Unfortunately it's not possible to do what you want without a for loop

lyric comet
loud ridge
spice linden
round coral
#

Question, is there anyway to get a list of services that's tied to a notification group?

I have tried expand(), but that returns an empty list. I'm assuming that's because it's a list of services rather than entities.

inner mesa
#

I don't think so

round coral
summer arch
#

How do you make a template sensor with the timestamp device class

#
- trigger:
  - platform: state
    entity_id:
      - vacuum.sl60d
    to: cleaning
    for:
      minutes: 5

  sensor:
    - name: "Vacuum Last Clean"
      state: "{{ now() }}"
      device_class: timestamp
      icon: mdi:broom
marble jackal
#

Don't see an issue with that one

summer arch
#

ValueError: Invalid datetime: sensor.vacuum_last_clean has timestamp device class but provides state 2024-01-21 16:32:33.708601+10:00:<class 'str'> resulting in ''str' object has no attribute 'tzinfo''

#

sorry, didnt realise I didn't hit enter

#

This is the error in logs

plain magnetBOT
#

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

marble jackal
#

Does it work with "{{ now().isoformat() }}"

summer arch
#

No, same error I tried that one a while ago when I came across a forum post.

I have also tried as date time and as timestamp even

marble jackal
#

@summer arch Just did a quick test on my system (2024.1.5) an this is working for me:

- trigger:
    - platform: state
      entity_id: input_boolean.test
      to: "on"
      for:
        seconds: 2
  sensor:
    - unique_id: 2351e548-664a-4850-8c58-979d0fbf9e0f
      name: "Test 123"
      state: "{{ now() }}"
      device_class: timestamp
summer arch
#
- trigger:
  - platform: state
    entity_id: vacuum.sl60d
    to: cleaning
    for:
      minutes: 5

  sensor:
    - unique_id: vacuum_last_clean
      name: "Vacuum Last Clean"
      state: "{{ now() }}"
      device_class: timestamp
      icon: mdi:broom
#

This is more like yours now?

#

now its working....

#

what changed

marble jackal
#

You added a unique id

summer arch
#

nvm
This entity is no longer being provided by the template integration. If the entity is no longer in use, delete it in settings.

marble jackal
#

It probably created a _2 because you now added the unique id

summer arch
#

ValueError: Invalid datetime: sensor.vacuum_last_clean has timestamp device class but provides state 2024-01-21 16:32:33.708601+10:00:<class 'str'> resulting in ''str' object has no attribute 'tzinfo''

summer arch
marble jackal
#

I don't have a clue then. You have this under template: right?

#

The error indicates your datetime doesn't provide information about the timezone, but it does (+10:00)

summer arch
summer arch
#

it would suggest my state is a string and a string has no timexone info?

#

but as showed, yours works

#

I think I got it but it doesn't make sense (or at least it isn't reading as not supplied now)

#

and the -platform is double indent under -trigger?

#

but sensor is single indent

#

I indented -platform

#

2024-01-21T10:19:09+00:00

#

looks like it workd

marble jackal
#

I did notice that, but thought it wouldn't matter

#

Not sure what you mean with - platform: though, that's only used in the legacy format

marsh cairn
#

The trigger platform for templates

summer arch
#

yeah, platform for the trigger had to be double indented

#

so how do I make a template sensor with a triger then? cause docs still show that is the way (*see link)

marble jackal
#

Oh yes

#

You were just not using the same indentation for the trigger configuration and the sensor configuration

floral shuttle
#

using a template on an entities state in an automation to create an entry in calendar:```
- service: calendar.create_event
target:
entity_id: calendar.afvalwijzer
data:
summary: >
{{trigger.to_state.attributes.friendly_name}}
start_date: >
{{trigger.to_state.state}}
end_date: >
{{trigger.to_state.state}}

#

are there other considerations here, or cant we use a template like this at all?

#

nvm. this is it:Expected minimum event duration of 0:00:01 (2024-01-28, 2024-01-28).

plain magnetBOT
#

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

lucid thicket
#

@twilit kettle

#automations-archived message
You can play around with this is the template editor (developer tools -> template):

{{ expand('binary_sensor.group_fenster_und_turen') | selectattr('state', 'eq', 'on') | map(attribute='name') | join(', ') }}
lyric comet
floral shuttle
#

this works for the calendar.....:```
start_date: >
{{trigger.to_state.state}}
end_date: >
{{as_timestamp(as_datetime(trigger.to_state.state) +
timedelta(days=1))|timestamp_custom('%Y-%m-%d') }}

turbid mural
floral shuttle
#

or this, which still is a terrible template for indicating an event:```
action:
- variables:
date: >
{{trigger.to_state.state}}
- service: calendar.create_event
target:
entity_id: calendar.afvalwijzer
data:
summary: >
{{trigger.to_state.attributes.friendly_name}}
start_date: >
{{date}}
end_date: >
{{(as_datetime(date)+ timedelta(days=1))
|as_timestamp|timestamp_custom('%Y-%m-%d')}}

plain magnetBOT
#

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

hybrid halo
#

Sorry I found a bug!

marsh cairn
slow vine
#

is this how to run a shell_command with passing args to the command?

shell_command:
  manage: '/config/scripts/manage.py "{{ args }}"'

I think it not working but I'm not sure how to debug the output. I tried using a script but i get errors tthere too.

#
    sequence:
      - service: shell_command.manage
        data:
          args: "--help"
          response_variable: manage_response
      - service: persistent_notification.create
        data:
          title: "card info:"
          notification_id: "manage_response"
          message: "{{manage_response['stdout'] }}"
lyric comet
#

What do the values in the script trace show?

floral shuttle
#

no matter what I try, I cant get a working default for this template secondary: > {% set event = state_attr(config.entity,'datum')|as_datetime|as_local %} {{state_attr(config.entity,'type')}}: {{event.strftime('%d-%m-%Y')}} on the set event. those state_attr(config.entity,'datum') have the '1956-09-12 00:00:00+01:00' form

#

but on restart (and when on that particular view, the templates in that view sometimes throw: 'TypeError: float() argument must be a string or a real number, not 'NoneType''

inner mesa
#

It's probably being evaluated before the integration is set up

#

I would use now() if state_attr(xxx) is not defined else yyy or check against None

slow vine
# lyric comet What do the values in the script trace show?

Sorry I had to run out.
In developer tools I looked and it seems like the script is not receiving the args properly. it is saying error: unrecognized arguments: --info 123456 when in the actual cli it works
developer tools: service, shell_command

marble jackal
#

It's caused by applying datetime before the integration for config.entry is ready

#

You could do this

floral shuttle
#

its probably caused by the final use of the 'event' in {{event.strftime('%d-%m-%Y')}} ?

inner mesa
#

No

marble jackal
#

No

#

It's caused in the step where you set the variable

inner mesa
#

I also made a suggestion

floral shuttle
#

yep let me try that

marble jackal
#

I have a PR open to add the default parameter to as_datetime

inner mesa
#

It's a dumb error right now

floral shuttle
#

confirm the default(0,true) to fix it... I had tried |default(0), but missed the true

marble jackal
#

I initially made the PR so it would always either return a datetime object or None (when no default was provided) but that was not accepted

sick ice
#

I'm using this across a few automations to prevent weird things happening with successive triggers:
{{ (now() - state_attr('automation.sync_living_and_dining_lights_brightness','last_triggered')).total_seconds() > 1 }}

Is there a way to replace the automation.xyz part with a reference to 'this automation' so I can easily use this as a copy/paste?

inner mesa
#

seems like you could just add a delay at the end of the automation if you're trying to prevent rapid successive triggers

#

I just ran a quick test:

- id: test_trigger
  alias: test_trigger
  trigger:
    - platform: event
      event_type: foobar
  action:
    - service: persistent_notification.create
      data:
        message: "{{ this }}"
#

output was:

{'entity_id': 'automation.test_trigger', 'state': 'on', 'attributes': {'id': 'test_trigger', 'last_triggered': None, 'mode': 'single', 'current': 0, 'friendly_name': 'test_trigger'}, 'last_changed': '2024-01-21T23:31:02.185737+00:00', 'last_updated': '2024-01-21T23:31:02.185737+00:00', 'context': {'id': '01HMQ5SYX9NC69CWW1H68MDRC3', 'parent_id': None, 'user_id': None}}
#

so... {{ this.entity_id }}

sick ice
#

the delay method creates more annoyance that it solves I think. Much prefer this.

inner mesa
#

Note that this.last_triggered is exactly the same

#

See the output above. It's a state object

sick ice
#

sorry not sure I follow that last part. exactly the same as what?

inner mesa
#

Actually, it's this.attributes.last_triggered

#

As your state_attr() call

#

See my experiment. Run your own

sick ice
sick ice
keen crypt
#

can someone help before i lose my sanity here? i cannot figure out where the syntax error is
`template:

  • sensor:
    name: hvac_main_binary
    state: >
    {{ (states('sensor.emporiavue2_circuit_4_power') > int 100) | iif('true', 'false') }}`

Invalid config for 'template' at configuration.yaml, line 138: invalid template (TemplateSyntaxError: expected token ')', got 'integer') for dictionary value 'sensor->0->state', got None

inner mesa
#

States are strings

fickle sand
#
state: >
  {{ states('sensor.emporiavue2_circuit_4_power') | int > 100 }}
inner mesa
#

You put '> int 100', which is nonsense

keen crypt
#

oh duhhh!! that sensor in particular should be an integer value though

inner mesa
#

That's better

#

What you're doing with 'true' and 'false' doesn't make sense

#

Just make a binary_sensor and return the test

keen crypt
#

thats what this is for - a part of history_stats tracker.
- platform: history_stats name: Main HVAC today entity_id: binary_sensor.hvac_main_binary state: True type: time start: "{{ today_at() }}" end: "{{ now() }}"

#

i think i'm over complicating this in my head

fickle sand
#

But the entity resulting from your posted code will be sensor.hvac_main_binary not binary_sensor.hvac_main_binary

keen crypt
#

yea i just saw that - ive not gotten that far yet

inner mesa
#

And string a string of true or false, which is weird and unnecessary

fickle sand
#

For that you will need:

- binary_sensor:
    - name:
      ...
keen crypt
#

got it - thanks guys

rocky crypt
#

Hey there. I am trying to get a sensor created from a JSON file located through a website. I have to authenticate with a token I have so, I know authentication needs to be "bearer". I have this, but don't think it's correct :(. Can anyone assist on the correct method of doing this? I am wanting the token to pull from my secrets.yaml file as well.

sensor:
  - platform: rest
    resource: "https://mywebsite.com/test.json"
    headers:
      Authorization: >
        Bearer !secret test_token
    value_template: '{{ value_json.TestData[0].TestLevel }}'
    name: My Test Sensor
keen heath
#

Hi, any that can assist,

#
# MQTT Generator
mqtt:
  sensor:
    - name: "Main L1 Watts"
      state_topic: "32841/6D2B9ABBCB"
      unit_of_measurement: "W"
      value_template: "{{ value_json.R060 }}"
    - name: "Generator_L3_watts"
      state_topic: "32841/6D2B9ABBCB/Generator_L3_watts"
      unit_of_measurement: "W"
      value_template: "{{ value_json.32841/6D2B9ABBCB/Generator_L3_watts }}"
#

i'm not winning

#

this from the broker

plain magnetBOT
#

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

lyric comet
#

I am not sure why you are doing what you are doing neither of those statements look correct.
To start with try putting all the json attributes in the attributes and the samples you posted don't even match the message you are trying to read.

Something like

  - name: "battery_volts"
    state_topic: "32841/6D2B9ABBCB/Engin_battery_volts"
    value_template: >
       {{ value_json.6D2B9ABBCB.P004.R005 }}
    json_attributes_topic: "32841/6D2B9ABBCB/Engin_battery_volts"    

might work, but I am no expert.

#

If not set the value template to a static value until you can easily see the attributes and workout the correct extraction.

mighty ledge
#

what does the P0## represent?

keen heath
#

my topic that I load the DSE

#

%TYPE%/%UID%/Oil_pressure

mighty ledge
#

So what is R060 and P004 mean?

#

Your response doesn't seem like it answers my question.

#

The topic you show is 32841/6D2B9ABBCB/Generator_L-N, where the data is

{
    "6D2B9ABBCB": {
        "P004": {
            "R008": 2326,
            "R010": 2322,
            "R012": 2328
        }
    }
}
#

so in regards to JUST THAT information, what does P004, and R008, R010, and R012 represent? @keen heath

keen heath
#

I think the P004 is maybe the gateway, as it not changing but the R008 is like voltage so L-1 to Nutral is volt

mighty ledge
#

ok, and what about the other R data?

#

The template needs to know what to do, right now the R keys are not static, therefore a static template will not do the job

#

until you can answer the question about R, there's nothing we can do to help

floral shuttle
#

while {{states(trash)}} outputs ' 2024-02-02' (and the entity is a device_class: timestamp, how come the {% from 'easy_time.jinja' import month %} {{month(trash)}} (or states(trash) ) for that matter outputs the current month januari?

#

is trash in the wrong format for that macro?

mighty ledge
#

@keen heath at most I can tell you that your template will most likely look something like this, however the ... inside the {{ }} will be replaced with information that grabs from the proper R data>

    - name: ???
      state_topic: "32841/6D2B9ABBCB/Generator_L-N"
      unit_of_measurement: "W"
      value_template: "{{ value_json['6D2B9ABBCB'].P004... }}"
mighty ledge
#

month(1) would be january, if you provide bad data, it defaults to the current month

floral shuttle
#

o in that case I did 😉 (provide bad data....)

#

{{month(as_datetime(states(trash)).month)}}

mighty ledge
#

Yep was just going to say that

floral shuttle
#

cool, thx

mighty ledge
#

@keen heath can you provide a link to the documentation on your device that covers the MQTT responses?

floral shuttle
#

would you be interested in adding some functionality to that so we can simply drop in a timestamp and easy_time calculates the month?

mighty ledge
#

You can add a issue as a FR

floral shuttle
#

sure, will do. thx for considering

humble mortar
#

What could I use to make tts spit to this url?

http://wirepodIP:8080/api-sdk/assume_behavior_control?priority=high&serial=##000000
http://wirepodIP:8080/api-sdk/say_text?text=" + "Your family room lights are off etc" + "&serial=##000000
http://wirepodIP:8080/api-sdk/release_behavior_control?priority=high&serial=##000000

I would like so I can just call this some way and then it would work kind of like the media player and template in the text field there
The first line grabs control of the device the second takes the text input the third releases control of the device.

example:

service: notify.alexa_media_robot_vector
data:
  message: Your family room lights are off
mighty ledge
#

Sorry, I don't offer support outside these channels

keen heath
#

can I we transfer the doc

keen heath
hybrid halo
#

Hi! They have the following sensors and I would need a template for a new sensor with a name sun_opacity:```
Cloud coverage = sensor.cloud_coverage
PIR-Lx = sensor.pir_je_illuminance_lux
UV-index = sensor.weatherapi_dom_uv_index

mighty ledge
#

Can you just provide a link to the documentation? Or the unit that you have? I'm not sure why you need to email me the doc

keen heath
#

as the DSE send me the documents

mighty ledge
#

How large is it?

hybrid halo
mighty ledge
#

then make a sensor group w/ average as your selected option

#

no templates needed.

keen heath
#

3 Mb

hybrid halo
mighty ledge
#

0% of the things your'e asking for require code

#

Everything can be done via the UI

keen heath
#

I find the copy of the DSE

#

can I send the link?

mighty ledge
#

post the link here

hybrid halo
keen heath
#

see page 74

mighty ledge
#

Wow, you're going to have to use that document to figure out what each register means

#

you basically have to reverse engineer the entire response as if it were modbus, which is no easy feat

#

at the bottom of page 81, it describes what P and R are

#

Those are unsigned integers that represent the data.

#

Typically, an API like this requires a full blown integration

#

You can probably do it in value_template, but it's going to be challenging

keen heath
#

I have the topic file loaded

#

an it is loaded in to the gateway

mighty ledge
#

You aren't understanding what I'm saying

#

The manual covers the data that's coming out of the device, as a modbus protocol

keen heath
#

yes

#

ok

mighty ledge
#

Ok, so do you know what each register means and what it does?

keen heath
#

yes

mighty ledge
#

Do you know how to convert the information from the register to your real life value?

keen heath
#

ps: I'm in IT, not a dev

#

and Elect

mighty ledge
#

if you don't, then you need to figure that out. Simply getting the information from a single register will be

    - name: P004 R036
      state_topic: "32841/6D2B9ABBCB/Generator_L-N"
      value_template: "{{ value_json['6D2B9ABBCB'].P004.R036 }}"
mighty ledge
mighty ledge
#

and even then, if the register isn't supplied, it will error

#
    - name: P004 R036
      state_topic: "32841/6D2B9ABBCB/Generator_L-N"
      value_template: "{{ value_json['6D2B9ABBCB'].P004.get('R036') }}"
#

that will not error, but your sensor will go unavailable whenever the register isn't supplied in the data

#
    - name: P004 R036
      state_topic: "32841/6D2B9ABBCB/Generator_L-N"
      value_template: "{{ value_json['6D2B9ABBCB'].P004.get('R036', 0) }}"
#

that will not error and supply 0 when the register isn't supplied in the data

#

Again, that will only get you the unsigned integer from the register

#

You still need to know what each register represents, and how to conver said register to your real life value. All of which, may be supplied in that documentation, but probably depends on how it's wired/setup.

keen heath
#

thank you

#

it works,

#

just need to fix the decimal

#

can I post pic?

mighty ledge
#

add a unique_id, then adjust the precision via the UI

keen heath
#

need to add a . to the value.

#

reading is 4523 but its 4.523w

mighty ledge
#

Divide it by 1000

#

I can give you an example when I get back to my desk

keen heath
#

thank you

mighty ledge
#
    - name: P004 R036
      unique_id: something_unique_to_all_mqtt_entries_you_add
      state_topic: "32841/6D2B9ABBCB/Generator_L-N"
      value_template: "{{ value_json['6D2B9ABBCB'].P004.get('R036', 0) / 1000 }}"
keen heath
#

thank you.

#

if a line has more value

#

value_template: "{{ value_json['6D2B9ABBCB'].P004.get('R008', 0)('R010', 0)('R012', 0) }}"

#

is that correct

mighty ledge
#

no

#

you'll have to get each one separately

keen heath
#

ok

#

if a value is - 2 is not showing

mighty ledge
#

I don't know what that means

humble mortar
#

Dump TTS messages to device

keen heath
#

so my main get power for solar so it go in to the - watt as we push back to the grid

keen heath
#

@mighty ledge Thank you for all the support. I really really thankful for the support. Next step Victron intergration

languid pendant
#

hey everyone! I'm having trouble achieving the look I want in the entities card. Here's the picture https://ibb.co/wzLcFcF and here is the code https://pastebin.com/6SbY3UKv. I've read through the entities card tutorial on HA website but can't wrap my head around the function that I need... Any help would be greatly appreciated!

languid pendant
#

so sorry, thx!

quiet shell
#

I'm trying to avoid writing a bunch of if/else blocks in an automation, so I figured a Jinja template would be a nice way to ease some of that, but I'm having a problem getting the template to render for every automation run. Here's a simple example, what am I doing wrong? Do I need to move it somewhere else, or take a different approach?

- service: light.turn_on
  metadata: {}
  data:
    brightness_pct: "{{ 75 if states('sun.sun') == "above_horizon" else 20 }}"
  target:
    device_id: e126710010c6ba52093b7d8525c2615d
inner mesa
#

what do you mean by:

I'm having a problem getting the template to render for every automation run

#

it works sometimes?

quiet shell
#

(boo, doesn't look like I can upload a gif directly here 😦 )

#

When I put the jinja string in there, the left of the editor turns red.

#

It sort of feels like I need to put the jinja template string somewhere else maybe?

inner mesa
#

please use something like imgur

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.

inner mesa
#

but I don't see anything wrong with that

#

it may just be telling you that it doesn't support templates in the UI editor and you need to use YAML

#

you can try it in devtools -> Services

quiet shell
#

Service YAML contains syntax errors, please fix the syntax

#

shakes fist.

#

Nothing obvious is jumping out at me.

marsh cairn
#

Maybe removing the metadata: {} part?

vast juniper
#

Hey all👋

Need help with a Home Assistant template to show if there is any tomorrow's local calendar events. Any tips or templates to share?

quiet shell
#

@marsh cairn Nope, I don't think that's it. I'm having the same problem doing this directly in Dev Tools -> States, and in that block I'm not using metadata.

#

Here's what I'm seeing in Dev Tools. You can very clearly see that using 75 and 20 for values directly just works, but the jinja template string is the problem: https://imgur.com/a/vM0xruM

#

I feel like this should just work.

#

I got a bit more context by editing the automations.yaml file directly: YAMLSyntaxError: All collection items must start at the same column. YAMLSemanticError: Implicit map keys need to be followed by map values.

#

And: cannot read implicit mapping pair; a colon is missed

marsh cairn
quiet shell
#

Woah! It suuure does!

#

@marsh cairn Thank you sir!

inner mesa
#

that should definitely not be necessary

#

oh, duh. you were using " both inside and out

#
- service: light.turn_on
  metadata: {}
  data:
    brightness_pct: "{{ 75 if states('sun.sun') == 'above_horizon' else 20 }}"
  target:
    device_id: e126710010c6ba52093b7d8525c2615d
#

would be fine

marsh cairn
#

Quotes... I should pay more attention to those too 😅

quiet shell
#

Blaaaaah!

#

Whelp, I feel dumb. Thanks y'all! That's one mistake I'll never make again 😛

inner mesa
#

it's an easy one to make

#

I mean, it even got by Jorg 🙂

quiet shell
#

Haha, true. But I know I'll never git bit byte it again

humble mortar
#

(I may be templating it wrong or maybe you can't template there?)

lucid thicket
humble mortar
lucid thicket
#

Are you referring to this template:

  say_text:
    url: 'http://10.0.0.111:8080/api-sdk/say_text?text={{ states("input_text.your_text") }}&serial=00######'

?

humble mortar
#

Yes

#

If I change that to

  say_text:
    url: 'http://10.0.0.111:8080/api-sdk/say_text?text="test 1 2 3"&serial=00######'

It works fine he says "Test 1 2 3"

lucid thicket
#

Do you have an input text helper with an entity _id of input_text.your_text?

humble mortar
#

nope just created one will test again.

lucid thicket
#

That template will provide the state of that input helper. I would suggest you create an input text helper and populate it with some text to it

inner mesa
#

What...did you think would happen? 🙂

humble mortar
#

Hmm still said unknown

lucid thicket
#

What is the name of your input helper?

humble mortar
#

I'll try putting some static text in it

humble mortar
lucid thicket
humble mortar
#

hmm

lucid thicket
#

Input text helpers hold plain text

humble mortar
#

input_text.your_text

#

Ok so if I manually enter stuff in that box and hit enter then trigger it Vector says what's in that box

#

When I opened the door he said Test 1 2 3

#

but the automation doesn't seem to dump text in there and then say it...

lucid thicket
#

Maybe we need to go back to what you’re trying to do.

humble mortar
#
      - service: rest_command.say_text
        data:
          your_text: 'Your family room lights are off etc'
#

does that need to be text_input.your_text

lucid thicket
#

No

#

You have a couple ways you can do this

#

Then you would just need to call the service rest_command.say_text and you don’t need to provide data because you put the text into the input text helper

#

The other method is to ditch the input text helper and have the automation provide the text and you re-write the template to use that text

plain magnetBOT
#

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

lucid thicket
#

First you need to change the template to expect a variable. Let’s call it your_text

  say_text:
    url: 'http://10.0.0.111:8080/api-sdk/say_text?text={{ your_text }}&serial=00######'
humble mortar
#

done

lucid thicket
#

Then you can revert the service call back to what you originally had, where it was providing the your_text variable to the service:

      - service: rest_command.say_text
        data:
          your_text: 'Your family room lights are off etc'
humble mortar
#

Working thank you for your help!

#

There's so many examples in the forums of people trying to template a URL and at the end either nobody answers them or they say something like GOT IT... and don't show how it was done 😄 most of them gave up on rest and switched to curl'n a URL with shell_command 😖

lucid thicket
#

Templating a url is just templating any string. Most people template strings for notifications, so a good google phrase is “home assistant template notification”

worthy cairn
#

Anyone know why I'm getting this error in setting up a Template Sensor for Airgradient (ESPHome)?
Sensor None has device class 'aqi', state class 'measurement' unit 'None' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'template: - sensor: - name: "AQI (pm2.5)" state: >- 4 unit_of_measurement: AQI device_class: aqi' (<class 'str'>)

humble mortar
lucid thicket
lucid thicket
humble mortar
#

Oh ok I thought you were saying to convert the automation into a notification

lucid thicket
#

No, sorry for the confusion. Normally people are trying to template strings for a purpose different from what you are trying to achieve. But the method to achieve a string as a result is the same

worthy cairn
humble mortar
#

How would I get the templated automation to be used like a notification?

So I could just go into my other notification group and dump this unit into it as well?

- name: ALL_DEVICES
  platform: group
  services:
    - service: mobile_app_1
    - service: mobile_app_iphone
    - service: mobile_app_android
    - service: mobile_app_iphone2
    - service: alexa_media_vector
    - service: desktop_1
    - service: desktop_2
    - service: robot_vector #<= add it like this

example

service: notify.ALL_DEVICES
data:
  message: Your family room lights are off
lucid thicket
#

Do you have one or are you asking how to create one?

humble mortar
#

Would that be a helper?

#

I don't have one I am asking.

lucid thicket
#

Though I am looking and I don’t see that you can template the resource

humble mortar
#

Can it call an automation ie the one we made and just dump text to it?

lucid thicket
humble mortar
#

Ok will try that just thought it would be difficult to explain this all over again to someone unaware of what I was doing already.

heavy crown
#

Hi, can anyone help me with getting the result of a service call into the attributes of a template sensor. I am trying to enhance the opensky integration with a service call but have no clue to actually get the data 'out' 🙂

#

I would also like to use it in a card, e.g. map card could then show the flights based on the position

#

Any example would probably alreayd help me investigating in the right direction

marble jackal
#

Enhancing an integration with a Service call sounds more like a #developers thing

heavy crown
#

i.e. the service would kick back a dict. The current integration (my enh.) will be adding that to a sensor (the 'opensky' sensor) but I alo want to use this in a different way...if possible

marble jackal
heavy crown
marble jackal
#

correct

heavy crown
#

thx

floral shuttle
mighty ledge
floral shuttle
#

aargh, i was loking for the wrong info... apologies for that

#

and then I bumped into that big video and couldnt think straight anymore

grizzled grove
#

I'm trying to add a js to a custom card.
To return the attr I have to write:
````${states["sensor.test"].attributes.xxxx}```
But what if I want to return the state itself?

inner mesa
grizzled grove
#

If I use:
${states["sensor.test"]}
It returns [object Object].

inner mesa
quasi gulch
#

How can I get a list of all the automations based on a certain blueprint

marble jackal
#

There's no attribute or any other indication that an automation is created based on a blueprint. So this is not possible using templates

keen heath
#

Hello. I have two solar cards but I want to calc them together as one?

sonic sand
#

Hey!
I'm trying to create a template [on action tab] that will raise +1 degree temperature to the ac device.

 service: climate.set_temperature
  data_template:
    entity_id: climate.bedroom
    target_temp_low: {{ (state_attr('climate.bedroom', 'current_temperature')|round(0)) + 1 }}

What am I doing wrong?

marble jackal
#

current_temperature is the measured temperature, not the temperature it is set to

#

You should also wrap your template in quotes

#

And date_template is depreciated for years already, you can just use data

sonic sand
marsh cairn
#

My guess would be temperature

sonic sand
#
 service: climate.set_temperature
  data:
    entity_id: climate.bedroom
    target_temp_low: {{ "(state_attr('climate.bedroom', 'temperature')|round(0))" + 1 }}

quotes like that? or even after the + 1 at the end?

marsh cairn
#

Around the curly brackets, not within

sonic sand
#
 service: climate.set_temperature
  data:
    entity_id: climate.bedroom
    target_temp_low: "{{ (state_attr('climate.bedroom', 'temperature')|round(0)) + 1 }}"
#

that should do it?
EDIT:

Error running action
some but not all values in the same group of inclusion 'temperature' @ data[<temperature>]. Got None
humble mortar
sonic sand
#

well in devtools i'm getting this error

ValueError: Template error: round got invalid input 'None' when rendering template '{{ (state_attr('climate.bedroom', 'temperature')|round(0)) + 1 }}' but no default was specified
marsh cairn
#

Your temperature attribute seems not to be numerical

sonic sand
marsh cairn
#

What does {{ state_attr('climate.bedroom', 'temperature') }} say in the dev tools?

sonic sand
marsh cairn
#

climate.bedroom_ac ?

sonic sand
#

yeah, got few climate entities

marsh cairn
#

And what does climate.bedroom say?

sonic sand
#

null

marsh cairn
#

That's your problem

sonic sand
#

but it doesn't matter, when I try the string

service: climate.set_temperature
data:
  entity_id: climate.bedroom_ac
  target_temp_low: "{{ (state_attr('climate.bedroom_ac', 'temperature')|round(0)) + 1 }}"

it gives an error.

#

i'm trying to make it work on the entity that showing 27 in dev tools first, then i will try to solve the other climate device

#
Error running action
some but not all values in the same group of inclusion 'temperature' @ data[<temperature>]. Got None
marsh cairn
#

I would go with something like this:
{{ state_attr('climate.bedroom', 'temperature')|int(7) + 1 }}
If the attribute isn't numerical it defaults to the minimal value of your climate entity - aka setting it to 8 degrees

#

If other climate entities have another min_temp, you have to adjust that.

sonic sand
#

in devtools it's showing 28 btw

marsh cairn
#

Or set it to a default value -1 you prefer.

sonic sand
#

still not working.. there is something wrong

marsh cairn
#

Does this work?

service: climate.set_temperature
data: |
  {{ {'target_temp_low': (state_attr('climate.bedroom', 'temperature')|int(7) + 1)} }}
target:
  entity_id: climate.bedroom
sonic sand
#

let me check

#
Error running action
some but not all values in the same group of inclusion 'temperature' @ data[<temperature>]. Got None

nope

marsh cairn
#

And this?

service: climate.set_temperature
data:
  target_temp_low: "{{ state_attr('climate.bedroom', 'temperature')|int(7) + 1 }}"
  target_temp_high: 30
target:
  entity_id: climate.bedroom
sonic sand
#

I'm using sensibo if it's matter

marsh cairn
#

Does the climate entity bedroom have a high and low setting or does that one just use a single target temperature?

sonic sand
#

just one I think

humble mortar
#

Added this when I run the automation it reads the template name instead of what I put in message of the automation he says "vectortext"

configuration.yaml

command_line:
  - notify:
      name: vectortts
      command: "curl -X POST -H 'Authorization: Bearer LongLiveToken' -H 'Content-Type: application/json' -d '{\"message\": \"{{ vectortext }}\"}' http://HAIP:8123/api/services/script/vector_speech"

automation

service: notify.vectortts
data:
  message: test
marsh cairn
marsh cairn
humble mortar
#

What should it look like?

#

I tried like 10 different combinations of quotes and no quotes all over the place without success.

#

The line above was the only one that actually let it load the configuration without failure.

marsh cairn
#

What happens, if you are using the following service call?

data:
  vectortext: test```
marble jackal
marble jackal
#

And the HVAC mode should be heat_cool

#

I think

humble mortar
marsh cairn
#

I forgot it's a notifyer, not a script facepalm

sonic sand
#

in addition the the low and high?

marsh cairn
marble jackal
#

I would use the multi line notation so the double quotes are not needed

sonic sand
#
service: climate.set_temperature
data:
  target_temp_low: "{{ state_attr('climate.bedroom_ac', 'temperature')|int(7) + 1 }}"
  target_temp_high: 30
  hvac_mode: heat_cool
target:
  entity_id: climate.bedroom_ac

like that?

humble mortar
marble jackal
#
command_line:
  - notify:
      name: vectortts
      command: >
        curl -X POST -H 'Authorization: Bearer LongLiveToken' -H 'Content-Type: application/json' -d '{"message": {{ vectortext }} }' http://HAIP:8123/api/services/script/vector_speech
#

And I don't think you need the quotes around the template

humble mortar
#

After doing that he no longer says anything no errors

sonic sand
#

the hvac_mode method did not changed anything. still error.

fickle sand
#

So you didn't, please read it carefully

#

As that would look like this

service: climate.set_temperature
data:
  temperature: "{{ state_attr('climate.bedroom_ac', 'temperature')|int(7) + 1 }}"
target:
  entity_id: climate.bedroom_ac
sonic sand
#

Thanks man

#

and to lower by 1 degree i should just change the + to - ?

#

I am making a remote to that ac

fickle sand
#

Great that it works! he literally mentioned to change target_temp_low: for temperature:

sonic sand
#

Thanks Bas.

humble mortar
obtuse zephyr
humble mortar
#

There is a glitch in it that doesn't allow LongLiveToken to work so it just gets a 401 error.

obtuse zephyr
#

🤔 What kind of glitch

humble mortar
#

I tried it and got the same issue

#

Maybe you can see something I did wrong if that is not the state of it?
notify.yaml

- name: vector
  platform: rest
  resource: http://HAIP:8123/api/services/script/vector_speech
  method: POST_JSON
  headers:
    Authorization: !secret vector_llatoken
    Content-Type: application/json
#
Logger: homeassistant.components.rest.notify
Source: /usr/src/homeassistant/homeassistant/components/rest/notify.py:223
Integration: RESTful (documentation, issues)
First occurred: 12:31:49 AM (1 occurrences)
Last logged: 12:31:49 AM

Client error. Response 401: Unauthorized:
NoneType: None
obtuse zephyr
#

Why can't you just call the script directly?

humble mortar
#

I also tried to put Authorization: Bearer !secret vector_llatoken with no success same error.

#

I wanted the automation to identify as a notification so I can just dump it into notification groups that dump messages to it to say.

obtuse zephyr
#

What does the script do?

humble mortar
#

Just dumps text to a robot with a text to speech engine for him to say HA notifications. "Your garage door is open, etc"

#

The robot doesn't have json compatible url interface just straight args in a url

#

I was trying everything to work around that.

mighty ledge
humble mortar
#

Sorry can you show me an example of what that means?

mighty ledge
#

this is a dictionary

#
item:
  something: value
  something2: value
#

this is a list

#
item:
- something
- something2
humble mortar
#

Thank you so you just add the information with a dash and just the variable with no name?

mighty ledge
#

it should be a full string

#

you should see errors in your logs with your current configuration

humble mortar
#
- name: vector
  platform: rest
  resource: http://HAIP:8123/api/services/script/vector_speech
  method: POST_JSON
  headers:
  - "Authorization: !secret vector_llatoken"
  - "Content-Type: application/json"

Something like this?

mighty ledge
#

yes, but Authorization should be in your secret

#

and it should be listed as
- !secret ....

humble mortar
#

OK I will try that

mighty ledge
#

if that doesn't work, the docs are wrong and a map is acceptable. I haven't looked at the code, the docs could be wrong

#

I'm starting to think the docs are wrong

#

Yeah, they are just wrong, ffs

#

it's a map

#

or dict, what you had

humble mortar
#

How do you use a map?

mighty ledge
#

what you originally had

humble mortar
#

So it is b0rk then

obtuse zephyr
#

What's in !secret vector_llatoken

humble mortar
#

just the LongLiveToken from HA

obtuse zephyr
#

Prefix w/ Bearer

#

(space after Bearer)

humble mortar
#

Testing...

#

notify.yaml

- name: vector
  platform: rest
  resource: http://HAIP:8123/api/services/script/vector_speech
  method: POST_JSON
  headers:
    Authorization: !secret vector_llatoken
    Content-Type: application/json

secret.yaml

vector_llatoken: Bearer ####...
Error running action
Unknown error
obtuse zephyr
#

Hopefully more details in the log

mighty ledge
#

ffs, the docs are wrong for params and header in all of the rest documentation

#

The logs will have the actual error.

mighty ledge
#

I'm at work, otherwise I'd change it

#

it's not a PR you can do via the github website

#

If it is, I have no idea how to do it. Never dealt with a PR that touches multiple files from the website.

#

I have a fork on my desktop at home, if I remember, I'll update it

silent seal
#

Ahh yeah, needs a fork. But you can edit your fork in an editor on the website.

humble mortar
#

the log

obtuse zephyr
#

haip

#

I assume is not the name of your instance

humble mortar
#

good catch

#

Yay it worked!

#

Dies...

#

That was so much relentless mind mash

#

Thank you everyone!

humble mortar
lyric comet
#

Are you still pointing at the same Home Assistant instance you are trying to call into? Are you sure you can connect HA to its self on loopback?

plain magnetBOT
#

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