#templates-archived

1 messages · Page 31 of 1

mighty ledge
#

a dictionary, the key order does not matter

#

what I posted above will work

unique briar
#

element 0 of the list is the dict, so grab the dist and pull temp out of it

#

oh

#

that IS what you posted above

mighty ledge
#

yes

#

but keep in mind, I added another field

#
    json_attributes_path: '$.0'
#

you need that for attributes

#

to work

unique briar
#

wonderful, this works perfectly

#

thanks so much for your help, i'm going to go mail my computer science degree back to the school now, this seems very obvious now that you've explained it.

marble jackal
#

@mighty ledge I was looking at your post about finding the next dst, and I understand what you are doing
I was able to remove the need for the first macro

      {%- macro is_dst(t) %}
        {{- t.timetuple().tm_isdst != 0 }}
      {%- endmacro %}
      
      {%- macro finddst(t, kwarg, rng) %}
        {%- set ns = namespace(previous=is_dst(t), found=none) %}
        {%- for i in range(rng) %}
          {%- set ts = t + timedelta(**{kwarg:i}) %}
          {%- if ns.previous != is_dst(ts) and ns.found is none %}
            {%- set ns.found = i %}
          {%- endif %}
        {%- endfor %}
        {{- ns.found }}
      {%- endmacro %}
      
      {%- set t = now().replace(minute=0, second=0, microsecond=0) %}
      {%- set d = finddst(t, 'days', 366) | int - 1 %}
      {%- set h = finddst(t + timedelta(days=d), 'hours', 25) | int - 1 %}
      {%- set m = finddst(t + timedelta(days=d, hours=h), 'minutes', 61) | int %}
      {{ (t + timedelta(days=d, hours=h, minutes=m)).isoformat() }}
#

but I can't understand why you can't replace is_dst(t) and is_dst(ts) with (t.timetuple().tm_isdst != 0) and (ts.timetuple().tm_isdst != 0)

#

when I do that, it will give yesterday as next dst

mighty ledge
#

DST is really stupid btw

#

If I remember correctly, I had to jump through hoops for DST to work year round

#

as the check stopped working when DST changed

marble jackal
#

no, that's my version in which I removed the first macro

#

maybe that first macro is needed to let it work year round, as the DST starts end of this month over here

mighty ledge
#

yes pretty sure it was that

#

that's what I currently use

#

the tm_isdst does not work year round

#

it was something like that

#

whatever the problem was, it was annoying and I had to go back to the drawing board when DST changed because it messed up

#

but I don't think I tried the timetuple

#

so tha tmight be a way around that stupid macro that I wrote

marble jackal
#

does seem to work though

mighty ledge
#

it probably will over .dst()

marble jackal
#
      {%- set t = now().replace(minute=0, second=0, microsecond=0) %}
      {%- set d = finddst(t, 'days', 366) | int - 1 %}
      {%- set h = finddst(t + timedelta(days=d), 'hours', 25) | int - 1 %}
      {%- set m = finddst(t + timedelta(days=d, hours=h), 'minutes', 61) | int %}
      {% set t = (t + timedelta(days=d, hours=h, minutes=m)) + timedelta(days=1) %}

      {%- set d = finddst(t, 'days', 366) | int - 1 %}
      {%- set h = finddst(t + timedelta(days=d), 'hours', 25) | int - 1 %}
      {%- set m = finddst(t + timedelta(days=d, hours=h), 'minutes', 61) | int %}
      {{ (t + timedelta(days=d, hours=h, minutes=m)).isoformat() }}
#

I applied it 2 times like this

mighty ledge
#

well, just so you know, testing it with a timedelta isn't going to work

#

because time is oh-so-over-fucking-complicated

marble jackal
#

oh no, it doesn't work

#

Well, I was able to have it return march next year 🙂

mighty ledge
#

grabbing a date during DST actually changes the underlying datetime object when you're in DST vrs out of DST

#

and the only thing you can do is wait until DST is applied for you to check the code

marble jackal
#

Well, I can't get it to work anymore, so I believe you that all 3 macro's are needed to have it span years

#

🙂

#

and that time is oh-so-over-fucking-complicated 🙂

mighty ledge
#

It took some time to come up with it, and I remember I was annoyed with the outcome of my really long macros

marble jackal
#

yeah, I understand why you put it in a trigger based template sensor, you don't want this to run every minute

mighty ledge
#

yeah, it's super heavy

#

as a calc

#

we really just need a DST integration

#

I don't know how the code can be simplified tho

#

as DST is handled really oddly as a flag

#

I remember why i had to do the stupid for loop too

#

because some guys DST started at 1:05 instead of 2:00 like most of the world

#

so I had to search for the minute instead of the day

#

basically the code adds a time increment and notes when the DST offset changes. Then, when it finds it, it 'increases' the resolution until we get the exact second it changes

#

starts on days, then hours, then minutes, and I think seconds after that

#

oh, no, just minutes

silent vector
#

How would I dynamically either merge these 2 lists or only have - foo .
https://dpaste.org/Ur9oG

Essentially with Jinja how would I generate those 2 being combined to produce that output.

mighty ledge
#

that's a list of dictionaries

#

it's not easy to do

silent vector
#

But is it possible lol?

mighty ledge
#

yes

#

and only myself, thefes, or rob would probably be able to help

#

it's probably the most difficult thing to do in templates atm

#

so what do you expect the outcome to be of that merge?

#
santa:
- foo:
    name: test
  type: disk
  size: 100
  world: test

?

silent vector
#

Oh I worded it wrong

#

The output is what I put in dpaste

#

That would be the expected output.

#

If I want both lists of dicts

#

If I want only the

santa:
  - foo:
      name: 'test'
    type: 'disk'

For example that's another possible output

mighty ledge
#

oh, you want to filter out ones that only have the field foo?

#

@silent vector

silent vector
#

2 output possibilities.

santa:
  - foo:
      name: 'test'
    type: 'disk'

Or

santa:
  - foo:
      name: 'test'
    type: 'disk'
  - type: 'disk'
    size: '100'
    world: 'test'

I just don't know how to construct that dynamically with Jinja.

mighty ledge
#

YOu're going to need to explain the situation alittle better because constructing that information depends on the input information and what you currently have

#

I can write an example, but I can almost guarantee you won't know how to use it in your situation

#

espeically if the dictionaries themselves are dynamic w/ their keys

silent vector
#

I think I could figure it out once I see an example. Those are just arbitrary values in my examples but the inputs are static names and not dynamic.

mighty ledge
#
      {%- set ns = namespace(items={}, spool={}) %}
      {%- set fmat = "('{0}': {1})" %}
      {%- set items = (switches or []) + (lights or []) %}
      {%- for item in items %}
        {%- set state_obj = expand(item) | first | default(none) %}
        {%- if state_obj and state_obj.domain in ['light','switch'] %}
          {%- set domain = state_obj.domain %}
          {%- set entity_id = state_obj.entity_id %}
          {%- set entity_ids = lights if domain == 'light' else switches %}
          {%- set current = settings[domain] %}
          {%- set current = dict(current, **settings[entity_id]) if entity_id in settings else current %}
          {%- set key = domain ~ '_' ~ current.items() | list | string | lower | regex_findall('[a-z0-9_]+') | join('_') %}
          {%- if key in ns.spool %}
            {%- set ns.spool = dict(ns.spool, **{key:ns.spool[key] + [entity_id]}) %}
          {%- else %}
            {%- set ns.spool = dict(ns.spool, **{key:[entity_id]}) %}
          {%- endif %}
          {%- set entity_ids = ns.spool[key] %}
          {%- set current = dict(domain=domain, **current) %}
          {%- set current = dict(current, entity_id=entity_ids) %}
          {%- set ns.items = dict(ns.items, **{key:current | string}) %}
        {%- endif %}
      {%- endfor %}
      [{{ ns.items.values() | unique | sort | list | join(', ') }}]
#

that's an example

#

that uses all 3 methods of dynamic keys

#

in a list

#

here's another one

#
    cycles: >
      {% set rollup = current_cycles + [ next_cycle ] %}
      {% set ns = namespace(ret=[], attrs=[]) %}
      {# setup durations for phases #}
      {% for i in range(rollup | length) %}
        {% set attrs = rollup[i] %}
        {% set next_attrs = rollup[i + 1] if i + 1 < rollup | length else {} %}
        {% set ns.attrs = attrs.items() | rejectattr('0','in',['duration', 'action']) | list %}
        {% set duration = (next_attrs.start | as_datetime - attrs.start | as_datetime).seconds if next_attrs else 0.0 %}
        {% set ns.attrs = ns.attrs + [('duration', duration)] %}
        {% if attrs.phase == 'on' %}
          {# on state, try to find phase #}
          {% set l, u = current.final_spin.duration - current.final_spin.window, current.final_spin.duration + current.final_spin.window %}
          {% if l <= duration <= u %}
            {% set ns.attrs = ns.attrs + [('action', "finish")] %}
          {% else %}
            {% set ns.attrs = ns.attrs + [('action', "spinning")] %} 
          {% endif %}
        {% else %}
          {# off state, do not collect phase #}
          {% set ns.attrs = ns.attrs + [('action', "idle")] %}
        {% endif %}
        {% set ns.ret = ns.ret + [dict(ns.attrs)] %}
      {% endfor %}
      {% set last = ns.ret | list | last | default(idle) %}
      {% if ns.ret | length == 1 and last.phase in ['off', 'idle'] %}
        []
      {% else %}
        {{ ns.ret if 'finish' not in ns.ret | map(attribute='action') else [] }}
      {% endif %}

from https://github.com/Petro31/home-assistant-config/blob/master/scripts/washer_dryer.yaml

#

@silent vector ^

silent vector
#

Checking it out now. Pretty cool Jinja 🧙

mighty ledge
#

the second example isn't great, but it uses it for next_cycle and it's way over complicated for what's actually needed

silent vector
#

Thank you I will play around with this

dull burrow
#

you're welcome

mighty ledge
#

@silent vector the first one is the only example where i'm creating dynamic dictionaries of information in a list using lists of other information

ember coyote
#

Yep that works. Problem is, what if I dont know what "Value1" is? 🙂

floral steeple
#

hi all, I'm trying create a weekly (or monthly) average sensor BUT I do not want the average to include when the sensor is 0....does this makes sense I can explain what I'm trying to do if it does not make sense

lofty mason
ember coyote
lofty mason
#

So your example has multiple ids. which one do you want?

ember coyote
#

last one added to that list

#

might have to do this in several steps 😁

lofty mason
#

yeah, you probably need a foreach loop over each of the keys in the dict, then find the one with the greatest added time, and grab the id of that

#

But basically the thing to know is that state_attr() will return the whole dictionary, and then you can use whatever code you need to operate on that

sage stirrup
#

Hello hello, is there anyone around that wants to help me with a few template questions?

royal vortex
#

ask away

elder stag
#

Can anyone help me with a template to calculate a battery state of charge percent to batter time to 0 or battery time to 20%

mighty ledge
empty elk
#

Hi, im trying to make a value template for a custom switch but its not working as expected

{{ is_state('sensor.f1', 'running') }} returns False
{{states('sensor.f1')}} while this returns running
Why isn’t the top one true?

lofty mason
#

Try in developer tools->template?

#

If I test it i get True / running

empty elk
#

I did try this in the dev tools

#

Its in dutch but this is the template dev tools

lofty mason
#

huh, weird

#

does the state include a trailing whitespace or something? I don't have any other ideas :\

empty elk
#

It shouldn’t

#

But it might, its a sensor for a rest api i created in python and i couldnt use an if statement there aswell

lofty mason
#

If I set my state to "running " I get False/running, and if I set it to "running" I get True/running. So it could happen in theory

marble jackal
empty elk
#

Ofcourse, theres a zero width invisible character behind running. I told python to remove one character and the word didn’t change. Its working now

#

Thanks guys, wouldn’t have figured it out without you

copper rose
#

Is the Android template widget read only or can you include buttons in it that change state? I basically want to just put a mobile dashboard I made on my home screen and it looks like templates are the only way to do it.

sage stirrup
#

Hello, So, I am having a fun time with the imap_email_content sensor. Overall goal, I'm trying to extract a number from an email and set it as the value of a sensor to a helper (or a template sensor?). I have the template code that works to extract the number out of the email, but when I put it into the template sensor the sensor doesn't update and stays as unknown.

#

thats weird I restarted the server and the sensor updated with the extracted value from the email for a second and then flipped to unknown. and when I goto the history of the sensor it shows the value I'm looking for, but the sensor state is unknown

#

weird after sitting for 5 minutes its updated now.

#

It looks like something is causing the startup to be very slow, and it appears my sensor doesn't initialize until HA has finished starting up

brittle socket
#

Hey I am wanting to have an automation announce when someone has entered/left a zone on a google hub how do I get TTS to say the person's name and the zone they entered/left I was told to use a template and I'm assuming I just have all my people inside one template person and when one of them changes it makes the template equal them and that state change will trigger the automation the problem is I don't know how I would go about doing that

marble jackal
# brittle socket Hey I am wanting to have an automation announce when someone has entered/left a ...
trigger:
  - platform: state
    entity_id:
      - person.john
      - person.jane
    to: ~
action:
  - service: tts.google_translate_say
    target:
      entity_id: media_player.livingroom
    data:
      message: >
        {%  set name = states[trigger.entity_id].name %}
        {%  set action = 'left' if trigger.to_state.state == 'not_home' else 'arrived_at' %}
        {%  set zone = trigger.from_state.state if trigger.to_state.state == 'not_home' else trigger.to_state.state %}
        {{ name }} {{ action }} {{ zone }}
sacred sparrow
#

how can I make this - less than '20' for 5 minutes?
wait_template: "{{ states('sensor.couch_smartplug_watts')| int < 20 }}

mighty ledge
#

use a trigger instead

#

or make a template binary sensor w/ delay off

brittle socket
mighty ledge
#

or you're clicking the 'test' button for the automation, which wont work because there's no trigger

brittle socket
#

im just trying to test the actions

mighty ledge
#

right, see my last message

#

there's a typo in the template as well. trigger.from_state.staet should be trigger.from_state.state

mighty ledge
brittle socket
#

ok ill try spoofing my location on my phone to see if it works

mighty ledge
#

Just make sure you fix the typo...

brittle socket
#

yea i did

mighty ledge
#

It'll work then

#

google might trip up with the names of the zones

marble jackal
#

Which typo? 😉

floral shuttle
#

I just accidentally found a script where I didn't end the service template with an {% else %} ... as it is a practically impossible task to manually go through all of my yaml files, I wonder if we could have a smart search for that somehow?

#

above issue hadnt hurt in the past, because any/all of the possible states we're included in the if and elif's, but still, I dont like the templates dangling like that .

mighty ledge
floral shuttle
#

no, it's not about a specific template. I was looking for a way to check all templates in the config, for a missing {% else %}

mighty ledge
#

For a missing else??? Not possible without a crazy regex statement

floral shuttle
#

yeah, thats what I figured.... o well, will check by hand in one of my maintenance cycles...

mighty ledge
#

I know I’ve said this in the past, but I really think you should take a coding class of some sort

#

Just so you can learn basics so that you understand logic

floral shuttle
#

? I have, and I did, and I have no understanding issues

#

I just had some older files....

mighty ledge
#

Because having an else or not is 100% contextual and it shouldn’t be something that every template needs. It’s something that you as a template creator should decide for that specific template

floral shuttle
#

look, its more the opposite in this case. just like when you encounter a certain string, and think, hey, where else did I see that. I had that now with this specific template, and figured: I wonder if I have that elsewhere too.

#

realizing its way easier to search for something, than for the absence of something 😉

ember coyote
#

Im getting there @lofty mason 😄 Now the automation works if there is only one item in the list.

  {{ data.id }}   
  {%- endfor -%}```

That will return the "id" I need. But if there is multiple items in the list, it breaks ofcourse.
rare furnace
#

Anyone who knows how I can send tap action from a custom:button-card?

#

I am trying to send a tap to node red, it works with normal button. But not with custom:button-card. I can hold to get into more info and the press the "press" button and it works. But not when I tap the icon on my dashboard

plain magnetBOT
#

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

rare furnace
#

I have tried: call-service and toggle

mighty ledge
#

or your entity_id is wrong

#

input_button services require an input_button entity, and button services require a button entity

rare furnace
#

entity_id is that the same as the entity?

mighty ledge
#

you're mixing the 2

#

you have an input_button service and a button entity

rare furnace
#

Ok, but how can I fix this?

#

I'm not quite sure what to do

mighty ledge
#

by using the corect service that matches your entity_id...

rare furnace
#

and that is?

mighty ledge
#

what's your entity_id?

#

I feel like you're complicating this in your head

#

and it's really really simple

#

for example, if I have an entity called switch.xyz, and I want to turn it on, i use the switch.turn_on service

#

if i have a light that's called light.xyz and i want to turn it on, i use the light.turn_on service

#

So, 1: Find your entity_id. 2: Find the service that works with that entity_id that does what you want

#

in your case it's going to be input_button.press or button.press, depending on what your entity_id is

rare furnace
#

my entity i want to use is: button.flexit_operating_mode_away

#

this is a button created in node red

mighty ledge
#

alright, so which service do you want to use then?

rare furnace
#

I dont know

mighty ledge
#

based on what i've said

#

are you reading what I'm writing?

rare furnace
#

I just want to toggle it or activate it, not sure if its boolean or a state or something, cant really tell. It just activates a flow

ember coyote
#

what do you want the button to do?

rare furnace
#

Just activate a flow

mighty ledge
#

I'm trying to lead you to water and I feel like you're not reading what I'm writing

rare furnace
#

I'm new. I'm sorry.

mighty ledge
#

it's not about new

#

it's reading

#

Ok, so let me recap

rare furnace
#

I have tried looking for the ID, I dont know where to find it.

#

I tried looking in "entities"

mighty ledge
#

you gave me your id though

#

you said it was button.flexit_operating_mode_away

rare furnace
#

Yeah ok, then my id is: button.flexit_operating_mode_away?

#

Entity and entity ID is the same?

mighty ledge
#

I guess so 🤷‍♂️ is that what you see in your frontend?

rare furnace
#

Yes

mighty ledge
#

click on your entity, there's an info page that will tell you the entity_id

#

if that's what you see in the frontend, then that's the entity_id

rare furnace
#

Yeah it is the ID

#

button.flexit_operating_mode_away

mighty ledge
#

alright, so based on that, what service should you use according to what I said before?

#

you're using input_button.press

#

but that service doesn't match the entity_id button.flexit_operating_mode_away

rare furnace
#

I'm not sure what service I should use. The example i had up there was something I googled and it didnt work

#

I have tried toggle and it didnt work either

#

But with regular button created in dashboard I can use "toggle"

rare furnace
#

Ok, I get it now. It was just button.press, not input_button.press. Thanks

#

So I was almost there, the service was wrong.

mighty ledge
#

Yes, keep in mind you can view all entities in developer tools -> states page (for entity_ids)

#

and you can view all services in the developer tools -> services page

rare furnace
#

Yeah I know that, so my entitiy ID was correct.

#

Allright

mighty ledge
#

right, but using those 2 pages will help you figure out what you can do and how the services/entities interact

rare furnace
#

Cool. I am also trying to make animations to the button, but the entity im calling the service on have no feedback, can I use a different entity to start animations, change colors etc on the same button?

#

I have a multi state object I can read the feedback from

mighty ledge
rare furnace
#

yeah thats what I'm using

#

Currently i have standard buttons in a container with fan symbol

#

Oh ok, frontend, noted

floral steeple
#

all, I'm scratching my head with this one....I'd like to create a sensor that only averages the value of another sensor when its non-zero. Is this possible? Some other members suggest filter and create a new sensor with a filter, and average that, but im not sure if this would work

#

if I create a low bound filter say of 0.01, does it mean that when the real sensor is 0, will the state be 0.01? because I don't want it to include 0.01 when the real sensor is 0.

inner mesa
#

i would just use a simple template

#

{{ expand(['sensor.x', 'sensor.y', 'sensor.z'])|rejectattr('state', 'eq', '0')|map(attribute'state')|map('float', 0)|sum }}

floral steeple
#

ok, but how do I make this a 30 day average?

inner mesa
#

your requirement just shot through the roof

#

sure, but how do I do that on the moon?

marble jackal
#

Btw, I would move the float so it converts non numeric states to the default of 0, and filter out the 0's

inner mesa
#

sure, agreed

#

I'm just the ideas guy, details are left to the reader 🙂

floral steeple
#

its one sensor, and this is how it looks
https://ibb.co/XzmgmS0
I just want the average when its on (i.e. above 0), over 30 days

lofty mason
#

How about a template that just follows the input sensor, but with a state trigger of not_to: 0. Then you can use statistics platform on that for average.

floral steeple
#

i'll work with this {{ expand(['sensor.x', 'sensor.y', 'sensor.z'])|rejectattr('state', 'eq', '0')|map(attribute'state')|map('float', 0)|sum }}

floral steeple
#

im monitoring my HVAC velocity to determine when my filter needs changing. This happens slowly over time, hence the requirement for monthy average. Having 0 in this, would skew the data,

lofty mason
#

This would mean that for the entirety of the time where it is 0, the template will hold the last non-zero value. I'm not sure if that's the right answer for your usecase, how that will affect the average. Maybe forcing it to be unavailable would be better, but I don't exactly know how statistics handles that. I'll guess it just ignores those points, which may be what you want.

floral steeple
#

if I create a binary sensor entity, based on 0 or above 0, only when its above zero, inject the data to the long term average sensor...lol

inner mesa
#

This is where we need my feature request for conditions in trigger-based template sensors

floral steeple
#

do you have a PR? I can support it!!

inner mesa
#

No more PRs from me until my 8 month old bug fix PR gets some attention

floral steeple
#

wonder if there is a way to create a mini-database for this application

floral steeple
#

this i could use right now!

#

how is not possible. Im thinking now, I might have to use google sheets (Excel) when value is above 0, and Excel will be the engine and database. Send the data to google sheets and =mean(AX:BX)...if you think about it, it has time and number...surely HA can do all this, but I'm not seeing it.

sterile plume
#

I've tried to create a template to add gas consumption to my energy management system (already have CO2, Solar, Main import/export, solar array, and battery), though all attempts so far have been unsuccessful.

#

(what is the link to upload code to, instead of pasting it here?)

floral steeple
sterile plume
#

ty

#

This does create the sensor and add the value, though I cannot get the Energy Distribution graphic to show the gas icon and consumption

#

I've tried several permutations, where device_class=energy, state_class=measurement, etc

mighty ledge
#

what energy distribution graphic

#

energy should have a UOM of kWh

sterile plume
#

Even for gas? The one's I've seen are in ft3 and m3

mighty ledge
#

you have to add that as a sensor to gas consumption that produces kwh

#

so your device_class should be energy, and the state_class should be whatever the sensor does

#

then you have to add it to your gas in the energy tab

sterile plume
#

Why do all the working examples I've seen show m3 or ft3 for UOM?

#

in their templates?

mighty ledge
#

if that's what gas requires, then that's the units, but kwh will also work

#

and it should be m3 per hour

#

energy is a rate over time

#

not just a value

#

so to show up in energy, it needs to be an energy

sterile plume
#

" add that as a sensor to gas consumption" is there something special I need to do for this?

mighty ledge
#

see the blurb?

#

it describes what you need

#

also keep in mind that you need to have a history for you to be able to select an entity for gas consumption

sterile plume
#

Ah yes, how could I have missed that!

#

And now it shows up!

#

Now I just have to fix the units.

#

You've been a big help, Petro. Thanks so much!

mighty ledge
#

you may not have to is you use device_class gas w/ m3

#

according to that blurb

sterile plume
#

Yes, thanks!

#

In reality, I'm usings propane, measured in gallons, though I tried using "gallons" and "gallon" for the unit of measure, and it never seemed to work. However, my furnace burns propane at 0.8664 gallons per hour. Since the furnace and heatpump measurements are in watts, and the template time defaults to hours, I assumed that it would automatically perform something like an Riemann integral. However, as the furnace has been running for over an hour, it's now show 91.4, so I'm going to have to figure out some other approach than what I have currently

glossy sleet
#

"{{ state_attr('sensor.uren_gewerkt_deze_week', 'time') }}"

Please, what should i fill in instead of 'time' for this to get a returned value?

#

It's a history stats sensor that i created

#

To track time at work

marble jackal
#

Check in developer tools > states

plain magnetBOT
marble jackal
#

But if it is the state of the sensor you are looking for, use {{ states('sensor.uren_gewerkt_deze_week') }}

marble jackal
glossy sleet
#

Is it possible to hide this for a specific user?

#
           {%- if now().hour < 12 -%}Goedemorgen
           {%- elif now().hour < 18 -%}Goedemiddag
           {%- else -%}Goedenavond{%- endif -%}, {{user}}
Je hebt deze week {{ states('sensor.uren_gewerkt_deze_week') }} uur gewerkt```
#

I have this, but my wife also is seeing my worked hours

marble jackal
#

Probably, which card are you using?

#

Oh wait

#

I already see you are using the user variable

#
           {%- if now().hour < 12 -%}Goedemorgen
           {%- elif now().hour < 18 -%}Goedemiddag
           {%- else -%}Goedenavond{%- endif -%}, {{user}}
{% if user == 'Ziepoeskenetnie' %}
Je hebt deze week {{ states('sensor.uren_gewerkt_deze_week') }} uur gewerkt
{% endif %}
glossy sleet
#

You are the best! Thank you

verbal mica
#

is possible to change integration name of created sensor in config.yaml, so device from that integration gets assigned this sensor/attribute? Exmple: sensor.light_power which was made in yaml gets assiged as attribute to Device switch.light from different integration

rose scroll
verbal mica
verbal mica
#

I give up after hours of trying to fix my sum of "sensor.power" entities to exclude entities with "unavailable" states, since some plugs lose connection from time to time and get "unavailable" as power, and then my "sensor.total_power" reports "unknown"

marble jackal
#

You can use the new sensor group under helpers for that

verbal mica
patent stump
#

Are you able to access event data in a template? I'm using fire event in Node-Red thats called WandD, and I'm attempting to use the data in card.
value_template: >-
{% set event_data = state_attr('event.WandD', 'data') %}

#

Some additional details, I've been trying to do so, but with no success.

#

I see the event coming in via the developer tools using WandD
event_type: WandD
data:
utcDate: "2023-03-04T16:02:46.000Z"
windSpeed: 0.94
windDirection: 29
origin: REMOTE
time_fired: "2023-03-04T16:02:47.217389+00:00"
context:
id: 01GTPNS19H1JEM0GSSFFAPWGMV
parent_id: null
user_id: ee5ff5714a954a30b260e3d3afc07837
But no matter what I've tried I'm not seeing data in the template.

marble jackal
#

not like that

#

but if you have an event trigger, you can use the trigger data

#

trigger.event.data

obtuse zephyr
patent stump
#

Well, I'm pretty new to HA. I have a weatherflow device, and it has local network UDP events that sends out updates on wind direction and speed rapidly. So I am trying to create a card that shows wind direction and speed in real time. I'm not sure which would be easier. If I do the trigger approach does the event that I'm sending from Node-Red need to be modified for the trigger to work?

obtuse zephyr
patent stump
#

I don't have a MQTT server on my network, I use ISY and Polyglot. But since I'm using synology docker, I suppose I could add that to the node-red and HASS containers running there. I have had on my list to learn more about MQTT. I'm already working on learning HA and Node-Red and feel like that is going to take a few weeks.

obtuse zephyr
patent stump
#

Yes, that one polls, if I'm not able to get the template to work, then I'll go the MQTT route.👍

#

I figure if I can wrap my head around the template and triggers, it will translate well to what I have been using for 15 years. ISY from universal devices is a state engine, so triggers is how it works.

obtuse zephyr
#

Still... I think if you're going to keep the event, you're going to end up writing it to a template sensor to then display on a card, just seems like you could skip that if you're using Node-Red and create an entity directly

patent stump
#

I wanted to be able to do that to start with, but I haven't found in Node-red a way to do that.

mighty ledge
#

does node red create the entities on startup? If not, going the template sensor route is the best option as the state & entity will persist on a startup

patent stump
#

I appeared they only way to pass data other than boolean, was the fire event.

#

Ohh...... ok... now I see the light!

#

Yes I'll try the socket.

obtuse zephyr
#

To petro's point, I'm not sure how state is restored (or not) upon startup

mighty ledge
#

If it uses websockets, I would assume it doesn't exist on startup

obtuse zephyr
patent stump
#

On the node red front, I just have a flow that used the node-red-contrib-weatherflow-udp and then pass a value via the fire event.

#

I'm seeing I need to do some reading on this now.

mighty ledge
#

personally, I avoid node red and go w/ just HA

#

the small headaches that node red produces in the long run aren't worth the fancy graphics

#

and if you want to do anything complicated, you need to learn JS which is harder than jinja

#

to me, it makes no sense

patent stump
#

Some of the questions being asked are outside of my understanding right now. I like that idea of KISS, but I don't think HA has local UDP integration with Weatherflow.

mighty ledge
#

and then you get to a point where you never understand yaml either, so you are just shooting yourself in the foot

patent stump
#

I definitely don't want to learn JavaScript.

#

It sounds like there is a weatherflow UDP local network solution for HA, is there?

inner mesa
#

I use it through MQTT

#

Wasn't that pointed out earlier?

patent stump
#

Sounds like the MQTT route would be the better route for me. Yes, it was. 👍

inner mesa
#

there was also a custom component at some point that offered direct integration, I think

patent stump
#

Ahhh thank you! Yes, that looks like addresses what I was looking for. As I mentioned earlier, there was alot of information given to me, and I needed to go through and do the reading to figure out next steps. Thank you @obtuse zephyr @mighty ledge @marble jackal and @inner mesa

amber hull
#

I am using a template that pulls the street number {{ state_attr('sensor.bill','street_number') }} How do I create a blank if the street number is none or N/A?

marble jackal
#

it will be none in that case, so basically blank

#

or you do something like this

#
{% set number = state_attr('sensor.bill','street_number') %}
{{ iif(number, number, 'blank') }}
amber hull
#

Would the output be the word blank? What I would like is nothing i.e. a space.

marble jackal
#

then output ''

amber hull
#

Thanks

sonic ember
#

What would be the suggested method to get a history graph of an entity attribute? Do I create a new entity to contain that attribute, or is there an easier way?

inner mesa
#

Create a template sensor for it

sonic ember
#

Ok, as I thought then. Will try that as soon as I get my HA back up. It often crashes when I use Studio Code Server... Maybe time I figure out why.

obtuse zephyr
#

Probably lack of RAM

halcyon dagger
#

Nevermind, IBM error

swift gull
marsh cairn
#

Hi, pretty new to HA and no coder, been fiddling around with this for a few hours now, to get where i am 😄
My situation,,
I receive dates for my waste pick up by using a HACS integration (RecycleApp), works perfectly.
I want to notify myself a day before.

Maybe this is not the perfect way, then i am open to new ways!
If i would add this code to a card i see the date of today. (because tomorrow is "pmd collection")
{{ (as_timestamp(states('sensor.pmd')) - 1) | timestamp_custom('%Y-%m-%d') }}

So i added this code to my automation.
But does it not pass the condition test.
I feel i need something in front of my code like "now=", or "today=", dunno tbh, tried a few things, but no avail 😄
Does anyone have any experience with this please?
Thank you

lofty mason
marsh cairn
#

Now idea how i can understand this line, but it passed 😄

#

thank you!

ember coyote
#

Gurus, what am I missing here? Shouldnt this return all entities with 'door' in the name and are 'on'?

  {% if 'door' in state.name %}
    {% if state.state == 'on' %}
      {{ state.name }}: open
    {% endif %}
  {% endif %}
{% endfor %}```
marble jackal
#

I would say so, but this is case sensitive, could it be that you use Door in the name?

ember coyote
#

Nah dont think so. Tend to only use lower case. But at least now I know im on the right path 🙂

marble jackal
#
{% for state in states.binary_sensor %}
  {% if 'door' in state.name and state.state == 'on' %}
    {{ state.name }}: open
  {% endif %}
{% endfor %}
#

this should work as well

#

the template works for me (it returns the ESPHome API status binary sensor for my doorbell)

marble jackal
#
{% for state in states.binary_sensor if 'door' in state.name and state.state == 'on' %}
  {{ state.name }}: open
{% endfor %}
ember coyote
#

damn, you makes this prettier for each minute

#

its interesting. Your last example works as I would expect. Only that it only returns binary_sensors with door as device_class. I have a z-wave contact sensor thats also named door_xxxx but with device_class safety. That one does not show up.

#

im sure its something on my end. I'll figure it out. Thanks @marble jackal

marble jackal
#

Are you sure it's a binary sensor?

maiden magnet
#

Hi, i want to write one number into the other, but i always get an error:

data:
  value: >-
    "{{states("input_number.niedertarif")}}"
target:
  entity_id: input_number.strompreis

Fehler beim Aufrufen des Diensts input_number.set_value. expected float for dictionary value @ data['value']. Got None

ember coyote
marble jackal
#

Then use state.entity_id

ember coyote
#

ahhh. Now I feel proper stupid.

marble jackal
maiden magnet
marble jackal
#

The first or the second

#

Oh wait, you are using the multi line format.
Don't use quotes outside the template then

maiden magnet
#
data:
  value: >- 
    {{states('input_number.niedertarif')}}
    
target:
  entity_id: input_number.strompreis

like this?

dense swan
#

Anyone know why I am getting this error after 2023.3 in my logs: 2023-03-05 10:06:16.949 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'None' has no attribute 'battery_pct' when rendering '{{ state_attr('sensor.freezer_sensor', 'data')['battery_pct'] }}'?

#

This is my template: freezer_sensor_battery: friendly_name: "Freezer Sensor Battery" value_template: "{{ state_attr('sensor.freezer_sensor', 'data')['battery_pct'] }}" unit_of_measurement: "%"

dense swan
#

Could it be due the restart of HA on first pull? I am pulling that data from a rest platform sensor.

marble jackal
marble jackal
#

Use an availability template or defaults to prevent that

ember coyote
#

is it possible to use multiple filters in the if statement? Like if 'door' in state.entity_id but not 'contact'

#

maybe with regex?

dense swan
# marble jackal Use an availability template or defaults to prevent that

That fixed this one error, what about this? 2023-03-05 10:31:22.398 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'None' has no attribute 'last_checkin' when rendering '{{ strptime(state_attr('sensor.freezer_sensor', 'data')['last_checkin']|replace('-00:00Z','-0000Z'), '%Y-%m-%d %H:%M:%S%zZ') }}'

sonic sand
dense swan
#
        friendly_name: "Freezer Sensor Last Update"
        device_class: timestamp
        value_template: "{{ strptime(state_attr('sensor.freezer_sensor', 'data')['last_checkin']|replace('-00:00Z','-0000Z'), '%Y-%m-%d %H:%M:%S%zZ') }}"
        availability_template: "{{ states('sensor.freezer_sensor') == 'success' }}"```
marble jackal
#

@dense swan availability_template: "{{ state_attr('sensor.freezer_sensor', 'data')['last_checkin'] | default('na') != 'na' }}"

sonic nimbus
#

and I want somehow to change this number '65' based on if input_boolean.guest_mode is on or off. If its off => leave 65 degrees, and if its on to increase up to 80 degrees should I set saome variable if guest mode is set to on. and then to create an if statement?

marble jackal
sonic nimbus
#

maybe it has better clarity

marble jackal
#

It has the same result 🙂

glossy sleet
#
end: "{{ now() }}"```
#

Is this the correct format for tracking a whole week?

#

Because my sensor has reset today

#

I want to track from monday 00:00 to sunday 00:00

#

My purge_keep_days is set to 10 days

lofty mason
#

What is "today" where you are? I assume it's not working correctly or you wouldn't be asking?
That seems like it would track from monday 00:00 to monday 00:00

marble jackal
#

But what you had should give the same (but then a timestamp)

glossy sleet
#

Very strange it has reset today, huh?

swift gull
#

Hi, i just made 2 sensors with scrape to get the info from a website: sensor.f1_date (2023-03-19) and sensor.f1_time (17:00:00Z)
How do i get these in a template condition like now() == sensor.f1_date and now() == sensor.f1_time

glossy sleet
#

I'm in europe

mighty ledge
#

if you want monday to sunday, that's a bit different

#

what the fes posted

fleet viper
#

struggling on a comparitor template. the value shows as 0 but this returns false.

"{{states('sensor.tesla_charger_actual_current') == 0}}"

#

nm made both strings and it worked

inner mesa
#

yes, all states are strings

winter haven
#

How can I use a string value from a value template as part of the broadcast message on tss.google_translate service?

#

Is there some example of the sintax

marble jackal
#

Can you give some more insight where this string value comes from, is it the state of an entity

sonic sand
marble jackal
#

Because you are trying to convert unavailable to an integer

sonic sand
marble jackal
#

my guess would be that the templates for the light entity are rendered before the number entity is available

#

so you will probably see this after a reboot

sonic sand
#

yeah it's coming right after rebooting

marble jackal
#

the best way to avoid is, is to add an availability_template on the light entity

#

oh you already have it

#

add a check on the number to it

sonic sand
#

but there already has an availability template

        availability_template: "{{ states('switch.hfjh_v2_eadb_fish_tank_2') in ['on', 'off'] }}"
marble jackal
sonic sand
#

Checked on the devtools it's returning true, is that ok before I change it?

marble jackal
#

do yo understand what the template is checking?

sonic sand
#

Yeah, if device is ON/OFF and if the number.brightness has numbers as output and not text such as unavailable

marble jackal
#

okay, so it return true now?

sonic sand
#

yeah

marble jackal
#

okay, then you answered your own question

sonic sand
#

Which mean device is ON and has number, changed it

#

Thanks man

marble jackal
#

BTW, what is in that script you are using for the turn_on and turn_off actions

wicked pasture
#

I have a problem with sensor to sum up the kWh from the data provided from zigbee outlet which provides current power consumption.

- platform: template
  sensors:        
      ac_grow_box_watt:
        value_template: "{{ states('sensor.grow_box_switch_power') | float | round (2) *0.1}}" 
        friendly_name: "Grow Box Watt"
        unit_of_measurement: "W" 
        device_class: energy     
        unique_id: acgrowboxwatt

- platform: integration
  source: sensor.ac_grow_box_watt
  name: Grow Box kWh
  unit_prefix: k
  round: 2
  unique_id: growboxkwh
#

{{ states('sensor.grow_box_switch_power') | float | round (2) *0.1}} gives normal output of 3,5 ,but when reading the entity created is "empty" as there are no data accumulated

plain magnetBOT
#

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

mighty ledge
#

to clarify point 1, energy is power over time. i.e. Wh or kWh. So, if you are just outputting watts, then the device_class should just be power.

wicked pasture
#

so now i am trying to get rid of everything that i randomly copy pated from the internet 😉 and i tried following this one https://www.home-assistant.io/integrations/integration/ its suppose to be working, so now i have in my sensors.yaml this :

- platform: integration
  source: sensor.grow_box_switch_power
  name: energy_spent kWh
  unit_prefix: k
  unit_time: h
  round: 2
  unique_id: energy_spent_kwh_123

when i go to developer tools-> states and select energy_spent kWh entity i get state unknown and this what i mean by "empty" sensor from my pov

#

sensor.grow_box_switch_power is returning current power from the zigbeee tuya outlet

mighty ledge
#

is sensor.grow_box_switch_power being recorded by history/recorder? If not, it needs to be.

wicked pasture
#

how to check that?

mighty ledge
#

otherwise, you may have to wait until sensor.grow_box_switch_power has data in the history before it will return a result

#

you can check that by looking to see if the sensor has a state history

#

go to the history or look in the more info on sensor.grow_box_switch_power

wicked pasture
#

so i can see a power graph for that sensor

mighty ledge
#

then you have a history and you most likely need to wait for an update

wicked pasture
#

ok I will check if this works out if not i will ask again

mighty ledge
#

it'll only be instant if your device has the correct amount of data to create the integration

#

if you only have 1 datapoint in your database, then you won't have enough data to create the integration

#

when I say integration i'm referring to the mathematical integration, not a home assistant integration.

#

if you have alot of data, then you most likely configured something incorrectly. Verify your entity_id is correct as that's pretty much the only thing that can mess up the configuration.

#

unless you have 2 sensor sections, that could also cause a problem.

#

@wicked pasture ^

final sun
#

Hi, I am trying to use now() to give me the date but I don't want the time. I've only found now().day, month and year.
How would I only get the date?

mighty ledge
#

.date()

final sun
#

Ah perfect ty

silent vector
#

Is there an easy way to filter to lower after a specific string.

For example var is test
all lowercase after matching 'FOO_' so 'FOO_bar' instead of "{{ test | lower }}" which would be foo_bar

mighty ledge
#

Not following you

silent vector
#

Is it possible to after a certain string make everything lower

#

Vs the entire string

#

If I just do | lower that's the entire string.

#

But I would rather after a certain point be lower.

marble jackal
#

is FOO_ always at the start, and always included?

silent vector
#

Yep it would be

marble jackal
#

{{ test | lower | replace('foo_', 'FOO_') }}

silent vector
#

Is it also possible to look for _ in case FOO_ is not always at the start?

marble jackal
#

this wil also work if it's not at the start

silent vector
#

Maybe it's FOOEY_

mighty ledge
#

I guess I don't understand why you even want to do this

#

I'd just split on _ and check the 1st item or 2nd item

marble jackal
#

If you always want the first part, split on the _

silent vector
#

I will try that

marble jackal
#

well, it needs a lot more code then what I had above

mighty ledge
#

yeah, there's no way to split inline

final sun
#

condition: state entity_id: calendar.arbeit attribute: start_time state: "2023-03-06 14:00:00"

I am trying check if the state is today's date at 14:00:00 and got this:

condition: state entity_id: calendar.arbeit attribute: start_time state: {{now().date()}} 14:00:00

Can I do something like that or how would I format that?

mighty ledge
#

on a generator

#

you might be able to use regex replace and then attempt to map it to a list

silent vector
#

Do you have an example?

marble jackal
#
{% set test = 'FOO_BAR_BANANA' %}
{{ ([test.split('_')[0]] + test.split('_')[1:] | map('lower') | list) | join('_') }}
#

FOO_bar_banana

silent vector
#

Awesome

#

Thank you.

marble jackal
#

you need to use a template condition

final sun
#

Hmm thats what I thought but wasn't sure. I'll try to get into it

mighty ledge
#

just make a template condition

marble jackal
#

{{ state_attr('calendar.arbeit', 'start_time') | as_datetime | as_local == today_at('14:00') }}

final sun
#

Tyvm I'll see if that works for me 🙂

swift gull
#

How do i substract 10 minutes from an input_datetime helper. (Time only)

inner mesa
#

{{ states('input_datetime.date_test')|as_datetime - timedelta(minutes=10) }}

floral steeple
#

Hi all, I'm using the Torque integration (log car diagnostics to HA). The problem with this integration is that the entities don't survive restart but come back with its history soon as I start the Torque app on my phone. The Spook integration, on every restart, tells me my automation is using an unknown entity as a result. I was hoping a workaround would be to create a sensor based on the Torque sensor, but with an availability template. The state is the state, unless its unknown, unavailable or none...then its just unavailable.

#

this is so wrong, but its a start

      attributes:
        friendly_name: "Jeep Gps Latitue"
      icon: mdi:jeep
      state: >-
        {% set latitude= states("sensor.jeep_gps_latitue") %}
        
        {% if latitude = unknown, unavailable, none %}
          {{ latitude = unavailable }}
        {% else %}
          {{ latitude }}
        {% endif %}
inner mesa
#

yes, I would call that sorta pseudo-code

buoyant pine
#

Pseudo-pseudo-code?

inner mesa
#

just make an availability template

floral steeple
#

that is what would normally work....BUT Frenck's spook will not like that the automation is using an entity that does not exist

inner mesa
#
    - unique_id: jeep_gps_latitude
      attributes:
        friendly_name: "Jeep Gps Latitude"
      icon: mdi:jeep
      availability: "{{ states('sensor.jeep_gps_latitude') not in ['unknown', 'unavailable', None] }}"
      state: "{{ states('sensor.jeep_gps_latitude') }}"
#

I assume the missing "d" was a typo

#

I don't understand this, or the relevance of it:

BUT Frenck's spook will not like that the automation is using an entity that does not exist

floral steeple
#

its a long story...but basically the Torque integration is outdated

#

Ok! I will try this, and yes that was a typo

swift gull
#

I like to use that time in an automation but i want to trigger 10 minutes before 17:00

floral steeple
#

@inner mesa thank you, that worked! Now Frenk's Spook wont warn me every time I restart HA that Torque sensors are missing and the automation should be updated.

inner mesa
swift gull
#

Thx ill take a look

swift gull
dense swan
#

That url has the break downs of code to show specific parameters only.

swift gull
#

How i add strptime to that? 🫣

dense swan
#

Ummm like this

#

{{ strptime(today_at(states('sensor.whatever')) - timedelta(minutes=10).'%H:%M:%S') }}

swift gull
#

Lemme try 😁

glossy sleet
#

Hi guys, next question. So, i have a sensor that is tracking time at work. My boss is allowed to subtract a break legally. This is 30 minutes if i worked between 4,0 - 7,5 hours, 60 minutes if i worked between 7,5 - 10,5 hours and 120 minutes if i worked between 13,5 - 16,5 hour shift. Is it possible to implement this so it's calculated automatic?

#

That it is automatically pulled off the hours i worked at a day.

heavy crown
glossy sleet
#

Accept what? It is for my own to check if my hours are payed out like they should

heavy crown
#

You mentioned 'your boss', so why would you need a sensor for this... whatever you register has not real value...just asking

#

And yes, one can construct a figure based on 'total hours'

glossy sleet
#

I need a sensor to supervise if my boss is paying out correctly. He has his own calculation and I just want to check that. Do you understand?

heavy crown
#

of course I can ...only that your figures are just a check and your boss always 'wins' (was in similar situation)

lofty mason
#

How does this sensor work? An input_number that you increment? A template with history_stats?

dense swan
#

{{ (now() - timedelta(minutes=10)).strftime('%H:%M:%S')}}

#

replace now() with your sensor states.

heavy crown
#
{% set day = 8 %}
{% if day > 4 and day <= 7.5 %}
{% set day = day - 0.5 %}
{% endif %}
{% if day > 7.5 and day < 10.5 %}
{% set day = day - 1 %}
{% endif %}
{% if day > 13.5 and day < 16.5 %}
{% set day = day - 2 %}
{% endif %}
{{ day }}
#

I will be mocked for this 🙃

marble jackal
#

you need to covert the sensor state to a datetime

#

{{ (as_datetime(states('sensor.petunia')) - timedelta(minutes=10)).strftime('%H:%M:%S')}}

inner mesa
mighty ledge
#

I'm guessing 90 minutes between 10.5 and 13.5?

glossy sleet
#

Exactly

mighty ledge
#

well that template doesn't cover that

#
{% set hours = 8 %}
{% if hours <= 4 %}{{ hours }}
{% elif hours <= 7.5 %}{{ hours - 0.5 }}
{% elif hours <= 10.5 %}{{ hours - 1 }}
{% elif hours <= 13.5 %}{{ hours - 1.5 }}
{% else %}{{ hours - 2 }}
{% endif %}
#

it seems odd that is first duration is 3.5 hours but the remaining is 3

#

if it was 4.5 starting, then you could make an equation

#

a one liner

glossy sleet
#

Thanks man, can i attach this to a weekly based sensor?

verbal moth
#

Hello,
I keep reading template code: …
and card code: …
Where to put the template code?
I know I have to place the card code in an new lovelance element.

mighty ledge
#

you just squanch it into your configuration.yaml file

verbal moth
#

Thanks 🙏🏼

swift gull
mighty ledge
#

if it's a string... blah[10:-6]

swift gull
marble jackal
#

Use strftime to get the output you want

inner mesa
#

For a lot of this, just googling for your question in Python will get you your answer

#

'How to I get a substring?', for instance. Basic Python

marble jackal
swift gull
#

Change your usename pls

#

"TheHero"

#

Thanks man.

#

Output just 16:50 now 🙌

marble jackal
#

🎉

foggy jacinth
#

Is it possible to show icons in the Developer Tools -> Template section?

stable turret
#

Hi all
Anybody know how to make this work ?

  • type: vertical-stack
    cards
    - !include ./template/gsp.yaml
    - !include
    - ./template/gsp.yaml
    - name:
    entity:
marble jackal
foggy jacinth
fading patio
#

How do I get the description: to show on two lines in the developer services tab of my script? It keeps showing it as one continuous line of text. Tried > , >- and |-. ```
buttonid1:
name: Button ID
description: |-
Identifies the action being returned when the button is pressed.
Use only letters and underscores.
required: true
example: "CLOSE_GARAGE"
selector:
text:

fickle sand
mighty ledge
foggy jacinth
mighty ledge
#

look at the options for that extension

#

if it doesn't have an option to do that, you can't do that

fickle sand
foggy jacinth
mighty ledge
#

not sure how it doesn't though if it shows both the text and icon...

foggy jacinth
#

I want icons with other text, not the text of the icon name.

fickle sand
mighty ledge
#

if you're using the markdown card, you can get it to work in-line with text. Also, you can get it to work with custom:button-card as well

#

basically, it's not easy.

tender blade
#

Hi everyone

#

Anybody can help me make a switch that sends a Google assistant SDK command when I turn it on

#

Like if I turn the switch on the Assistant gets a command

mighty ledge
#

uh, that's a loaded question

#

I suggest you use one of the normal routes to connect to google assistant

#

that means you'll need to expose HA to the internet as well

#

@tender blade can you expand on what you're trying to do? Did you google SDK or do you actually know what it means?

foggy jacinth
mighty ledge
#

but an icon is not text

#

it's an image

#

you can't just put images in the middle of text w/ software without having a method to do so

#

I think you're confusing emoji's with the icons that HA uses. You can use emojis all day, you can't use HA icons because they are not emojis

foggy jacinth
#

in a section on viewed with a web browser, that already shows the icon when you complete the name

mighty ledge
#

yes... and?

#

that doesn't mean you can put that icon in the middle of a line of text

foggy jacinth
#

yes, and what means it can't? I see mdi icons next to text everywhere in HA.

tender blade
#

Sorry for the question after I writed it I got it

mighty ledge
#

you can't move that icon around your ui

tender blade
#

So, I created a boolean switch and when it turns on then it sends a command to the Assistant throught the SDK

mighty ledge
#

I suggest you read up on HTML, then you'd understand because at this point, you're just arguing without having the knowledge to argue.

foggy jacinth
#

I know HTML

mighty ledge
#

ok, then how do you put an image inside text in HTML?

#

post the code right here.

mighty ledge
#

you can't create custom commands w/ google assistant

foggy jacinth
#

<img src=...> text

mighty ledge
#

ok, so try that in a text field

#

if your source is correct and the UI element renders HTML, it will show up properly

#

No built in cards (Aside from Markdown) render HTML

#

so you have to use something custom that renders HTML

foggy jacinth
#

You're saying the only way to render a gray rect box is to put it in a <input type=text> box?

#

and that's why that field can't output an image next to text?

mighty ledge
#

The only way to render HTML in a PREBUILT card in home assistant is to use the markdown card or a custom card that renders HTML that someone else built

tender blade
mighty ledge
#

if you want to make your own custom cards, you can do that and use any html you want, but you need to use typescript & javascript to get the job done

mighty ledge
#

you can change the color to whatever you want, use spans to create sentences and place that in the middle. Again, that can only be done in the markdown card.

#

(or custom cards that render html)

mighty ledge
tender blade
#

So thank you

mighty ledge
#

what exactly are you trying to do? You can expose all sorts of entities in HA to google assistant

#

you can tie scripts to a switch as well so it can run commands in HA

marble jackal
#

You can also expose the scripts directly

#

And call them by start <name> or use them in a routine

#

They are under scenes

stable turret
mighty ledge
#

Do you know how to use that?

stable turret
#

@mighty ledge I got it now, thanks for pointing ♡

mighty ledge
#

The yml you provided looked like lovelace gen

#

if you were just trying to do a normal include, I can help w/ that

crimson token
#

#blueprints-archived message

Hey, I accidentally put my question about sensors in the wrong channel… if anyone here could help me, I’d appreciate it very much ☺️

lofty mason
#

You may want to just delete the post in the other channel and edit them into your post here, just to keep everything in one place.

But as to your question, could you elaborate on what "not working" means? HA won't boot? Undefined value? Returns 6 instead of 7? etc.

crimson token
#

Alright, thanks 🙂

plain magnetBOT
#

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

crimson token
#

Okay, so… I tried making the RESTful sensor at the bottom, but it doesn’t show up at all in home assistant. That’s the issue 🙁

lofty mason
#

Did you reload REST sensor or reboot after adding it? I threw that into my config in my dev instance and I do see a sensor created, though the value remains Unknown.

mighty ledge
#

well, also looking at the resource the template is a bit wrong too

crimson token
#

One sensor tag at the beginning of the copied section, that’s it 👀

#

Hmm, okay… I restarted the YAML, not the entire Home Assistant 🤔

lofty mason
#

That might be enough, not positive. If you go to developer tools -> states, Do Ctrl-F5, you don't see sensor.mystnode_quality?

mighty ledge
#
{{ (value_json[0].quality.quality * 100 / 3) | round(1) }}
crimson token
#

Alright 🤔
Let me see, one second 🙂

crimson token
mighty ledge
#

also verify that you don't have a sensor: !include sensor.yaml in configuration.yaml

mighty ledge
#

Ok, then upon restart, it should work

crimson token
#

Alright, wait a second… I’ll grab my MacBook ☺️

mighty ledge
#

It'll show up as sensor.mystnode_quality as @lofty mason said

crimson token
#

Does the value template need the quotes or not?

mighty ledge
#

yep

#

sorry

crimson token
#

Alright, thanks. Copied your solution and now I'll restart >D

mighty ledge
#

this

  - platform: rest
    name: "Mystnode Quality"
    resource: https://discovery.mysterium.network/api/v3/proposals?provider_id=0xb393aeba7893a5e337298c183602ad5743e0d7a5
    scan_interval: 120
    value_template: "{{ (value_json[0].quality.quality * 100 / 3) | round(1) }}"
    unit_of_measurement: "%"
crimson token
#

Yes, exactly 🙂

#

I did try to follow the documentation and they use the strings as keys... I'm a little confused XD

mighty ledge
#

Also, FYI y ou don't need quotes for name or UOM. You only need quotes when dealing with characters in your fields that have { [, etc

crimson token
#

Alright, thank you 😄

mighty ledge
#

and the word 'on' and 'off', those also need quotes

#
  - platform: rest
    name: Mystnode Quality
    resource: https://discovery.mysterium.network/api/v3/proposals?provider_id=0xb393aeba7893a5e337298c183602ad5743e0d7a5
    scan_interval: 120
    value_template: "{{ (value_json[0].quality.quality * 100 / 3) | round(1) }}"
    unit_of_measurement: %
crimson token
#

Now it shows up! The restart seems to have worked 😄

mighty ledge
#

whenever you ADD to configuration.yaml, you have to restart

crimson token
#

Thank you very much both of you 🙂
❤️

mighty ledge
#

unless the configuration already exists

crimson token
mighty ledge
#

i.e. if you add a rest sensor, you can just reload

#

yaml reload only works if the integration has already been loaded

#

so when you add a new integration that's never been loaded, you need to restart

#

which might have been what you were running into

#

so from now on, you can add rest sensors without restarting

crimson token
#

Ahhhh, that makes sense. Hadn't used the REST integration before, that's true 🙂

#

This took me way too long to do... just like everything else I do with home assistant 🙈

#

And the REST integration will now request the data every 2 minutes?

mighty ledge
#

yep

#

IIRC it should be 2 minutes from restart

crimson token
#

Great, thank you very much 😌

mighty ledge
#

np

crimson token
#

I set that to 10 minutes, should be plenty 🙂

#

Have a great day!!! ❤️

crimson token
#

I’m back 👀🥲

#

It doesn’t seem to update… last time was 17 minutes ago 😅

mighty ledge
#

it wont' update if there's no updates

crimson token
#

Oh 🤔

mighty ledge
#

i.e. if the value is the same, it will not show a state change

crimson token
#

Ahhhhh, okay 🙈

#

Well, I’m stupid 🥲

#

Thank you once again ☺️

cursive knoll
#

hello i need a template someone to give me information ?

plain magnetBOT
#

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

acoustic idol
#

I can't make sense of the lower part. Can someone help me understand how the sensor Growatt Inverter has the attribute OutputPower?

#

It is part of the MQTT Message, but only the value TotalGenerateEnergy is bound to the sensor? Does it somehow save the MQTT Message?

mighty ledge
#

@acoustic idol json_attributes_topic: "energy/solar/growatt/" that has your attributes in it

#

that topic

acoustic idol
#

yes

mighty ledge
#

so what aren't you understanding then?

acoustic idol
#

Will these attributes be "saved" as attributes in that Sensor?

#

Hmm I'll try to explain

mighty ledge
#

they will be attributes on the sensor.growatt_inverter entity

acoustic idol
#

aaah

#

this this way I can access the full message I guess?

#

I assume this is specific for MQTT integration?

mighty ledge
#

I'm not sure I follow you

#

that mqtt configuration creates the sensor. Whatever you tell it to create, it will create.

acoustic idol
#

hmm ok I think I got it. Let me try

mighty ledge
#

so that configuration you made, is making that mqtt sensor

#

based on the information in your topics

acoustic idol
#

yes that I get. I just was assuming the message is ready by the sensor, the values taken over and the message discarded

mighty ledge
#

I have no idea if that configuration is correct or if your topics give you the proper information

acoustic idol
#

It seems odd to me that I can "access" the message via that sensor

#

But nevermind

#

Thanks alot for helping. I'll check this

mighty ledge
#

you supplied it to the attributes topic, so whatever's in that topic will be in your attributes

#

when that topic updates, so will the attributes on that sensor

acoustic idol
#

Maybe stupid question, sorry I'm a bit new to all this: Wouldnt it make more sense to map the MQTT Message into a new device (if thats possible) and derive the entities via templates?

mighty ledge
#

You can do that

#

But you didn’t do that

#

You told it to make attributes out of those values with that configuration

acoustic idol
#

where did I tell it that?

#

by using sensor?

mighty ledge
#

Your mqtt configuration that you posted

#

I’m guessing you copied and pasted that config then?

acoustic idol
#

yes

#

But I'm trying to understand it

mighty ledge
#

Alright, I suggest you spend time learning what you copied and pasted by reading the mqtt documents

acoustic idol
#

I tried, but honestly I don't fully understand

#

but it's ok, I'll read more

mighty ledge
#

Maybe start with something basic

#

Just a state

acoustic idol
#

just didn't fully understand the Home Assistant logic ydet

#

hmm yeah good idea

cerulean karma
#

Hi, I have got a sensor (sensor.hoymiles_600_ch1_current) that is "unavailable" during night. Is it possible to set it to "0" during this time without creating a copy of it?

marble jackal
#

No

cerulean karma
#

ok 🙂

cerulean karma
#

Another question: I have got a AVG Sensor that is TOP-1 consumer in the homeassistan_v2.db. Why is this sensor so voracious?

#

''' - platform: statistics
name: "Stromverbrauch 15min Durchschnitt"
entity_id: sensor.stromverbrauch_in_watt
state_characteristic: mean
precision: 0
max_age:
minutes: 15

155193|4|||sensor.stromverbrauch_15min_durchschnitt'''

cerulean karma
#

hmm strange, even it is top1 it is only 0,15MB if I am right

low bobcat
#

i'm trying to send the Set temperature from generic termostat via mqtt, but haveing a hard time : payload: "{{ states('climate.study.temperature.state') }}"

cerulean karma
#

if I create a helper via the UI in which yaml is this stored?

#

I can't find the name in any using "grep -i...:"

tidal heart
#

I have a sensor outputting a string that is not formatted as I want to. It uses ; to state a new line but the text is continuous. How can I add that on every ; there will be a line break? Here is an example output https://pastebin.com/52YR36m4

#

I want a line break instead of ;

cerulean karma
#

can you do something like: {{ "XYdjkfjsd; fsdfksdlhflsa; fdshsdjkl " |replace(";","\n") }} ?

tidal heart
wicked pasture
#

Hi i have a question how to get all the calendar events ? When i do

{% set events = states.calendar %}
{% for event in events %}
{{event}}
{% endfor %}

list consists of only one event which is the one that is closest to the current date

marble jackal
#

Oh, looks like you should use "{{ state_attr('climate.study', 'temperature') }}"

marble jackal
hallow pebble
#

I have a sensor sensor.washing_maschine_initial_time and sensor.washing_maschine_remaining_time which give an output as follows: 0:00:00. How can I find out which format that output is in (i.e. string, time, ...). I would like to get the percentage of progress (i.e.
{{ (states(sensor.waschmaschine_remaining_time) / states(sensor.waschmaschine_initial_time) |float * 100) | round(0) }}%
But this template is currently not accepted.

fickle sand
#

All states are strings, so you will always need to convert them (back) to the appropriate type

marble jackal
#

And to receive the state you need to use quotes around the entity_id

hallow pebble
#

Cheers, yes this was a quick copy and paste error.

silent vector
mighty ledge
#

Much better implementation than the first guy who tried it

#

Let's see if it gets merged for next release

#

I'd wager it won't

silent vector
#

🤞it will get merged for April.

mighty ledge
#

@cold crag that's a #frontend-archived question. Also, make sure you format the yaml and post the full yaml where that card resides.

plain magnetBOT
#

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

weak cradle
#

Moreover I do not like to have:
platform: homeassistant
event: start
because it will make the sensor.daily_energy_consumption zero after reboot. How can we keep the old info?

obtuse zephyr
#

Trigger sensors will retain their state upon restart... what are you trying to do w/ that trigger then?

#

You should also only have one template: section

weak cradle
#

I want to get daily consumption based on sum of 2 sensors. This utility meter will show separate values?

#

Can the following be replaced by the utility meter?
- name: "daily_energy_home_usage"
device_class: energy
state_class: total
unit_of_measurement: "kWh"
state: >
{{((states('sensor.energy_consumption_tarif_1')|float +
states('sensor.energy_consumption_tarif_2')|float -
states('sensor.daily_energy_consumption_saved')|float) +
((states('sensor.STP10_0_3AV_40_462_total_yield')|float +
states('sensor.STP3_0_3AV_40_542_total_yield')|float) -
states('sensor.daily_energy_solar_saved')|float) -
(states('sensor.energy_production_tarif_1')|float +
states('sensor.energy_production_tarif_2')|float -
states('sensor.daily_energy_production_saved')|float))
|round(3)}}

obtuse zephyr
#

No, the utility meter will give a running total of a time period though. Like in that doc I linked, the next section then shows you'd use a template (like you just posted) to calculate the sum of multiple

#

But then in that case, you don't need it to be a trigger sensor either

weak cradle
#

You are right. I can port/change my part to that of utility meter. Thanks!

acoustic arch
#

i got two kWh sensors which can be either a number or 'unknown'. How can i add these when one of them is unknown? Im doing a lot of if/then/else but i bet it can be written more hardcore syntax

weak cradle
#

Try with the is_number()
Example:
{% if is_number(states('sensor.daily_energy_offpeak')) and is_number(states('sensor.daily_energy_peak')) %}
{{ states('sensor.daily_energy_offpeak') | float + states('sensor.daily_energy_peak') | float }}
{% else %}
None
{% endif %}

acoustic arch
#

its about 2 PV inverters. One can still be offline, while the other one is producing...

marble jackal
#

{{ [ 'sensor.inverter_1', 'sensor.inverter_2' ] | map('states') | map('float', 0) | sum }}

acoustic arch
#

cool. Thats is indeed more hardcore then:

{% set a = 0 %}
{% endif %}
{% if not is_number('sensor.gw2500_ns_pv_power') %}
{% set b = 0 %}
{% endif %}
{{a+b}}```
#

thank you

marble jackal
#

if you want to sum values, you can always default them to 0

acoustic arch
#

adding | int(default=0) ?

marble jackal
#

btw, what you had was always going to be 0 because you were not checking for the state of the entity, but for the entity_id itself

acoustic arch
marble jackal
#

yes, which is the same as int(0), of use float(0) if you want to include decimals

acoustic arch
#

yup. Thanks! ill use your array map+sum

#

that way i miiiight actually learn something 😉

marble jackal
#

now you were not defining a and b in those cases

acoustic arch
#

once again: many thanks

marble jackal
#

you can do something like

#

{% set a = states('sensor.banana') | float if states('sensor.banana') | is_number else 0 %}

#

but a lot easier for that is {% set a = states('sensor.banana') | float(0) %}

acoustic arch
#

gotcha. Why do you always make it look so easy. I understand what you are presenting, but figuring it out by my self.... ugh

#

ill go with the array. To add something new to my hacked together HA installation😜

amber oxide
#

I'm trying to create a template sensor that will show the current open app on my Apple TV. I haven't ever created a template sensor...I've setup a separate sensors.yaml and templates.yaml file but don't know how to format the sensors I create properly. I'm finding it hard to understand the wiki about it too...

  sensors:
    - name: Television Media
      state: "{states('media_player.kitchen_tv.').attributes.app_open}"```

Will something like this work?
buoyant pine
#
"{{ state_attr('media_player.kitchen_tv', 'app_open') }}"
marble jackal
#

@amber oxide you are mixing the new format and the legacy format

kind flame
#

How do I save a variable in an automation between runs

#
  - variables:
      prior_brightness: |
        {% if brightness is defined %}
          {{ brightness }}
        {% else %}
          0
        {% endif %}
      command: "{{ trigger.event.data.command }}"
      brightness: "{{ trigger.event.data.params.level|int }}"
      command_direction: |
        {% if brightness > prior_brightness %}
          on
        {% else %}
          off
        {% endif %}  ```
#

I'm doing this but brightness always is not defined

marble jackal
#

By storing it in an input_text or input_number

ashen sequoia
#

{{ states.sensor.540i_xdrive_mileage }}

TemplateSyntaxError: expected token 'end of print statement', got 'i_xdrive_mileage'

#

So numbers in entities are a no-go?

#

Devtools keep giving me this error, I'm just trying to write an automation trigger that fires when last_changed is a few minutes ago, but it can't even print it's value at all

fickle sand
ashen sequoia
fickle sand
#

Could you not interpret last_changed as any state changes for x minutes ago?

amber oxide
#

Code is now - platform: template sensors: - name: Television Media state: "{{ state_attr('media_player.kitchen_tv', 'app_open') }}"

fickle sand
#

This as automation trigger

platform: state
entity_id:
  - sensor.540i_xdrive_mileage
for:
  hours: 0
  minutes: 5
  seconds: 0
fickle sand
amber oxide
#

I'm super new to all this templates stuff

#

I'm trying to add the sensor in my sensors.yaml

fickle sand
#

https://www.home-assistant.io/integrations/template/
example of correct syntax in configuration.yaml

template:
  - sensor:
      - name: "Average temperature"
        unit_of_measurement: "°C"
        state: >
          {% set bedroom = states('sensor.bedroom_temperature') | float %}
          {% set kitchen = states('sensor.kitchen_temperature') | float %}

          {{ ((bedroom + kitchen) / 2) | round(1, default=0) }}
amber oxide
#

Yeah, I've read that...but that doesn't work in my sensors.yaml...so I wasn't sure what I needed to do to make it work there

fickle sand
grave solstice
#
                  - attribute: >-
                      {%- if "essid" in states.this.attributes -%}essid{%-endif-%}
                    name: WiFi```
Having some trouble with this...anyone?
amber oxide
fickle sand
#

Legacy format for you is:

- platform: template
  sensors:
    tv_media:
      friendly_name: Television Media
      value_template: "{{ state_attr('media_player.kitchen_tv', 'app_open') }}"
grave solstice
#

Getting undefeined even when attribute essid exists

#

OFC its auto-entities

#

i am aware my question bordelines between frontend and templates

amber oxide
fickle sand
#

I think the best thing to do is to ditch (for now) the splitted setup of sensors.yaml and just build the template sensors in configuration.yaml like the documentation does. After you get a feeling for the mechanisms you can convert everything again into a split config

amber oxide
#

Okay honestly that sounds like the best plan. I was just trying to start out with the split config because it seemed like it might be a good idea just to start out as organised as possible to reduce clutter later down the track...

fickle sand
#

It's always best to first understand the basics, from that you can build a more custom/advanced setup

amber oxide
#

Very true. I have a habit of wanting to go for the most complicated, great looking/functioning stuff immediately without taking time to learn the basics first 😅

fickle sand
marble jackal
#

as mentioned in the docs

grave solstice
fickle sand
grave solstice
#

Yes, i did missunderstand...however i am rewriting the whole thing with the template option instead... wish me luck 😉

grave solstice
#

Getting close... Can somone spot my error probably formatting....

It lists everything weith ip as secondry however state is shown and i dont see the extra attribute in the row....

plain magnetBOT
#

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

grave solstice
#

Non templated code that works:

        filter:
          include:
            - entity_id: device_tracker.*
              attributes:
                source_type: router
              options:
                type: custom:multiple-entity-row
                secondary_info:
                  attribute:
                    - ip
                show_state: false
                state_color: true
                entities:
                  - attribute: essid
                    name: WiFi```
fickle sand
grave solstice
#

Well yes because essid doesnt always exist and the i want to use dynamic value

#

Thats why i am rewriting it

#

WiFI
Undefined is quite ugly

fickle sand
#

So you would only pass in entities that have the attribute essid

marble jackal
#

you can't template the entire config

#

but you can use a template to find the device trackers which match your needs

#

so for example those with the required attribute

plain magnetBOT
#

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

tired pebble
#

Does anyone have an idea on how to set a default value for a rest sensor using value_template? When the request fails or times out, it doesn't use float(0) as a default value

fickle sand
marble jackal
tired pebble
#

Well my internet doesn't work so i can't copy the code from pc

marble jackal
#

especially as you are not using templates

marble jackal
tired pebble
#

But it's just
-platform: rest
Value_template {{value.json_data | float(0)}}
scan_interval: 3600

fickle sand
tired pebble
#

Obviously has other parameters but these are the basic

grave solstice
tired pebble
marble jackal
#

This wil fail if value doesn't have an attribute json_data

#

you can use the default filter to work around that default

#

but is json_data a number? I would expect that to be a mapping itself

tired pebble
#

It's a number

marble jackal
#

anyway {{ value.json_data | default(0) | float(0) }}

tired pebble
#

Let me try

marble jackal
#

or {{ value.get('json_data', 0) | float(0) }}

tired pebble
#

The point i want it to be 0 is because as I said. My internet is currently down so i want my graphs to reflect that

tired pebble
#

Thank you

tired pebble
marble jackal
#

👍

tired pebble
#

Oh man. Localtuya can't initialize with internet outage. What a joke 🙃

grave solstice
#

Before the non template code which the bot changed to file

marble jackal
#

I already commented on that, you can't template the entire config

grave solstice
#

Ok thanks

loud vigil
#

Hi! I'm struggling with round() or format() round had no effect here : value_template: "{{ value | float / 1000 | round(2) }}"

#

and this returned nothing at all: value_template: "{{ value | float // 1000 }}"

mighty ledge
#

you're only rounding the 1000

#

use parenthesis to round the whole equation

loud vigil
#

ah, thanks. I'll try that

frail scarab
#

Hello everyone,
i currently struggling with the translation of states into my language
I would prefer to do this in template -> sensors
I've googled around and tried different code-snippets but nothing worked so far

mighty ledge
#

post what you've tried

frail scarab
#

i get from openweathermap_forecast_condition "rainy" and would like to have "regnerisch"

plain magnetBOT
#

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

frail scarab
#

i'm not sure if the file (/config/sensors.yaml) is correct

mighty ledge
#

that looks good, what's the problem

#

that's the old style so it goes in sensors.yaml

marble jackal
#

I would suggest to stick to one language 😉

frail scarab
#

and i'm not sure if the position (2 space from the left) is correct

marble jackal
#

this looks good for the legacy template format

mighty ledge
#

yaml looks fine

frail scarab
mighty ledge
#
- platform: template
  sensors:
    openweathermap_forecast_condition:
      value_template: >-
        {%- set state = states('openweathermap_forecast_condition') -%}
        {% if state == 'clear-night' %} Ясно, ночь
        {% elif state == 'cloudy' %} Bewölkt
        {% elif state == 'exceptional' %} Предупреждение
        {% elif state == 'fog' %} Туман
        {% elif state == 'hail' %} Град
        {% elif state == 'lightning' %} Молния
        {% elif state == 'lightning-rainy' %} Молния, дождь
        {% elif state == 'partlycloudy' %} Переменная облачность
        {% elif state == 'pouring' %} Ливень
        {% elif state == 'rainy' %} regnerisch
        {% elif state == 'snowy' %} Снег
        {% elif state == 'snowy-rainy' %} Снег с дождем
        {% elif state == 'sunny' %} Ясно
        {% elif state == 'windy' %} Ветрено
        {% elif state == 'windy-variant' %} Ветрено
        {% else %} Нет данных
        {% endif %}
marble jackal
#
sensor:
  - platform: template
    sensors:
      openweathermap_forecast_condition:
mighty ledge
#

bare minimum that goes into the sensors.yaml

marble jackal
#

😠

#

and i missed sensors:

plain magnetBOT
#

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

frail scarab
#

that's the complete file

mighty ledge
#

and that's completely wrong

frail scarab
mighty ledge
#

your yaml is wrong

#

look at what I wrote vs what you have

#

just put what I wrote into your file

frail scarab
#

@mighty ledge how can i keep both "things" in one file?

marble jackal
#

this could work with the right inlcude.. well the translated states.. the one above that looks like a total trainwreck

mighty ledge
#

the main issue is that whatever you have above your template sensor is also a mess

frail scarab
#

sorry, i'm not good with yaml

mighty ledge
frail scarab
#

it works so far

mighty ledge
#

I have no idea how it works as the spacing is wrong

frail scarab
#

@mighty ledge can you please help me to fix it?

mighty ledge
#

I can't tell what it should be doing

marble jackal
#
  friendly_name: Pricelevel
  entity_id: 
    - sensor.electricity_price_blabla
  value_template: '{{ states.electricity_price_blabla.attributes.level }}'

these 4 lines need indentation

#

and how did you include this file?

frail scarab
#

@mighty ledge it creates a new entity from a existing sensor attribute

mighty ledge
#
- platform: template
  sensors:
    pricelevel_electricity_price_blabla:
      friendly_name: Pricelevel
      value_template: '{{ states.electricity_price_blabla.attributes.level }}'

    openweathermap_forecast_condition:
      value_template: >-
        {%- set state = states('openweathermap_forecast_condition') -%}
        {% if state == 'clear-night' %} Ясно, ночь
        {% elif state == 'cloudy' %} Bewölkt
        {% elif state == 'exceptional' %} Предупреждение
        {% elif state == 'fog' %} Туман
        {% elif state == 'hail' %} Град
        {% elif state == 'lightning' %} Молния
        {% elif state == 'lightning-rainy' %} Молния, дождь
        {% elif state == 'partlycloudy' %} Переменная облачность
        {% elif state == 'pouring' %} Ливень
        {% elif state == 'rainy' %} regnerisch
        {% elif state == 'snowy' %} Снег
        {% elif state == 'snowy-rainy' %} Снег с дождем
        {% elif state == 'sunny' %} Ясно
        {% elif state == 'windy' %} Ветрено
        {% elif state == 'windy-variant' %} Ветрено
        {% else %} Нет данных
        {% endif %}
marble jackal
#

okay, the entity_id line can go 🙂

mighty ledge
#

there's a bunch of crap that was in it that was outdated or comments

#

and the spacing was wacky

marble jackal
#

BTW I was just looking at the templating docs, seems I missed the new contains filter which was added in January

mighty ledge
#

hmmm not sure what it does or why it would be needed

#

we have 'search' w/ regex

marble jackal
#

it does that

mighty ledge
#

ah it's a reverse of in

#

yeah we needed that

#

regex 'search' doesn't satisfy that

marble jackal
frail scarab
#

@mighty ledge do i have to restart the whole HA to get the new yaml-file loaded?

marble jackal
#

I was looking at the next docs to see if it was already added

#

you don't need to tag petro every time, he is here, chatting 😛

#

and no, you can reload template entities in devtools > yaml

#

as you can see, there are also others who can answer questions 😉

frail scarab
#

😉
in this channel are currently many people online. how does you know that i'm talking to you? or my question reffers to that what you told me 5 minutes ago?
that's why i tagging him
wrong?

marble jackal
#

it can be kinda annoying..

frail scarab
#

ohhh...
i think i found my issue.
i wanted to push the state to alexa.
i read anywhere that this is a different thing and what we have done does not work.
correct?

#

but it does not work 😦
it's still "rainy"

mighty ledge
#

you have to use your template sensor

#

so you're probably asking the wrong phrase

frail scarab
#

what do you mean?

marble jackal
#

you are creating a new sensor

#

so it will not translate the old sensor, it will create a new sensor which has the translated state of the existing sensor

mighty ledge
#

yes, this doesn't overwrite your existing sensor, you need to ask for your new sensors status

frail scarab
#

ah, oh.... nice. good idea

#

what's the name of the new sensor?

marble jackal
#

probably sensor.openweathermap_forecast_condition_2

#

as you used the same object_id as the existing sensor

#

but try to find it in developer tools > states to be sure

plain magnetBOT
frail scarab
#

hmmm...
no. no _2
only sensor.openweathermap_forecast_condition with "rainy"

marble jackal
#

okay, back to the start

#

where did you place the code petro suggested

#

in which file?

frail scarab
#

/config/sensors.yaml

marble jackal
#

okay

#

and how do you refer to that file?

#

in configuration.yaml

frail scarab
#

😮

marble jackal
#

there should be a line

sensor: !include sensors.yaml
frail scarab
#

is there a emojie for "shame"?

marble jackal
#

probably 😛

frail scarab
#

afk doogo wants to go outside

#

back

#

that explains why you both was so confused about the file

#

okay, i removed the # in from of the include and removed the part above which is somewhere else

#

now i have a sensor.openweathermap_forecast_condition_2

#

but it seems it does not match

#

sensor.openweathermap_forecast_condition state: rainy
sensor.openweathermap_forecast_condition_2 state: Нет данных

#

which means "no Data"

#

it works
"{%- set state = states('**sensor.**openweathermap_forecast_condition') -%}" does the trick

#

@marble jackal @mighty ledge Thank you so much for your help!

marble jackal
# frail scarab <@723160143314812971> <@372843932096397333> Thank you so much for your help!

BTW, alternative approach would be this:

- platform: template
  sensors:
    openweathermap_forecast_condition:
      value_template: >-
        {%- set state = states('sensor.openweathermap_forecast_condition') -%}
        {%- set translations = 
          {
            'clear-night': 'Ясно, ночь',
            'cloudy': 'Bewölkt',
            'exceptional': 'Предупреждение',
            'fog': 'Туман',
            'hail': 'Град',
            'lightning': 'Молния',
            'lightning-rainy': 'Молния, дождь',
            'partlycloudy': 'Переменная облачность',
            'pouring': 'Ливень',
            'rainy': 'regnerisch',
            'snowy': 'Снег',
            'snowy-rainy': 'Снег с дождем',
            'sunny': 'Ясно',
            'windy': 'Ветрено',
            'windy-variant': 'Ветрено',
          }
        %}
        {{ translations[state] | default('Нет данных') }}
frail scarab
#

thank you. currently it works so far for me

plain magnetBOT
#

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

mighty ledge
#

@frank sand ^

plain magnetBOT
#

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

#

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

compact panther
#

Hi can anyone please help with jinja2 code that that dynamically loops through a long list of multiple attributes for an entity called "sensor.gas_stations_search" and prints the the value of 'price' associated with the address at ‘7625 Sawmill Rd’ from my attributes. The end result should be one print & close the loop after it finds the price associated with ‘7625 Sawmill Rd’. currently I get multiple price prints

{% for result in state_attr(‘sensor.gas_stations_search’, ‘stations’).results %}
{% if result.address.line1 == ‘7625 Sawmill Rd’ %}
{% for price in result.prices %}
{% if price.credit.price %}
{{ price.credit.price }}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}

HELP