#templates-archived

1 messages · Page 26 of 1

inner mesa
#

like that

thick mesa
#

How do I round a number to they nearest value? example 84 to 80 i tried "round(0, 'floor')" but still doesnt work

inner mesa
#

negative numbers

#

{{ 84|round(-1) }} -> 80

thick mesa
#

ohh, tysm

neon bolt
#

Hello there, sorry to repeat here but : is there any way to check in a field if the date is in the past as a condition to perform or not an action ?

marble jackal
#

Which date should be in the past?

ivory saddle
#

Hi, how can i capture data from a sensor by using http get? I have a excel worksheet and i want to use the “get data from web” option in excel, this feature allows you to pull the data to the worksheet. Any ideas?

inner mesa
ivory saddle
inner mesa
#

You don't, you need to add headers as shown

ivory saddle
#

Hmm excel doesn’t allow you to do http post or get it only allows you to add the link, does this mean that it can’t be done directly from excel to HA?

neon bolt
pine musk
#

is there a way to iterate over a wildcard list of sensors?

#

ie, i want to execute x = x + states( 'sensor.docker*_memory' )

inner mesa
#

Yes

#

states.sensor|selectattr('object_id', 'search', 'docker.*_memory')

vapid stratus
#

Any ideas as why this template trigger isn't working? The time attribute on that entity is a time string of 06:30:00 and in my developer tools it properly returns true and false, but the automation doesn't trigger when it's supposed to.

  - platform: template
    value_template: >-
      {{ (as_timestamp(now()) + 60)|timestamp_custom("%H:%M:%S") ==
      state_attr('switch.alarm_clock_alarm_0_doppler_system_alarm', 'time') }}
marble jackal
sage stirrup
#

howdy, after some time working on my template code, I figured out how to check if I have a (google) calendar event happening before noon the following day. I wanted to share it on the Home Assistant community forum incase someone else is trying to do the same thing, but I can't find where I'd put it. Any suggestions?

vapid stratus
marble jackal
vapid stratus
marble jackal
#

now() + timedelta(minutes=1) > today_at(state_attr('switch.alarm_clock_alarm_0_doppler_system_alarm', 'time')) should work better than a string comparison

#

Does the alarm time show preceding 0's, so 07:30 instead of 7:30?

#

And does it show seconds?

thick mesa
#

How do I change phone battery state from "discharging" to "Not charging"?

marble jackal
#

I assume it's a binary_sensor and the atual state will be off

#

But anyway, you can't change the state of a sensor. You can create a template sensor which uses the state of the original one, and rephrase it

thick mesa
#

alr, thanks

late island
#

Hey! I would really appreciate if anyone could help me. I am trying to find out what causes this but I cant seem to find it out.

The automation without an error but not doing what it should, because the alarm_time name is missing do looks like this:

https://codeshare.io/dwJRBe

but it should look something like this but this throws an error

https://codeshare.io/JbV1md

marble jackal
#

define an errror

late island
#

whoops

#

Automation with alias 'Alarm Clock' could not be validated and has been disabled: invalid template (TemplateSyntaxError: expected token 'end of statement block', got '{') for dictionary value @ data['condition'][0]['conditions'][0]['value_template']. Got None

marble jackal
#

is your input_datetime containing both date and time?

late island
#

No only the time

#

So using the template function of homeassistant debug the following code is giving me "day is sunday"


day is {{ day }}```
#

So having alarm_time_sunday: name: Alarm Time Sonntag has_date: false has_time: true

as an input_datetime should work in my head

marble jackal
#
            {% set alarm_time = today_at(states('input_datetime.test')) - timedelta(minutes=states('input_number.test') | int) %}
            {{ now() > alarm_time and is_state('input_boolean.test', 'off') }}
#

replace the entities with yours

#

there is really no need to create an if-then structure to return true or false. Your statement will already return that

#

and you should not use state.some.entity.state. Use states('some.entity')

plain magnetBOT
#

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

grand walrus
#

Hello,
Home assistant was not seeing me at home, even when I was at home already during some time.. I I created a bigger zone called "Around_home"..

I was homeping that in checking the number of people in "Around_home", I would be able to see if there is someone at home… Unfortunately,if someone is "Home", it will not count it in "Around_home".. It seems we cannot be in two ovberlaping zones at the same time..

I then created this sensor, to be about to know how many people are at home :

- platform: template
   sensors:
     nbhome:
       friendly_name: "Number of persons at home"
       value_template: "{{states(zone.home+zone.around_home)}}"

But this doens't work.. And is always unavailable…
Could you please help me in the format of this sensor?

solemn frost
marble jackal
#

if you want the template to work, you need to do this

#

"{{ states('zone.home') | int + states('zone.around_home) | int }}"

#

As far as I know you can only change the radius of zone.home using customize

#

Which would still be an option 🙂

grand walrus
#

Thanks a lot @solemn frost , @marble jackal , I'll try both options to see which one works the best! thanks for your support!

gusty nimbus
#

i have a chicken coop with chickens that lay eggs i have an camera inside that sends snapshots through deepstack
i have it working that deepstacks find the egg but how could i use it inside home assistant now?

#

image_processing.deepstack_object_kipei
find this info:
targets:

  • target: egg
    confidence: 60

targets_found:

  • egg: 74.254

summary:
egg: 1

custom_model: kipei
all_objects:

  • egg: 20.433
  • egg: 74.254
#

i want on HA that he shows eggs 0 1 2 3 ..
and possible to telegram ?

#

an 'eggcount' and a telegram on the state of the count?

vapid stratus
vapid stratus
marble jackal
#

Ah okay, well the template I provided should work regardless

plain magnetBOT
#

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

grand walrus
#

Sorry My text was too long... but if you can still have a look 🙂

late island
#

Finally fixed it lol. The solution was changing set alarm_time = states('input_datetime.alarm_time_{{day}} to set alarm_time = states('input_datetime.alarm_time_' ~ day)

ivory saddle
#

My webhooks automation triggered by external nabu url works whenever it wants, it’s not reliable at all, is there a better way to trigger automations from outside Lan?

mighty ledge
#

maybe describe what you're doing alittle better?

ivory saddle
#

@mighty ledge thanks, I’m using iOS shortcuts app to trigger an automation in HA, when using the local ip it always works but when using the external link which is home assistant’s cloud service (Nabu.casa link) it only works sometimes because it does not trigger the automation😕 anyway I’ll move my question to automations

vapid stratus
marble jackal
swift gull
#

(states('sensor.dsmr_reading_electricity_currently_delivered_watt')|float / states('sensor.dsmr_reading_phase_voltage_l1')|float)|round(2) }} somehow it works but i get an error in the logbook, could someone tell me what is wrong with this? Something is in the wrong place or shouldnt be there i guess 😅

marble jackal
#

You are not providing defaults for the float filters, which is causing errors when the entity is not available (eg just after a reboot)

#

Best would be to provide an availability template

swift gull
#

Thx, availability_template with state other then (!=) unavailable works?

mossy flax
#

Hi! how i can change the value of a key of a dict?

mighty ledge
swift gull
swift gull
marble jackal
#

And based on this I assume you are using the legacy template sensor format

swift gull
#

That means like "until its a number"?

swift gull
marble jackal
#

It checks if the entities have a numeric state

swift gull
#

K

mossy flax
mighty ledge
#

no, you have to rebuild the dict

#

well, list

#

you can use namespace, but if your list is already defined outside namespace, you then have to use namespace

#

jinja is limited, it's not designed to 'create memory'

swift gull
limber birch
#

Hey. I have a morning routine that reads out different useful info to me ("Good morning. Today is [day], the [date]...") etc. that lasts for a few minutes.

I want to be able to give the TTS RSS feed data so that it can also read the news as well. Is there a way to do this? I know there is a way to display the news on lovelace, but I want a way that allows the TTS to read it out loud.

swift gull
# marble jackal And based on this I assume you are using the legacy template sensor format

Should be like this then?```template:

  • sensor:
    • name: fase l1 test
      state: "{{ (states('sensor.dsmr_reading_electricity_currently_delivered_watt')|float / states('sensor.dsmr_reading_phase_voltage_l1')|float)|round(2) }}"
      availability: "{{ states('sensor.dsmr_reading_electricity_currently_delivered_watt') | is_number and states('sensor.dsmr_reading_phase_voltage_l1') | is_number }}"
      unit_of_measurement: 'A'```
marble jackal
#

Looks fine

swift gull
#

Great, learned somthing again.. didnt even knew there were 2 methods.. thanks

opaque creek
#

I forgot to add unique ID to some template sensors. Is it safe to add one now afterwards?

marble jackal
#

You can still do that

late island
#

So my template looks like this now:

          {% set now_time = now().strftime('%Y-%m-%d %H:%M:%S') %}
          {% set alarm_time = today_at(states('input_datetime.alarm_time_' ~ day)) - timedelta(minutes=states('input_number.alarm_clock_rise_time') | int) %}
          {{ now_time == alarm_time and is_state('input_boolean.all_gone', 'off') }}```

The output of *now time* is 2023-01-22 19:54:00 and the output of *alarm_time* is 2023-01-22 19:54:00+01:00

It still shows false though.. Not sure what to do about that..
stiff scroll
#

Maybe this will work (not tested):


{% set day = now().strftime('%A').lower() %}
{% set wake_up_time = as_local(now() + timedelta(minutes = int(states('input_number.alarm_clock_rise_time'), 15))) %}
{% set alarm_time = today_at(states('input_datetime.alarm_time_' ~ day))  %}
{{ wake_up_time >= alarm_time and is_state('input_boolean.all_gone', 'off') }}

inner mesa
#

just use {% set now_time = now().replace(microsecond=0) %}

late island
#

Thanks!

marble jackal
# late island Thanks!

I would use this

{% set day = now().strftime('%A') | lower %}
{% set alarm_time = today_at(states('input_datetime.alarm_time_' ~ day)) - timedelta(minutes=states('input_number.alarm_clock_rise_time') | int) %}
{{ now() > alarm_time and is_state('input_boolean.all_gone', 'off') }}
opaque creek
#

Heya! I want a template sensor to turn true if a temp.sensor is above one input.number AND below another input.number. How would that code look like?
Something like this? I guess I want a "&" in there too?

{{states('sensor.temp') | float -1 > states('input_number.XX1') | float < states('input_number.XX2') | float }}
inner mesa
#

That would be 'and'

#

It I don't know what the -1 is doing there

#

But you really want this:

{{states('input_number.XX1') | float < states('sensor.temp')|float < states('input_number.XX2') | float }}
#

You probably want one or both to be <=

vapid stratus
silent vector
#

How would I use the uptime integration entity state in a template?

I want to know if {{ states('sensor.uptime') }} is greater than 1 hour.
Current state output.
2023-01-22T16:17:48+00:00

marble jackal
#

{{ now() - as_datetime(states('sensor.uptime')) > timedelta(hours=1) }}

silent vector
#

Weird
UndefinedError: 'timedeta' is undefined

marble jackal
#

typo fix

#

should have been timedelta

silent vector
#

Oh missed an l in delta

#

Yep lol

marble jackal
#

I missed it, but corrected it about the same moment you responded

silent vector
#

Thank you that worked.

nimble copper
#

I have a timedelta that is 05:32:54. I'm looking to return only the %H:%M.

#

Using this template {{ ('05:32:54'|as_timedelta).total_seconds()|timestamp_custom('%H:%M') }} I get the result 06:32

#

It's adding an hour to the result. I'm on GMT time. Not sure why it's getting the extra hour added?

#

adding timestamp_custom('%H:%M', **local=false**) corrects the addition of an hour. But is that the right thing to be doing in this instance?

marble jackal
#

It's adding an extra hour because of your timezone (which is GMT +1)

#

use | timestamp_custom('%H:%M', false) to not use the conversion to local time

#

which will give the correct result

#

example: 3660 equals to 1 hour and 1 minute

#

if you see that as a timestamp, that would be 1st of January 1970 at 01:01 UTC which is 1st of January 1970 at 02:01 GMT+1

#

and without false it will give you the result in your local time

nimble copper
#

😕 My HA sever is saying it's on GMT. Rather than BST / GMT+1.

marble jackal
#

if you enter {{ now() }} in devtools > templates, what does it return?

nimble copper
#

2023-01-23 11:17:34.396268+00:00

#

Which is my correct local time and matches the timezone set in settings.

marble jackal
#

hmm, in that case it should not matter if you use false or not

nimble copper
#

Yeah that's what I thought.

marble jackal
#

well, it does matter when DST is active, so you should still add it

nimble copper
#

So using | timestamp_custom('%H:%M', false) wont cause any issues when we switch back to BST in March?

marble jackal
#

no, it won't cause issues. If you don't add false you will have issues when you switch to BST

nimble copper
#

Perfect. Thanks for explaining @marble jackal

marble jackal
#

still not sure why the additional hour is added now

#

I also get 06:32 but I'm on GMT+1, so that was what I would expect

nimble copper
#

Yeah it's not what I was expecting.

#

The input is a number of seconds before another event happens. I've converted the amount of time into total seconds -> timedelta -> custom timestamp formatting.

#

So really it doesn't have any correlation or relevance to my timezone.

#

I wonder if I need to convert it into some sort of utc based time? I think I need to explore it further.

#

It's unrelated to this sensor. But I had been working on another template a few weeks back. And another user (can't remember who) had suggested formatting timedelta in this way. I wonder if this might be the approach I need to take in this instance. Needs more investigation:

timedelta(days=1)).astimezone(utcnow().tzinfo).isoformat()

marble jackal
#

the approach is fine

#

you just need to add false

#

I've already explained above why the timezone is relevant, it's becasue it is used in the timestamp_custom filter if you don't add false

marble jackal
mighty ledge
#

i.e. the only proper way to get the correct time out of that (assuming it does not go over 1 day is)

{{ ('05:32:54'|as_timedelta).total_seconds()|timestamp_custom('%H:%M', false) }}
marble jackal
mighty ledge
#

I saw that and it doesn't make sense

#

my only assumption is that OP mislead you.

mystic crescent
sterile prism
#

I have a switchbot on a coffee machine.
I want to use the android app "next alarm" sensor to trigger the swirchbot 30 mins before that "next alarm"

How on earth do I get this to work?

mighty ledge
mighty ledge
mystic crescent
mighty ledge
#

you have Veff

#

as a result

#

if that's the value you want, sure, we can help

marble jackal
mighty ledge
#

that too, I was leaning towards using at: as a trigger

mystic crescent
#

Sorry, what is a Veff?

mighty ledge
#

that's the equation you pointed to

#

what is veff... 🤷‍♂️

mystic crescent
mighty ledge
#

so, do you want veff? If yes, we can help make that equation on page 5 give you veff

mystic crescent
#

Please, that would be brilliant

mighty ledge
#

you'll need to find constants

#

C1 =dimensionless coefficient depending on the
wind effect
C2 = buoyancy constant
C3 = turbulence constan

mystic crescent
#

Yeah, I kind of figured that. The rest are easy enough

mighty ledge
#

or you could use the simplified version that they give you

#
{{ 0.0001 * (Vmet)**2 + 0.0035 * h * delta_t + 0.01 }}
#

h is the height of your window... does not provide units. so 🤷‍♂️

#

I would assume it's meters

#

because they are using a , in the numbers for the decimal point

#

Vmet is derived from a table in temperature difference

#

which for some reason is in kelvin

mystic crescent
mighty ledge
#

but, you can use the t-diff for °C

#

it's the same

mystic crescent
#

Ok, thanks, I’ll see how I get on. I may be back!

mighty ledge
#

you'll also need vmet

#

which is the wind velocity

#

in meters/second

mystic crescent
#

Yeah I’ve got all of the variables I think

#

Thanks again man

mighty ledge
#

So, the last thing is delta_t

#

which means you'll need to make a specific template sensor

#
template:
- trigger:
  - platform: state
    entity_id: sensor.temperature
    variables:
      delta_t: >
       {{ trigger.to_state.state|float(0) - trigger.from_state.state|float(0) if trigger.to_state is defined and trigger.from_state is defined else 0 }}
  sensor:
  - name: v-eff
    state: >
      {% set vmet = states('sensor.wind_velocity') | float(0) %}
      {% set h = 2 %}
      {{ sqrt(0.001 * vmet **2 + 0.0035 * h * delta_t + 0.01 }}
#

@mystic crescent ^

#

keep in mind, you'll have to change the fake sensors that I provided

marble jackal
mystic crescent
opaque creek
clever fable
#

Can anyone spot an error in this

#
data:
  temperature: "{{ states('input_number.heater_temp') | int }}"
target:
  entity_id: climate.living_room_thermostat```
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.

mighty ledge
clever fable
#

I have an input number currently set to 68 and the service doesn't seem to be able to apply that to the thermostat

mighty ledge
#

It'll only apply the setpoint temperature

#

the actual temperature will be whatever it is in your room

clever fable
#

I have looked for errors and was previously getting errors saying it expected a float but now I get no errors, Do I need to specify float in the template?

#

No I am looking at the setpoint value when applying this and it doesn't change

mighty ledge
#

it's a number, which is a float at the end of the day

clever fable
#

yeah thats what I figured

#

Let me get rid of the template just to make sure the service is working properly

mighty ledge
#

you might need to set a high and a low

#

it depends on what mode you're in

clever fable
#

You know that may be it Let me try that.

#

chaging the value to the number 68 gave the same results

opaque creek
#

I want a template sensor that is changing state with 3 "if"s..
1: if a temp sensor is between 2 input.numbers 1 and 2
2: if temp sensor is lower than input.number 1
3: if temp sensor is higher than input.number 2

I'm thinking something like this but it's not working.. will my idea even work? 😄

{% if states('input_number.1') | float <= states('sensor.temp') | float <= states('input_number.2') | float == True %}
  Temp is Between 1 and 2
{% elif states('sensor.temp') | float < states('input_number.1') | float == True %}
  Temp is lower than 1
{% elif states('sensor.temp') | float > states('input_number.2') | float == True %}
  Temp is higher han 2
{% endif %}
clever fable
#

@mighty ledge Needed to set a HVAC Mode as well.

#
data:
  hvac_mode: heat
  target_temp_low: "{{ states('input_number.heater_temp') | int }}"
  target_temp_high: 85
target:
  entity_id: climate.living_room_thermostat```
#

Thanks for your help

mighty ledge
silent seal
mighty ledge
#

Just remove all the == True and it should work

#

except you'll need defaults for float on sensor.temp

silent seal
#

What should happen when input 1 > input 2, but the sensor is still between them? 😉

opaque creek
#

Thank you! Hm ok let me try. Yes maybe there's a lot of IF's that could ruin my idea here hehe

silent seal
#

Well, I would grab a piece of paper and a pen and map out the possibilities

#

But, I'd also set some variables.

silent seal
#
{% set input_1 = states('input_number.1') | float(0) %}
{% set input_2 = states('input_number.2') | float(0) %}
{% set sensor_temp = states('sensor.temp') | float(0) %}

{% if input_1 <= sensor_temp <= input_2 or input_1 >= sensor_temp >= input_2 %}
  Temp is Between 1 and 2
{% elif sensor_temp < input_1 %}
  Temp is lower than 1
{% elif sensor_temp > input_2 %}
  Temp is higher than 2
{% endif %}
mighty ledge
#

{{ 1 <= 3 <= 5 }}

#

however, I'd just use an else

#

for the last one

#

#lazy

silent seal
#

Same, but I copy pasta-ed the original

opaque creek
#

Thanks a lot! @mighty ledge and @silent seal. Yes it did work by just removing the "== true" as you said Petro.
But @silent seal's code looks much more understandable!
You're awesome guys. Thanks a lot!

marble jackal
#

Whoops

silent seal
#

Too slow 😛

#

Which is rare for you!

marble jackal
#

Discord was not displaying all messages

#

It does that sometimes, then I respond and suddenly a whole lot of replies appear

silent seal
#

Ah yes, I have seen that.

mighty ledge
#

Good ole caching

final mural
#

I'm struggling to get a super simple template to work. I tested the template using the developer tools and it works fine there. However, I can't get it to work in Lovelace. In my UI, the icon is not rendered, regardless of the value of the sensor. Any thoughts on what I'm doing wrong?

icon: >
              {% if is_state('sensor.tpms_fl_alarm','00') %}
              mdi:tire
              {% else %}
              mdi:car-tire-alert
              {% endif %}
silent seal
#

Does that card support a template in that field?

#

And you may need icon: >- to remove whitespace around your output

final mural
#

it's an entities card underneath a vertical-stack

silent seal
#

It doesn't support templates

manic yacht
#

Hello,
How can I create a sensor with data from 24 hours ago?
Thank you.

obtuse zephyr
manic yacht
obtuse zephyr
#

Apart from setting up a SQL sensor directly, I'm not aware of a way to fetch that. I don't think templates will have historical access directly, either.

lofty arrow
#

I recently searched for the same thing and it works with sql integration but it's not really practical for my usage. I need to change the history time frequently to find the best for me and don't want to restart ha all the time. I'll redo it in node-red so that I can change the history time easily.
My query looks like this:

SELECT * FROM states WHERE entity_id = 'sensor.your_sensor' ORDER BY ABS(TIMESTAMPDIFF(SECOND, last_updated, DATE_SUB(NOW(), INTERVAL 1 DAY))) LIMIT 1;
pine musk
#

hello, templating folk!
I am playing with ESPHome, on an esp32-cam board. I have turned on ble:


text_sensor:
  - platform: ble_scanner
    name: "BLE Devices Scanner"
#

which returns a json packet:

#
{
    "timestamp":1578254525,
    "address":"D7:E7:E7:66:DD:33",
    "rssi":"-80",
    "name":"MI Band 2"
}
#

I am trying to get the address as a sensor, and the name as an attribute:

    - state_topic: esphome-web-cam-1/sensor/ble_devices_scanner/state
      name: ble_scanner
      object_id: ble_001
      value_template: "{{ value_json.address }}"
      json_attributes_topic: "esphome-web-cam-1/sensor/ble_devices_scanner/state"
      json_attributes_template: "{{ value_json.name }}"
#

but it's not working...

#

I get the address as a sensor, but no name attribute

mighty ledge
mighty ledge
inner mesa
#

suddenly you feel like Rip Van Winkle

pine musk
#

RobC, how do I extract the additional parameter from a json payload

mighty ledge
pine musk
#

its MQTT from an esphome device

mighty ledge
#

Well, your json attributes template should just be {{ value }}

#

the rest looks good

pine musk
#

nice, thanks

mighty ledge
#

np

pine musk
#

NOPE, thats worst

mighty ledge
#

Lol, what's the problem?

#

logs?

pine musk
#

now the sensor is only a frienly name

mighty ledge
#

any errors? logs?

inner mesa
#

I would have said "{{ value }}" as well

#

since it's looking for a dict to populate the attributes

#

or maybe "{{ value|tojson }}"

#

or |fromjson or something

pine musk
#

no errors, just a mostly non-existent sensor

inner mesa
#

or just {{ value_json }}

pine musk
#

ok, I set it up as 2 sensors... but they change way fast

#

cause its scanning ble devices

#

now I need to figure out how to collect the fast scan as a list

mighty ledge
#

You should be using a template sensor

#

with an MQTT trigger as a trigger

#

then make sensors that populate based on the information coming from the trigger

pine musk
#
    - state_topic: esphome-web-cam-1/sensor/ble_devices_scanner/state
      name: ble_address
      object_id: ble_001
      value_template: "{{ value_json.address }}"

    - state_topic: "esphome-web-cam-1/sensor/ble_devices_scanner/state"
      name: ble_name
      object_id: ble_002
      value_template: "{{ value_json.name }}"```
#

is working

#

under MQTT:

fickle kettle
compact rune
maiden magnet
#

Hello, can someone help me? I have an automation which should check if a text helper has the value "Pfäffikon SZ"
How can i do that?

manic yacht
lofty arrow
#

It's open source. No one implemented it yet.

One would need to write a custom_component which does the same but is easier for the user where one can set the history date or time before now you want to look up or even a range where the median is taken or whatever function one could apply.
Maybe it gets into core if people see the needs for it.

For now it's possible but it's not obvious to do so. That's why there are forums, etc. which gives solutions/workarounds 🙂

The thing is that SQL has all the power to do anything related to a history sensor. So it's just nicer for people to do but not a must since it's already possible.

manic yacht
lethal wolf
#

will this work ?

#
description: "shut down all lights when there is no one home"
mode: single
trigger:
  - platform: state
    entity_id:
      - zone.home
    to: "0"
action:
  - service: light.turn_off
    entity_id: all
marble jackal
jolly crest
#

I have a sensor with 3 json_attributes. Only one or the other two has a value at a time. In my value_template I want to only include the active attributes. Now it looks like this: value_template: «{{ value_json.XXX }}». What do i type to include the other two attributes?

lethal wolf
#

@marble jackal I'm a little lost sometimes with all these different sections 😄 but thanks for the reply 😉

neon bolt
#

hi there

#

when i do this as a condition in an automation :
condition: numeric_state
entity_id: sensor.thermometre_salon_temperature
below: input_number.temperature_max_mode_jour
it's working fine ...
is there a syntax for the value in the bellow field to be input_number.temperature_max_mode_jour - .5 degree ?

marble jackal
#

Hi

neon bolt
#

I was told by someone Bright that it could be achieved with value_template

marble jackal
#
condition: numeric_state
entity_id: sensor.thermometre_salon_temperature
value_template: "{{ states('sensor.thermometre_salon_temperature') | float - 0.5 }}"
below: input_number.temperature_max_mode_jour
neon bolt
#

If i understand well, what I try to do is the oposite ?

marble jackal
#

oh, sorry, then use + 0.5 🙂

neon bolt
#

yes ! your right 🙂

marble jackal
#

or just use a template condition

condition: template
value_template: "{{ states('sensor.thermometre_salon_temperature') | float < states('input_number.temperature_max_mode_jour') | float - 0.5 }}"
neon bolt
#

I will try that

#

do I put this directly into my condition ?

#

cool, that's working, could that be used as a trigger too ?

mighty ledge
#

if you use it as a trigger, it will only trigger when the template resolves false, then resolves true

#

so if thermometre_salon_temperature is less than temperature_max_mode_jour - 5 and stays there, it won't retrigger until it moves above, then below again

neon bolt
#

hummm .. i want my fireplace to turn on if the temperature is -.5 degree under my comfort temp ... what would be the best way to trigger that action then ?

mighty ledge
#

if you want it to constantly trigger, use it as a condition

barren umbra
#

If you only want it to trigger once, then use the above value_template as a template trigger.

neon bolt
#

u mean this ?

#

condition: numeric_state
entity_id: sensor.thermometre_salon_temperature
value_template: "{{ states('sensor.thermometre_salon_temperature') | float + 0.5 }}"
below: input_number.temperature_max_mode_jour

barren umbra
#

Why did you change from float - 0.5 to float + 0.5?

mighty ledge
#

it's the same principle

#

he moved it to the other side of the <

neon bolt
#

I need the temp of the thermometer to be -.5 degree under the input number

#

if I use it as the trigger, should I just use it that way ?

#

platform: numeric_state
entity_id: sensor.thermometre_salon_temperature
value_template: "{{ states('sensor.thermometre_salon_temperature') | float + 0.5 }}"
below: input_number.temperature_confort

#

doesn't seem to do what i expect 😄

marble jackal
#

If it's already true it won't trigger

misty oxide
#

Hi, i am trying to setup a sensor using rest, but when its unable to parse the states from my entities. Do anyone have a good method to do this? I also tried to parse this from template to HTTP Request in Node-Red using payload however this gives me "Invalid URL" with no more explaination.

Snip:

  • platform: rest
    name: Christopher til Jobb
    resource: https://api.openrouteservice.org/v2/directions/driving-car?start={{ states.device_tracker.s21plus.attributes.longitude }},{{ states.device_tracker.s21plus.attributes.latitude }}&end={{ states.zone.work.attributes.longitude }},{{ states.zone.work.attributes.latitude }}&profile=driving-car&format=geojson&units=km&api_key=HIDDEN
    value_template: '{{ value_json.features[0].properties.segments[0].duration/60 }}'
    unit_of_measurement: 'min'
    scan_interval: 300
neon bolt
#

it's actually false ...

#

but the fireplace turns on ...

#

I tried either + 0.5 and - 0.5

#

don't seem to be the issue

#

Here is the full Autmation

plain magnetBOT
#

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

barren umbra
#

Examine the automation trace...

neon bolt
#

I dont understand what I see

barren umbra
#

When did the automation trigger? as soon as you saved it, or?

#

What was the room temperature and the input number when it triggered?

neon bolt
#

I think i am stupid ...

#

when i do "execute" does it bypass the trigger ?

barren umbra
#

No, just HA automation challenged!

Yes, it bypasses the triggers AND the conditions!!

neon bolt
#

Shame on me ... 😄

#

is this true only for the Execute command ? or if I fire an automation through another automation too ?

mighty ledge
#

yep

barren umbra
#

I would test your trigger by changing the input number so the numeric state test starts out false and then change the input number so the test becomes true thus triggering the automation via the trigger...

neon bolt
mighty ledge
#

the firing from another automation and testing the automation

#

it only runs the actions

barren umbra
#

You can also do your trigger this way rather than numeric state...

platform: template
value_template: >-
  {{ states('sensor.thermometre_salon_temperature') | float <
  states('input_number.temperature_max_mode_jour') | float - 0.5 }}
neon bolt
#

😦

barren umbra
#

Yessssss, petro is correct!

neon bolt
#

I will need to check all my automations then ... 😄

barren umbra
#

Why are you trying to fire an automation from another automation? That's one place where scripts are used. They only test conditions and execute actions....

neon bolt
#

I will check, maybe I didn't really did it, only triggering some from an action on a button

barren umbra
#

For me, an action on a button would normally run a script, not an automation, but you could fire an automation, which in essence is a just a manual trigger, executing the actions when the button is pressed. The automation will then execute the actions. In actions, you can use choose: or if-then-else: to control exactly what is to happen.

neon bolt
mighty ledge
#

That's ultimately what I do as well

#

I have more scripts than automations

barren umbra
#

No so for me here as I don't think I have any common actions among my 117 automations that I could script. Currently 48 scripts...

mighty ledge
#

I make everything variable

#

and all my scripts are parallel as well as my automations

#

really cuts down on things

barren umbra
#

Hmmm. Food for thought...

neon bolt
#

you mean that that would be better to set that as as script instead a automation ?

#

hum ...

#

unable to paste my screenshot 😄

barren umbra
#

Yes, and no!

neon bolt
#

my question was related to the screenshot I am unable to send 😄

#

I do have an automation with no trigger, no condition ... (some if in the action ...)

barren umbra
#

That should be a script then...

neon bolt
#

good to know, would be my first scrit 😄

marble jackal
#

Basically you already created a script now 🙂

neon bolt
#

can I just copy the action code into my script ?

#

I am learning ...

marble jackal
#

under the sequence: key

#

but you need to take care of indentation then

neon bolt
#

Thanks a lot for your help guys ... I learned a lot today

#

(btw, the automation trigger you helped me to build is working fine !)

barren umbra
#

Automation action: becomes sequence: in scripts so you can copy all of the action: section including action:, paste into script & change action: to sequence:...

neon bolt
#

I will try 🙂

misty oxide
#

Hi, i am trying to setup a sensor using rest, but its seems to be unable to parse the states attribute from my entities. Do anyone have a good method to do this or can point me in the right direction? I also tried to parse this from template to HTTP Request in Node-Red using payload however the payload from template is correct the http request gives invalid url. This points me in the direction that the payload sent to http request is not read. Ive tried different syntanx in the "URL" field without any luck. Worthy to say that i am new to create custom sensors

Sensor snip:

  • platform: rest
    name: Christopher til Jobb
    resource: https://api.openrouteservice.org/v2/directions/driving-car?start={{ states.device_tracker.s21plus.attributes.longitude }},{{ states.device_tracker.s21plus.attributes.latitude }}&end={{ states.zone.work.attributes.longitude }},{{ states.zone.work.attributes.latitude }}&profile=driving-car&format=geojson&units=km&api_key=HIDDEN
    value_template: '{{ value_json.features[0].properties.segments[0].duration/60 }}'
    unit_of_measurement: 'min'
    scan_interval: 300
mighty ledge
misty oxide
#

Before i check it up, would it be so simple that i just change the "resource" in current snip to "resource_template"? 😄

mighty ledge
#

yes

marble jackal
#

You should probably also use state_attr() instead of states.some.entity.attributes.some_attribute

nova fable
#

how do I get / set servo values (level?) from within the templates? my servo has the entity_id number.servo_control
-- edit --
turns out I can get the value like this: {{ states("number.servo_control") }} but how do I change it?

nova fable
#

I am trying to move the servo based on another value.

silent vector
#

Well that would be an integraatio?

#

Integration.

#

Wherever is the servo coming from? As in how would you set it today?

nova fable
#

I don't know? I asked the question somewhere, and I was asked if i had a template for it... so, I started looking at templates... I am new to Home Assistant

silent vector
#

Have you ever controlled the servo through a service call? That's what I'm getting at. I don't have one of these so knowing that would be helpful.

#

Once that's done it's easy

nova fable
#

I haven't. I am a noob here, I am still trying to figure out where to place everything, to get things working.

#

I am able to control that servo from the dashboard with a slider, but I want to be able to control based on another sensor value

silent vector
#

Oh. Are you using esphome?

nova fable
#

yes

silent vector
#
service: number.set_value
data:
  value: "{{ value here }}"
target:
  entity_id: number.servo_control
  
#

Don't literally put the value here but that's where the value from another sensor would go

#

Or whatever you're trying to do

#

What's the other sensor entity id?

nova fable
#

sensor.sump_room_temperature

silent vector
#
service: number.set_value
data:
  value: "{{ states('sensor.sump_room_temperature') }}"
target:
  entity_id: number.servo_control
  
nova fable
#

so, what I am looking to do, is if the temperature in my sumproom gets higher, then I want to start opening a damper, and if it gets to a certain temp, then start a fan.. but it isn't an absolute value from that temperature sensor (say: 20* open 20%, 23 open 50%, and 25* 100% and turn on fan. Is this not a template? or should it go somewhere else, and I can start looking into that section

silent vector
#

Well yes you didn't explain all of that lol.

nova fable
#

sorry.

silent vector
#

You would create a template sensor off of your sump room temperature. Then use the value of the template sensor in the service call.

How do you get 23 open 50% is that arbitrary? What I'm trying to understand is what logic is needed.

#

Are these values you want?
20 open 20%
23 open 50%
25 open 100%

#

In an automation you could track the state change of the template sensor created above ^

nova fable
#

at the moment, those are estimated values... could be different. but basically, I am just looking at how to actaully control the servo without manually using the slider on the dashboard of HA

silent vector
#

Well the logic would be static is why I was asking unless you have a formula for estimating?

#

Then it could be dynamic

nova fable
#

I am sure I can come up with a formula to use, but I am trying to figure out how to move it first, before I leap into full automation of it

#

I was going to use a php script (which is what I know) and roll my own arduino sketch / code, but then I found ESPHome, and then found HA and almost everthign I was going to write, was pretty much done for me... i just had to put evertyhign together. I am now trying to figure out how to put it all together now

silent vector
#

Alright.

- sensor:
    - name: "Servo"
      state: >-
        {% set sump_room_temp  = states('sensor.sump_room_temperature') | int %}
        {% if sump_room_temp == 20 %}
        20
        {% elif sump_room_temp == 23 %}
        50
        {% elif sump_room_temp == 25 %}
        100
        {% endif %}

nova fable
silent vector
#

Home Assistant.

#

There are automations in esphome.

#

But I think it's only off esphome data as in data available to esphome where as ha can consume data from more sources? Not sure.

nova fable
#

where in HA does this go? sorry to sound so 'needy', still trying to learn everything

silent vector
#

In a templates file

timid osprey
#

o.O

inner mesa
#
{% set map = {"20": 20, "23": 50, "25": 100} %}
{{ map[states('sensor.sump_room_temperature')] }}
silent vector
#

That too ^

#

Much cleaner if your logic gets bigger and it's arbitrary values.

nova fable
#

ok, thanks for the info... this gives me something to look at, but I will need to wrap my head around it more... lunch is over, gotta get back to work... will play more when I get home

mighty ledge
#

are you just trying to compensate one value for another?

#

if yes, there's ways to do this right in your esphome sensor or even in home assistant without needing to generate the equation

nova fable
neon bolt
#

Hi there ... anyone could tell me how to change that to trigger if both values are equal ?

#

platform: template
value_template: >-
= = {{ states('sensor.thermometre_salon_temperature') | float <
states('input_number.temperature_confort') | float }}

inner mesa
#

I'm not following. You mean <=?

#

or just ==?

#

I don't know what you meant by just sticking == outside the template like that

neon bolt
#

it's a mistake

#

my template is : platform: template
value_template: >-
{{ states('sensor.thermometre_salon_temperature') | <
states('input_number.temperature_confort') | float }}

#

if I understand well, this one fire the trigger if sensor.thermometre_salon_temperature gets under nput_number.temperature_confort'

#

i would like to to work when both are equal

inner mesa
#

==

mighty ledge
#

Change the < to ==

inner mesa
#

you seem to be dancing around the solution to the point that I can't tell if it's really what you want or not

neon bolt
#

🙂

#

ok ... I was getting a syntax error, but it was my mistake, I did not realize I deleted the float

neon bolt
#

ready for another stupid question ? if the trigger work, but conditions fail, Should I see a trigger date and a trace ?

silent seal
#

Yes

neon bolt
#

😦 looks like it did not work then 🙂

ember gull
#

How can I write a template that returns the precipitation_probability of the current day from the entity in this screenshot? https://i.imgur.com/1gcKqG0.png

#

Oh! I got it!

{{value_json[0]['precipitation_probability']}}```
exotic arch
#

Hi all

#

anyone been working with nordpool additional cost ?

#

been trying for some time now but have somehow messed up and currently have an invalid config...

#

anyone have a few spare minutes to look through my yaml code ?

muted berry
#

I need some help here... So I have an integration that shows the hourly energy price and gets updated each hour. I need to collect that data and expose the avreagera of all data points over the period of a month

#

Im using the nordpool integration if that helps, to get hourly rates

mystic saffron
#

is_volume_muted template not evaluated? (universal media player)

formal ember
#

hey template gurus. trying to convert an entity that is in Watts (W) to Kilowatts (kW) - am guessing I have to divide the original one by 1000, but not sure how to put that into a template to create a sensor.

#
- sensor:
  - name: Solar Current AC Power
    unit_of_measurement: kW
    state: "{{ states('sensor.solaredge_ac_power')|float / 1000 }}"
#

would that work?

edit: yep it works 🙂

misty oxide
formal ember
#
- sensor:
  - name: Solar Current AC Power
    unit_of_measurement: kW
    state: "{{ states('sensor.solaredge_ac_power')|float / 1000 | round(1) }}"

Added the round(1) to the sensor and it isn't working, still getting 3 decimal places in the output...

marble jackal
#

You are rounding 1000 only

formal ember
#

ah fek lol

marble jackal
#

Use parenthesis around the calculation

formal ember
#

as in the float / 1000?

#

ah, put from states onwards

#
ValueError: Template error: round got invalid input 'states('sensor.solaredge_m1_ac_power')|float / 1000' when rendering template '- sensor:
  - name: Grid Current AC Power
    unit_of_measurement: kW
    state: "{{ "states('sensor.solaredge_m1_ac_power')|float / 1000" | round(1) }}"' but no default was specified
#

im a retard, i put quotation marks instead of brackets...

misty oxide
#

Do anyone see what is wrong with this? value_template: '{{ value_json.features[0].properties.segments[0].duration | float /60 }}'
If i remove the |float / 60 it gives me the actual result but i need this to be divided by 60

marble jackal
formal ember
#

thanks mate

marble jackal
misty oxide
#

It gave me 1,181.0 the json result from API is 1180.9 and its seconds. I would like it in minutes hence divided by 60.

#

However, right now it gives me nothing. That might be due to max 40 API request each hour. Hence i think i just move over with "Waze" integration to be honest

sonic ember
#

What am I doing wrong here?

{% set therm = 'climate.incomfort_1' %}
{% if state_attr(therm,'temperature') is not none %}
{{ state_attr(therm, 'current_temperature') >= 'input_number.living_room_home_temperature' }}
{% endif %}

The error I get I think is telling me that one of the two variables being compared is float and the other str.

#

How can I fix this? It must be that state_attr(therm, 'current_temperature') is a string...

lofty mason
#

In line 2 you have 'temperature' and in line 3 'current_temperature' ? is that intended?

sonic ember
#

yes that's intended.

#

Oh wait... DOH! I need |float() after each other the states being compared

#

What's the number for in the brackets of the float() ? I never got tha

lofty mason
#

I believe it is the default value to return if the number cannot be casted to float

#

"foo" | float(5) returns 5

#

If its empty it seems to just propogate an error

sonic ember
#

ah ok

#

Hmm still getting an error: UndefinedError: 'input_number' is undefined

#

input_number.living_room_home_temperature is a helped entity I created. Do I need to add something around it, maybe the state thing as well?

inner mesa
#

Yes, you just gave it a string

#

I suggest reviewing the second link in the channel topic

#

It will help avoid guessing

sonic ember
inner mesa
#

See the 'states' section

sonic ember
#

Yeah I just saw it thanks. Silly mistake!

exotic arch
#

Hi all

mighty ledge
#

hello

timid osprey
#

{{ ["h","e","l","l","o"] | join("") }}

exotic arch
#

I need a bit of help im afraid...I have been trying to add additional cost to my nordpool sensor...but no luck

#

anyone have a few minutes to spare to look at some yaml code ?

mighty ledge
#

just post the question and code here

#

make sure you format the code

plain magnetBOT
#

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

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

exotic arch
#

the idea is to add a few additional costs based on the month and hours

#

In Denmark we have an additional tariff running from 17-21 but only from October to march

inner mesa
#

Adding |float to the end of each line isn't necessary and probably isn't doing what you expect

mighty ledge
#

but outside that the template looks fine

exotic arch
#

when I add the template, the sensor stops working....very strange

mighty ledge
#

but because it's a custom integration, are you sure that it updates properly when time changes?

#

well, you aren't using mutli-line notation

#

but the way you have it should still work

exotic arch
#

the sensor updates every hour...so the idea is to add (+) the additional cost only when its between october and march and from 17-21

#

sadly I am doing something wrong cause the sensor stops working all together...

mighty ledge
#

are there errors in your logs?

exotic arch
#

I have actually copied the example from the repository and changed a bit here and there... so very strange

#

no errors

#

above link shows example code from repository

#

not too much different than mine 😉

#

just restarted HA....now with errors

#

Error adding entities for domain sensor with platform nordpool
Error while setting up nordpool platform for sensor

mighty ledge
#

what's the error

exotic arch
#

so here lies the problem

mighty ledge
#

it's in your logs

#

you may have to view the text logs

exotic arch
#

link to error log

mighty ledge
#

right

#

typo on your part

#

elafgift

#

is in your dict

#

and you're calling

#

elagift

#

notice the missing f

#

also, I just noticed that you have an else that will never be hit

#
    additional_costs: >
      {% set s = {
        "lavlast": 0.5403,
        "spidslast": 1.3202,
        "nettarif": 0.095,
        "systemtarif": 0.08375,
        "elafgift": 0.01
        }
      %}
      {% if 4 <= now().month < 10 %}
          {% if 17 <= now().hour < 21 %}
              {{ s.spidslast + s.nettarif + s.systemtarif + s.elafgift }}
          {% else %}
              {{ s.lavlast + s.nettarif + s.systemtarif + s.elafgift }}
          {% endif %}
      {% else %}
          {{ s.lavlast + s.nettarif + s.systemtarif + s.elafgift }}
      {% endif %}
exotic arch
#

shit...you are right!

mighty ledge
#

you can also probably simplify that whole template

exotic arch
#

been looking at this freakin code for 30 min now...never saw it

#

simplify....huh, then I need your help. I'm already struggling as it is 🙂

mighty ledge
#
    additional_costs: >
      {% set s = {
        "lavlast": 0.5403,
        "spidslast": 1.3202,
        "nettarif": 0.095,
        "systemtarif": 0.08375,
        "elafgift": 0.01
        }
      %}
      {% set last = iif(4 <= now().month <= 10 and 17 <= now().hour < 21, s.spidslast, s.lavlast) %}
      {{ last + s.nettarif + s.systemtarif + s.elafgift }}
#

you can simplify it further by removing the dict

exotic arch
#

thank you very much!! this is great...

mighty ledge
#
    additional_costs: >
      {% set last = iif(4 <= now().month <= 10 and 17 <= now().hour < 21, 1.3202, 0.5403) %}
      {{ last + 0.095 + 0.08375 + 0.01 }}
exotic arch
#

even better - thanks....wonder what you could do with the rest of my sloppy yaml code..... hehe

#

still trying to understand the code....how does the template see the difference between month and hours... the "10 and 17"

mighty ledge
#

it just does

#

there's an and in between

#

there's a order of operations that are performed when code is executed

#

that line is equivalent to

{{ (4 <= now().month <= 10) and (17 <= now().hour < 21) }}
exotic arch
#

so basically it adds 1.32 from october to march between 17 and 21. and the rest of the year and hours it adds 0.54?

mighty ledge
#

but the parenthesis aren't needed because the interpreter is smart

exotic arch
#

damn...where can I learn all this....

mighty ledge
#

so, it's april to october

#

python tutorials will help you the most

exotic arch
#

correct....my bad. the added tariff runs from 1 october until 31 mach

#

python tutorials - perfect. will add to my todo list 🙂

#

thank you again Petro 🙂

mighty ledge
#

np

inner mesa
#

In general, Python and Jinja are descriptive enough that you can often just read the expression like an English sentence. It has a lot less symbolic and obtuse syntax than other languages

dull burrow
#

before fes gets to it :x

marble jackal
#

Huh what?

dull burrow
mighty ledge
#

they are readable IMO

dull burrow
#

With understanding of regex jinja pemdas sure

#

It was a complement because of how ‘elegant’ some of his solutions are based on me lurking in here the past year

#

Apologies if it didn’t come across that way.

inner mesa
mighty ledge
#

no one likes c rob

dull burrow
#

Let me guess that just says hello world?

#

I liked learning C just not pointers

#

I still shiver when I hear star char

inner mesa
#

figuring out what it does is half the fun

dull burrow
#

"fun".. you keep using that word haha 😛

#

fun exercise in a class i suppose

inner mesa
#

After macro expansion the format string is roughly 100K.

dull burrow
#

so this is how they went to the moon on like 2K of ram?

deft pebble
#

Hey is it possible to only state the number if the count is +1, using following template?

        | map(attribute='entity_id') | map('area_name')
        | select('in', ['Living Room'])
        | list | count }}```
#

So if only one cover is open there will be no number, and if there will be 2 or more covers open the number will show?

lofty mason
#

I would do:

{% set n = states.cover | selectattr... 
     (your existing template) %}
{% if n > 1 %}
{{ n }}
{% endif %}
deft pebble
#

Seems like that is working! Awesome! Appreciate you quick help!

wheat kayak
#

Hello I have a sonoff RF hub that turns a fake fireplace on and off with buttons in HA. I would like to have a switch in home assistant that can select on or off. I do not want to use a input_boolean toggle helper because it makes node red automations more complicated, so ideally would love to have the entity show as a switch. Is there a way to do this with the switch template in yaml?

timid osprey
#

if you're able to read the current state, yes

#

actually, a switch will work anyways

wheat kayak
#

cannot read the state as these are momentary buttons

timid osprey
#

optimistic if you can't read it

wheat kayak
#

basically i just need to have "input_boolean.fireplace" to be "switch.fireplace"

silent seal
#

So, exactly what BuSheeZy linked?

wheat kayak
#

Yes - I have looked at the link although i cannot seem to get this to work - I will mess around with it some more

timid osprey
#

make sure you test the switch before you add node-red complexities

#

don't test with a bunch of layers between

wheat kayak
#

will do

pine musk
#

C C++ Lisp.... these are a few of my favorite things

tame coyote
#

no asm?

pine musk
#

its been years and years... the companies that made the computers I programmed in Asm don't even exist anymore

inner mesa
#

Stone Tablet Computing

#

they were bound to be obsolete eventually

pine musk
#

not quite that old.... Digital Equipment Corp

#

Processors – As previously mentioned, the ESP32 uses a Tensilica Xtensa 32-bit LX6 microprocessor. This uses 1 or 2 cores (*all chips in the series are dual-core, except the ESP32-S0WD). The clock frequency reaches up to 240MHz and it performs up to 600 DMIPS (Dhrystone Million Instructions Per Second).

#

wow. Back in the day, a DEC VAX running VMS was a 1 MIP machine.

#

and the ESP32 is 600x as fast

formal ember
#

Is it possible to reverse the state of an entity via a template, I have one for electricity grid usage and it goes from negative to positive- negative being using grid and positive is feeding into grid. I’d like to flip that around for a visual sakes in a gauge card.

pine musk
#

split it in two, and use a dual gauge card. {% set pos = value %}. {% set neg = -value %} based on which way the sstate goes.

formal ember
#

Current gauge on the top right

pine musk
#

ok, use a template sensor:

template:
  - sensor:
      - name: grid_consumption
        state: >
          {% set value = - (value) %}
          {{ value }} 
#

that will take a negative value and give grid_consumption as the positive version of it

#

same thing works to negate a positive value

#

not sure how to do that on the energy page

formal ember
pine musk
#

the template sensor will give you a new entity with the value negated

formal ember
#

and where do I put the current entity in that template to go off?

#

like i should list sensor.grid_consumption somewhere in there no?

pine musk
#

use it for the value in ()

formal ember
#

hmm that isn't working for me

#
- sensor:
    - name: Grid Consumption Reversed
      state: >
        {% set value = - (sensor.grid_consumption) %}
        {{ value }} 
#

i think i've royally stuffed this lol

inner mesa
#

sensor.grid_consumption that isn't how you get a state

formal ember
#

ok

pine musk
#

try states(''sensor.grid_consumption")

formal ember
#

TypeError: bad operand type for unary -: 'str'

inner mesa
#

with |float

formal ember
#

perfect, thanks!

muted berry
#

So the statistics sensor..I'm trying to use max_age option but is it limited to days and not months?

sonic sand
#

hi, I am trying to create a sensor that if both of my phones are home the state of the sensor will be 'ON' if both of them are not home state will be 'OFF'

  - platform: template
    sensors:
      both_phones_at_home:
        value_template: "{{ is_state('device_tracker.elians_iphone', 'home') and is_state('device_tracker.ofir_phone', 'home') }}"
        device_class: presence

What am I missing to make it work?
Thanks!

charred dagger
#

Things usually "work" in one single way but can "not work" in infinite ways. Which one is yours?

charred dagger
#

Yes

sonic sand
#

Well I want the sensor to consider both of devices (I can group them if it's helping) and not only 1

charred dagger
#

So with what you have there you actually get a sensor and no error messages, but it only considers one of the iphones randomly?

sonic sand
charred dagger
#

So you want ON if ANY phone is home but OFF only if BOTH phones are away?

#

Then you should change and to or

sonic sand
#

yeah

#

ok I'm trying that, thanks man!

charred dagger
#

You also may want to change the name of the sensor then, because that will confuse you in the future otherwise.

sonic sand
#

Give me some good sensor name then 😂 I'm bad at these

charred dagger
#

any_phone_at_home for example?

sonic sand
tidal heart
#

I would like to make a sensor reminding me to pay the bills after payday. But if the payday is on a weekend the payment comes the first weekday of the week after. I can't really figure out how to make that work. Anyone got ideas?

#

Trigger on 26th every month if weekday else first weekday after 26th

marble jackal
#
{{ now().day == 26 or (now().day == 27 and now().isoweekday() == 1) or (now().day == 28 and now().isoweekday() == 1) }}

Use this in a template binary sensor

#

@tidal heart ^

tidal heart
#

Wow, thanks a lot! Will try that out

compact rune
#

Guessing the middle condition is meant to have 27, though?

marble jackal
#

yep

compact rune
#

Ah, edited. Yup 🙂

marble jackal
#

just saw that, changed it for testing

#

forgot to change it back

tidal heart
#

I guess if use this as a trigger and make a restart it will trigger again. Anyway to prevent it from running more than once a month?

plain magnetBOT
#

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

marble jackal
#

It should not trigger again

orchid patrol
#

Hi, i have the following Yaml template that allows be to control an input_select option with a switch. I tried with the is_state value template and without the is_state and it's not changing the state of the target everytime i am switching on/off

muted berry
#

and use the binary sensor as a condition

marble jackal
#

That's indeed what I would do, as you will receive the message at midnight otherwise

orchid patrol
muted berry
#

I have an issue I wrote about yesterday, not sure if anyone picked it up

#

So I'm getting the hourly electricity prices for sweden from a Nordpool sensor

#

but I have a floating rate, meaning that the price I'll be paying is based on the average of the past month

marble jackal
muted berry
#

I'm trying to figure out how to actually capture all of the hourly rates, calculate the average, have them avaliable for the entire month and then reset on the last day of the month or first of the next

orchid patrol
marble jackal
#

yes, that's what I was trying to say

orchid patrol
#

But still i am not able to control the input_select option i wanted with the switch

muted berry
#

I can use a statistics sensor, but I can't reset it

orchid patrol
#

it does "nothing" despite the fact that it work in the entity page with manual control

muted berry
#

and I can't set duration as the amount of days differ

#

I can't use an utility meter as that's acumulative data

#

and I can't use the history of the data points directly from the nordpool sensor

marble jackal
orchid patrol
orchid patrol
muted berry
#

Does anyone have any good idea about how to solve this?!

#

I'm out of ideas :d

charred dagger
orchid patrol
#

the problem was obvious lmao

#

look at the yaml code again, i named it bedroom

#

while it was triggering the livingroom

#

i am sad that there is no Boonk emoji here

charred dagger
#

Do you mean 🤦?

orchid patrol
#

closest one you can find i guess

sonic sand
outer holly
#

Hi all, I have what i'm sure is a very simple question about templates but to which I have been completely unable to work out myself or find info about online.

#

If I wanted to create more than one sensor template, how on earth do I go about doing that without getting an invalid config

silent seal
#

Don't repeat the template key 😉

#
template:
  - sensor:
      - name: "Average temperature"
# ...
  - sensor: # if this is a sensor as well, you can omit this line
      - name: "Average humidity"
# ...
outer holly
#

ha interesting. I think I was getting an error without repeating the template key. Just trying to retrace my steps now

silent seal
#

A config check can tell you what is wrong

plain magnetBOT
outer holly
#

and how would the yaml adjust if I wanted to use a value template

silent seal
#

You mean you're using the legacy format which says it's not recommended? 🤪

outer holly
#

erm I guess I may well be doing that.

#

that might be whats throwing up the issues

silent seal
#

Switch to using the new format, and I bet you were duplicating something like the sensor key instead

outer holly
#

I basically have a hand full of temp sensors which I would like to use rounding of 1 decimal place with

silent seal
#

Oh, then delete the templates and wait for Wednesday

#

That is in the current #beta

outer holly
#

ahh

silent seal
#

Which will be out next Wednesday

outer holly
#

ok great. Guess that might be why I was hitting a brick wall

#

thanks for the help 🙂

silent seal
#

Not at all, I suspect you had duplicate keys in YAML and using the legacy format doesn't help

formal ember
#

Hello...

Trying to write a template that changes the colour of an icon within the Mushroom Template Card. I was using something else with card-mod I believe, but that doesn't work here. Hoping for a point in the right direction?

Old one:

state:
  - value: 'off'
    operator: '=='
    color: green
  - operator: default
    color: red
marble jackal
#

icon_color: "{{ 'green' if is_state(entity, 'off') else 'red' }}"

formal ember
#

yeah, so i did try that and the icon is now white

#

or grey...

formal ember
#

"{{ 'grey' if is_state(sensor.washing_machine_status, 'off') else 'green' }}"

#

same for
"{{ 'green' if is_state(binary_sensor.home_assistant_versions_update_available, 'off') else 'red' }}"

marble jackal
#

you can not test this in devtools

#

because you don't have the entity variable defined there

marble jackal
#

what is the total card config?

#

"{{ 'grey' if is_state('sensor.washing_machine_status', 'off') else 'green' }}"
"{{ 'green' if is_state('binary_sensor.home_assistant_versions_update_available', 'off') else 'red' }}"

#

My version was using the entity variable, which is available in the card when you add eg entity: sensor.washing_machine_status

plain magnetBOT
#

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

formal ember
#

Sorry on the phone now so a bit harder to copy pasta

#

Even the one for the text in the card does not seem to work. It’s set to Off but I’ve turned the machine on, which I can see in home assistant, but the card still says off.


{% if (states['sensor.washing_machine_status'].state, 'off') %} 
  Off
{% else %}
  On
{% endif %}
silent seal
#

You want to use

{{ is_state('sensor.washing_machine_status', 'off') | iif("Off", "On") }}
formal ember
#

Ahh

silent seal
#

Try not to use the states object directly (like you were using), it'll throw weird errors at startup/when things are unavailable, etc.

formal ember
#

Ahhh didn’t know that!

#

Now to figure out the icon colour problem

silent seal
#

Also, you weren't actually comparing things, you were just putting two items in brackets

formal ember
#

Yeah I’m really shit at templates tbh

#

One minute think I’m getting the hang of it, then start all over again

silent seal
#
icon_color: "{{ is_state(‘binary_sensor.home_assistant_versions_update_available’,'off') | iif('green', 'red') }}"
#

You had quotes around the template as well as multiline template syntax

formal ember
#

🤦‍♂️

formal ember
formal ember
#

Would this work?


{{ is_state('binary_sensor.home_assistant_versions_update_available’', 'off') | iif("Current", "Updates") }}
silent seal
#

Yes

#

But watch it, you have two different kinds of quotes there

formal ember
#

What should be where?

silent seal
#

Being consistent is key. Personally I try to use single quotes in templates.

formal ember
#

Ah right - will it throw a fit sometimes?

marble jackal
#

Well, if you use the single line notation, you also need to put quotes outside your template

#

and you quickly run out of options if you already use 2 types inside your template

formal ember
#

Ah so that one above should have “” around the entire thing and only use ‘’ inside it

formal ember
marble jackal
#

no, you should not sue these fancy quotes

umbral sigil
#

hello everybody, is there anybody who has a template vor battery states of homematic ip devices and could help me out?

swift abyss
#

`sensor:

  • platform: time_date
    display_options:
    • 'time'
  • platform: template
    sensors:
    dayoftheweek:
    value_template: "{{ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] }}"
    entity_id: sensor.time`
#

If I want to use this sensor can I just put it in configuration.yaml??

#

or is there another file it should be put into?

#

sorry for the super basic question

#

Studio Code server seems to not like the entity_id line

inner mesa
#

you could put that block in configuration.yaml if you don't already have a sensors: tag in there

#

yes, get rid of that

swift abyss
#

ok thanks I'll try that

deft pebble
#

Hey is it possible to create an sensor which is based on multiple attributes? I am able to create an sensor based on a state. But how would i create an sensor based on 2 attributes from 1 entity?

My idea is to create an sensor for my Sonos, creating states like Idle, Playing from source TV or Playing from source Spotify.

{% if is_state('media_player.sync_box', 'playing') %}

Would it be possible to use is_stateattr and how can i combine variables?

inner mesa
#

what attributes?

#

I'm not following what exactly you want to test and for what

#

"combine variables" how?

formal ember
#
{{ is_state('binary_sensor.home_assistant_versions_update_available’', 'off') | iif("Updates", "Current") }}

If binary_sensor.home_assistant_versions_update_available is off, should this template show Current?

#

I thought it would be the other way around, but if I do that, and the entity IS off, it presents as Updates

sand lynx
#

Excuse the potential stupidity, I'm very new to this and this is my first attempt at templates. I'm working on a sensor template to check the charging status of my apple watch. one of the last things I need to figure out is how to update the current status with icloud, since the polling is every 30 minutes. icloud.update seems to be the way to do it, but would that be called inside the template or would that go elsewhere? Thanks

formal ember
dull burrow
#

I think the iOS app exposes watch battery charging and a few other entities

sand lynx
#

it does, but it only checks for updates every 30 minutes.

#

@formal ember thank you. now i'm having issues with icloud.update telling me my email isnt correct.

formal ember
formal ember
sand lynx
#

i'm just hoping i can figure this out and i can stop leaving my watch off the charger. feel weird walking around with a dead watch

swift abyss
#

Hey all, another super on-brand newbie question over here. I was just watching a tutorial on templating and as an example they show {{ states('sensor.date')}} and mention that "everyone has this" but I get "unknown" when I put that into the template section of dev tools. Anyone know what might be happening?

#

Like is this an out of the box thing or do I need to add it?

dull burrow
#

Double check spacing

#

At the end before }}

buoyant pine
#

That doesn't matter

swift abyss
#

{{ states('sensor.date') }} returns the same

buoyant pine
#

Sounds like an entity named sensor.date doesn't exist on your system

swift abyss
#

ok thanks I guess I have to add it to YAML. weird

#

yeah I'll do that thanks so much. Super weird that it isn't a core sensor

#

yup that did it. Thought I was taking crazy pills. Thanks @buoyant pine !

sand lynx
#

Can someone look over this template and let me know what I am doing wrong: https://pastebin.com/bU0tefQN Still learning, so when it didn't work, I attempted to grab some info from the HA site to assist, still failing in traces with no info. Thanks

buoyant pine
#
{% if is_state('device_tracker.kyles_apple_watch_battery', '100') %}
  Battery is charged!
{% else %}
  Put watch on charger!
{% endif %}
#

Depending on what the state actually is though, you might be better off with

{% if states('device_tracker.kyles_apple_watch_battery') | float(0) > 99.9 %}
  Battery is charged!
{% else %}
  Put watch on charger!
{% endif %}
#

Oh wait, a device_tracker entity, hmm...

#

I don't think those report numeric states?

#

Maybe you meant sensor.?

sand lynx
#

in the template tester I got it to report correctly, but it was a mess

#

{% set Watch = state_attr('device_tracker.kyles_apple_watch', 'battery')%}
{{Watch}}

{% set Watch_charge = state_attr('device_tracker.kyles_apple_watch', 'battery_status')%}
{{Watch_charge}} is what I originally found. It displayed the numeric of charging and the status

#

had, not found.

buoyant pine
#

Makes sense. What's the problem then?

#
{% if state_attr('device_tracker.kyles_apple_watch', 'battery') | float(0) > 99.9 %}
  Battery is charged!
{% else %}
  Put watch on charger!
{% endif %}
sand lynx
#

my original attempt was, due to the 3 different states (NotCharging, Charged, Charging) I was going to do an If statement..if < 100 or status == "charging" then else

#

but again, im learning and every attempt to put it into a template failed me. lol

#

{% if 'device_tracker.kyles_apple_watch.battery' < '100' or
'device_tracker.kyles_apple_watch.battery_status' == 'Charging' %}
Not charging
{% else %}
Watch Charging!
{% endif %}

buoyant pine
#
{% set batt = state_attr('device_tracker.kyles_apple_watch', 'battery') | float(0) %}
{% set status = state_attr('device_tracker.kyles_apple_watch', 'battery_status') %}
{{ 'Put watch on charger!' if status == 'NotCharging' and batt < 90 else 'Battery is charged!' }}
sand lynx
#

that makes a lot more sense, thank you. let me see if i can get it added now.

#

is the information in the top correct? script:
msg_watch_battery_check:
sequence:
service: notify.mobile_app_iphone_2
data:
message: >

#

It still does nothing

#

it works inside the template tester, but in an actual template trigger it does not.

swift abyss
#

I've been googling for a while and I'm super surprised to see that there is seemingly no simple solution for getting a list of calendar events from a calendar entity? Is that right? I'm just trying to get a list of the days events so I can put it in a morning digest.

marble jackal
#

A calendar entity only has one calendar entry in it's data

swift abyss
#

I thought templating would be the solution but yeah it only shows the next event

marble jackal
#

So you will not be able to get a list of events out of it

swift abyss
#

that's pretty silly.

#

Ok thanks

#

seems like a solid contender for a WTH post

sand lynx
#

im confused as hell script: service: notify.mobile_app_iphone_2 data: message: {% set batt = state_attr('device_tracker.kyles_apple_watch', 'battery') | float(0) %} {% set status = state_attr('device_tracker.kyles_apple_watch', 'battery_status') %} {{ 'Put watch on charger!' if status == 'NotCharging' and batt < 90 else 'Battery is charged!' }}

#

is failing, traces show `Executed: January 27, 2023 at 1:53:00 AM
Result:
result: false
entities:

  • device_tracker.kyles_apple_watch`
#

verified name of entity, checked out.

marble jackal
#

Please properly format it as code

plain magnetBOT
#

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

marble jackal
#

@sand lynx But based on what I can get out the unformatted mess above, my guess is that you need to add > after message: (so message: >) to indicate you are using the multi line format

ebon yoke
#

is it possible to adjust the times of day on and off times through another helper?

#

i want to dynamically be able to change those

marble jackal
#

the times of day of what?

sand lynx
#
service: notify.mobile_app_iphone_2
data:
message:  >
{% set batt = state_attr('device_tracker.kyles_apple_watch', 'battery') | float(0) %}
{% set status = state_attr('device_tracker.kyles_apple_watch', 'battery_status') %}
{{ 'Put watch on charger!' if status == 'NotCharging' and batt < 90 else 'Battery is charged!' }}
```  Here is the current one.  As a template trigger it keeps failing on the device_tracker in traces as "This node was not executed and so no further trace information is available."
#
source_type: gps
battery_level: 100
latitude: Location
longitude: Location
gps_accuracy: Location
account_fetch_interval: 30
device_name: Apple Watch Series 7 (GPS + Cellular)
device_status: offline
owner_fullname: Me
battery_status: NotCharging
battery: 100
low_power_mode: false
icon: mdi:cellphone-link
friendly_name: Kyle’s Apple Watch

Entity attributes for "device_tracker.kyles_apple_watch"

inner mesa
#

change > to >- and indent the three lines under message: to the right by 2 spaces

#

also, indent message: to the right by 2 spaces

plain magnetBOT
#

YAML is the mark up language used by Home Assistant, consistent indenting (two spaces per level) is key. Here is a primer, and this explains multi-line templates. For validating YAML see YAML Lint.

inner mesa
#

@sand lynx Proper indentation is critical for YAML. Also:

plain magnetBOT
inner mesa
#
service: notify.mobile_app_iphone_2
data:
  message: >-
    {% set batt = state_attr('device_tracker.kyles_apple_watch', 'battery') | float(0) %}
    {% set status = state_attr('device_tracker.kyles_apple_watch', 'battery_status') %}
    {{ 'Put watch on charger!' if status == 'NotCharging' and batt < 90 else 'Battery is charged!' }}
sand lynx
#

Thanks for the help, @inner mesa. I added that and it seems to do the same. Am I putting in the correct area using a trigger template?

inner mesa
#

that's not a trigger, it's a service call

#

if you're putting it in the trigger section of an automation, then no, that's not the right place

sand lynx
#

That might be part of my problem then.

inner mesa
#

it's not a trigger 🤷

sand lynx
#

So that makes me more confused. How would I use this to run automatically each night at a certain time? I apologize for all the questions, still trying to understand how to properly use home assistant, I’ve had it for about a week now.

inner mesa
#

with a time trigger, and that in the action

sand lynx
#

That seemed to have worked perfectly. Thank you for all the help and the docs to view, I’ll read up on those to try and make my life easier.

#

And yours too, lol

slim cape
#

Hello folks! I have a pretty simple question admittedly, but I'm just not very familiar with jinja syntaxing...I'm trying to use a value_template in the imap_email_content integration, and would like the conditional search to be case-insensitive:

      {% if 'delivered' in subject %}

I can't seem to find a way to specify that, and if that's not possible, another thought I had was maybe specifying a list, like:

      {% if ['delivered', 'Delivered'] in subject %}

Is there a case-insensitive approach? If not, will the list method work?

inner mesa
#

the easiest way is just to do {% if 'delivered' in subject|lower %}

slim cape
#

Ah! I had seen that syntax as well, but wasn't sure how it could be applied there. Thank you!

fleet viper
#

I'm trying to help cover gaps in mqtt/rtl data to maintain the current data if nothing shows up but the decimal is getting moved around on this.

Any thoughts?

- name: Weather Station Temperature
  unique_id: weather_station_temperature
  icon: mdi:thermometer
  state_topic: "rtl_433/Acurite-5n1/1558"
  device_class: temperature
  unit_of_measurement: "°C"
  value_template: "{{ value_json.temperature_C if value_json.temperature_C is defined else this.state }}"
#

is it something to do with conversion of C to F in a widget and it doesn't know the unit?

inner mesa
#

what does this mean?

the decimal is getting moved around

fleet viper
#

most recent data point is 53.2 F on the widget, then it jumps to 503.6

inner mesa
#

I suppose that it's possible that it's getting confused and repeatedly converting the value from C to F, even though it's already F

#

I would file an issue

#

this.state should either take the "native" state value for temperature entities, or bypass the conversion

tame coyote
#

or the sensor is failing

inner mesa
#

Yes, you could check that in MQTT Explorer

tame coyote
#

i've got a few sensors failing dumps realy hot or really cold

fleet viper
#

ya looks like it was failing for a bit. its been clear for the last hour. just odd timing it seems 😄

formal ember
#

would it be possible to combine the three (I think) binary sensors for HA updates (Core, OS, Supervisor) into one entity?

marble jackal
#

Well, you can create a binary sensor out of it, but it won't be an update entity

plain magnetBOT
#

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

half pendant
formal ember
marble jackal
#

A binary sensor would work for that

formal ember
#

thanks mate

lavish tapir
#

Roborock reports sensor times in seconds now. How can I use a template to change it back to hours?

pine musk
#

cool RobC

narrow surge
#

For automating the heating in the house better I would like to do the following:

When there is motion detected without a 5 minute pause between 2 detection points turn heating on 19c Will this only be possible with a template, if so what things should I use?

haughty breach
#

@narrow surge No, templates aren't necessary... but you could do that with standard state triggers and wait for trigger action. You might be able to do it with a wait template action, but only if your sensors have a long cool-down.

narrow surge
#

I thought that would need to be on for the entire 300 seconds to work?

haughty breach
#
....
action:
  - wait_for_trigger:
      - platform: state
         entity_id: 
           - binary_sensor.multisensor_living_room_motion
           - binary_sensor.motion_2
         to: "on"
     timeout: "00:05:00"
     continue_on_timeout: false
  - service: climate.turn_on .....
narrow surge
#

Thanks, I will try, I thought for this it would only work its its on for 5 minutes constantly, but I'm not always detected constantly.

haughty breach
#

Depending on how short your sensors' cool-down period is, you may need to use a template condition to reject when the first and second trigger comes from the same entity.

narrow surge
#

With 2 detection points I meant time between first and last detection in a 5 minutes time frame, not 2 motion detectors.

haughty breach
#

With that clarification, you can disregard the comment about the template condition and just use the wait for trigger.

dire zephyr
#

Hi guys. Having a problem decoding json info from mqtt sensor.

#

I have am mqtt sensor working fine using tele/WaterTankMonitor/SENSOR

#

and I can put out "Distance" from the following:

#

14:39:15.440 MQT: tele/WaterTankMonitor/SENSOR = {"Time":"2023-01-29T14:39:15","ANALOG":{"A0":840},"DHT11":{"Temperature":29.0,"Humidity":49.0,"DewPoint":17.2},"SR04":{"Distance":77.4},"TempUnit":"C"}

#

BUT the problem is I am using DeepSleepTime and sometime data won't get sent using tele before going to sleep again. So I want to us the topic: stat/WaterTankMonitor/STATUS10

#

It always gets sent after waking from deep sleep and looks like this:

#

stat/WaterTankMonitor/STATUS10 = {"StatusSNS":{"Time":"2023-01-29T14:38:51","ANALOG":{"A0":840},"DHT11":{"Temperature":29.1,"Humidity":49.0,"DewPoint":17.3},"SR04":{"Distance":77.4},"TempUnit":"C"}}

#

The problem is my value template:

#

value_template: "{{ value_json['SR04'].Distance }}"

#

doesn't pull out Distance. I assume it is because of the {"StatusSNS": in the payload but I don't understand templating well enough to include this path.

buoyant pine
#

{{ value_json['StatusSNS']['SR04']['Distance'] }}

dire zephyr
#

@buoyant pine thank you so much that works.

narrow surge
warm elbow
#

Is it possible to make templates that are only used inside a blueprint and not available as a choosable entity?

#

I would like to create a template sensor for logic inside a blueprint. It should not be accessible from anywhere else

warm elbow
#

Moreover, can I use the variable as condition for a repeat-while loop?

obtuse zephyr
#

Is the event the one triggering the automation?

#

All that info is in the docs I linked: The variables action allows you to set/override variables that will be accessible by templates in actions after it.

warm elbow
# obtuse zephyr Is the event the one triggering the automation?

Yes, I have a remote with different events for short press and long press. For a long press I want to create a template sensor, that is set to one when the long press starts and set to 0 when the button is released. I then want to hard-code a repeat-while into the blueprint that repeats while the template_sensor is 1

sonic nimbus
#

{{ as_timestamp(states.input_datetime.stefan_iphone_at_home.state) - as_timestamp(now()) < 10}} my helper here is 29-01-2023 00:00 why this condition returns True now() is 29-01-2023 6pm ?

#

I think I need |abs

obtuse zephyr
#

Also.... states('input_datetime.stefan_iphone_at_home') instead of states...

obtuse zephyr
warm elbow
obtuse zephyr
#

I'm not really familiar with blueprints, but I had thought the action section at least was like any other script. You could try #blueprints-archived to see if they have any ideas

sonic nimbus
solemn frost
#

Depending on what you're trying to accomplish, just using a zone trigger with for: could be simpler

dull burrow
#

https://imgur.com/a/6pHr36K i'm trying to return true or false for screen_on in this template and could use a pointer in the right direction

#

i've tried yaml {{ state_attr('media_player.master_tv','adb_response')['screen_on'] }} and it fails with UndefinedError: 'str object' has no attribute 'screen_on'

obtuse zephyr
#

I'd imagine it's due to it not always being a dict, only after you issue that particular command

dull burrow
#

i'm told this is the wrong way but it's currently working: yaml {{ state_attr('media_player.master_tv', 'adb_response').split(',')[1] == " 'awake': False" }}

uncut eagle
#

So I have some Zooz Zen76 on/off switches on exterior LED lamps that also have a light sensor (dusk to dawn) that prevents the light from turn on during the day. This circuit is confusing the Zooz, so when I tell the light to turn OFF, it's actually reporting OFF and lamp is ON. Zooz admits their firmware is fooled by these fixtures and doesn't recommend using them. But I have them installed, everything works otherwise.

I'd like a bandaid to invert the logic on the switch. Is the best way to use a template? Any examples?

obtuse zephyr
obtuse zephyr
dull burrow
#

basically i'm turning a tv on and starting a "goodnight routine" but the tv doesnt always show the proper state right away (such as off/shutdown) so the docs say to use adb GET_PROPERTIES to force update and act on those new values

#

https://dpaste.org/hb23b this is my full automation currently. i've added a couple delays because it seemed to fail without them (one for the updated values to populate and one for plex to launch before starting the playlist)

dull burrow
uncut eagle
obtuse zephyr
dull burrow
#

That’s what I thought too… smile except you used the right words to describe it

#

So as long as my way works, yolo?

obtuse zephyr
#

Yeah, I mean.... it's hacky, but I'd use it too since there doesn't seem to be a reasonable way to convert it sensibly. You could use regex but it'd be even worse to look at and not any less brittle

dull burrow
#

There’s a linked open issue going back to October with no solution either just workarounds

obtuse zephyr
#

That's a better solution than what I have for turning on my FireTV w/ WOL.... I just insert a delay and assume its on 😆

dull burrow
#

@inner mesa when searching here I see you also have a shield and automate with adb. Did you run into this issue, and if so, any better resolution?

inner mesa
#

I don't look at the adb_response for my stuff

#

I just pay attention to the states of the things that I'm controlling

dull burrow
#

the lack of updating of said states is the issue i'm having to solve

#

if i turn the tv off / make shield sleep it doesnt say it's off

#

and if it does, it doesnt do it 100% of the time

inner mesa
#

yes, I had issues with the states updating, so I found my own solution that I integrated into the "custom" AndroidTV integration, but the stock one is working for me now

dull burrow
#

seems to stem from this

inner mesa
#

mining that information is a complete pain in the ass

dull burrow
#

yeah

inner mesa
#

he was clearly doing it wrong when I first looked into it (grabbing the first window) and fixed that myself

dull burrow
#

i'm only using it for is the screen on or off (old tv so cant do it via the tv integration itself)

inner mesa
#

I wrote up a detailed post in one of those issues

#

what was wrong, why, how I fixed it

dull burrow
#

what's your github user so i can search it easier?

dull burrow
#

cries in advance then dives in

inner mesa
#

you can test everything it's doing from the command line using adb

#

it's just byzantine trying to walk through the code where he pieces things together to construct the command

#

I didn't look at what they did in the recent HA versions, but I don't have the problem anymore and I've removed the custom component

dull burrow
#

are you using automations relying on the screen or shield to be on/off?

#

i use hdmi-cec and the whole reason i ended up here is i couldnt rely on the state to be on/off for me to turn tv on to then start the playlist playing

inner mesa
#

no, I don't do any of that

dull burrow
#

it works fine if i can assume or know the tv is on or off, because then i can just do a simple power command with the shield and it turns the tv on then do the rest of the automation. i ran into scenarios where tv was on (didnt turn off when shield slept) and then when the command is ran, tv turns off while plex app launches and starts playing the playlist lol

#

anyways i'll read through your stuff and post to #automations-archived if there's an update, otherwise at least mine worksTM for now

#

thanks for the input

#

btw are you on android 12 (latest stable) now?

inner mesa
#

Whatever the latest shield release is

#

All the release numbers are very confusing

dull burrow
#

12 is when they introduces the unremovable ads on lockscreen

#

hard to miss 😭

#

i looked into using custom launchers but they're either too basic or too complicated to set up on each tv

inner mesa
#

I have those

dull burrow
#

it's apparently forced on nvidia from google to use android 12 per forum posts/comments 😭

uncut eagle
# obtuse zephyr Hmm, maybe a template switch or template light to just call the opposite service...

I added this to my configuration.yaml, seems to work. Getting a bit of bounce on the feedback (when I turn switch off, it indicates OFF, then indicates ON for a sec, then OFF again).

switch:
  - platform: template
    switches:
      den_door:
        friendly_name: "Exterior Den Door Light"
        value_template: "{{ is_state('switch.inv_exterior_den_door_light', 'off') }}"
        turn_on:
          service: switch.turn_off
          entity_id: switch.inv_exterior_den_door_light
        turn_off:
          service: switch.turn_on
          entity_id: switch.inv_exterior_den_door_light
marble jackal
#

To chip in on the Shield discussion, I have reliable states as well on Android TV 12 and the standard Android TV integration.
I only have problems when for some reason the cabled connection is failing and it switches to WiFi

sonic ember
#

Short template question I can't find a solution to online... I have template in an automation as a service call action:
temperature: "{{ states('input_number.living_room_home_temperature') | float }}"

Where would I put a conditional in the template? Simply everything between the "" ?

#

so temperature: " >
{{ if...
{{ states(...
{{ endif
"
?

#

I know quotes are needed for single line templates, but does that mean they are not needed for multi-line?

rose scroll
#

If you do a multiline template, you use > and no quotes.

#

And {{ is for Jinja statements that print the outputs. For statements that execute logic like if...elif...else...endif, you need {%.

sonic ember
#

Yeah I'm outputting a number entity

#

Ah thanks, let me test it quick...

rose scroll
#

You'd probably need:

{% if... %}
  {{ states(...) }}
{% endif %}

Pay attention to the bracketing.

sonic ember
#

Think I have it set up correctly, no errors at least. let's see when the automation runs if it works log-wise...

data:
  temperature: >
    {% if states('schedule.home') == 'off' %} {{
    states('input_number.living_room_low_temperature') | float }} {% else %} {{
    states('input_number.living_room_home_temperature') | float }} {% endif %}
#

HA changed the line breaks, I had them correctly! 😄

outer socket
#

Rest sensor, multiple values help 🙂
I'm trying to get this data https://pastebin.com/9thZ99PH into a sensor. I would then iterate over the sensor and add individual items to a shopping list on Microsoft ToDo.

#

Testing, using this command gives a response like from the pastebin
curl -k "https://tr.micro/api/shopping-list-entry/?format=json" -H 'Authorization:Bearer tda_eda44ac8_a65e_431e_95ad_16655cf5c688'

#

Furthermore, the log tells me the json is not formatted as a dictionary

#

Am I misunderstanding what can be done with my rest-sensor or am I simply doing it wrong.
I would like to extract name of the ingredient and amount needed and collect them as one attribute for each ingredient in the json.

grizzled grove
#

What's the best approach to include decimal values, if a state_attr comes like: XX.XX, instead of XX.

#

For instance, in a template such as:

#
      value_template: >
        {% if state_attr('weather.home_2', 'temperature') == 0.01 %}
          0.6117
        {% elif state_attr('weather.home_2', 'temperature') == 27 %}
          3.5681
        {% elif state_attr('weather.home_2', 'temperature') == 28 %}
          3.7831
        {% else %}
          ND
        {% endif %}
#

...and the value is ex: 27.8 or 27.82

grizzled grove
#

Hmmm...

#
        {% if state_attr('weather.home_2', 'temperature') <= 0.9 %}
          0.6117
        {% elif state_attr('weather.home_2', 'temperature') <= 1.9 %}
          0.6571
        {% elif state_attr('weather.home_2', 'temperature') <= 2.9 %}
          0.7060
        {% elif state_attr('weather.home_2', 'temperature') <= 3.9 %}
          0.7581
        .......
#

Seems to have done the trick.

ripe steeple
#

Heyo, I'm stuck trying to solve an problem. I do my testing in template editor under developing tools..
Trying to learn how to remove an item from a list by index. The editor screams at me that it's an unsafe way

How do I perform a remove from list in a safe manner?
{% set x=['a' , 'b' , 'c' ] %}
{{x.remove[0]}}

mighty ledge
#

you can't you have to filter

#

or slice

#

x[1:]

#

slicing -> x[1:], filtering -> x | reject('eq', 'a') | list

#

there's also a slice function

#

but you can't adjust memory without namespace, and namespace does not have a way to remove things.. that I know of

#

just checked, you cannot remove thigns from list even with namespace

ripe steeple
#

Thanks slice is perfect 🙂

Will store value in input_text. Retrieve, process first item, slice rest and store rest for next use

ripe steeple
#

Follow up if you will.

Why does the following return a list of numbers instead of a string without the 1.

{% set x= ("1,2,3").split(",") %}
{% set y = x[1:] %}
{{y|join(",")}}

#

With the slice I get

[
"2",
"3"
]

Then I want it to string as in "2,3"

But join makes it
[
2,
3
]

#

Ah ok it's the comma separation that ruins it

#

Tried another character then it worked

inner mesa
#

I think it's also a case of the dev tools interpreting the text result

#

it will probably return text if used elsewhere

ripe steeple
#

Oh alright makes some sense. Thanks. Now I can automate room-queue handling by voice commands for my vacuum