#templates-archived

1 messages · Page 149 of 1

unreal merlin
#

I've got as far as expand(states|selectattr('domain','in',['sensor']) |selectattr('attributes.device_class', 'eq', 'illuminance') |selectattr('entity_id','in',area_entities('Front porch'), but a bit stuck with adding multiple areas syntax wise

#

'entity_id', 'in', (area_entities... , area_entities) doesn't seem to work - what's the best way around this?

#

I've got: arming_time: 120 (this is the time allowed to leave the perimeter, e.g. in 120 seconds, alarm will be fully on). delay_time: 120 (the time you have to disarm (e.g. put in code) before full fledged alarm. I also have trigger_time: 600 on my end, 10 mins after the party starts, no1 cares anymore, so stop annoying the world.

#

All that looks like you're missing the " for the template, e.g. arming_time: "{{... Fixing that will reveal you'll need 'HH:MM', 'HH:MM:SS' as format for the value there, so your input number may to be "timeformed". Something like {{ '%02i:%02i:%02i'%(m/60,m%60,(60*m)%60) }} would work, where m is your input_number

regal temple
#

You made my day!!! Thanks. I am such a noob, not knowing I have to quote it... And piping this info into the calculation would be done like this: arming_time: {{ states('input_number.arming_time_zone1') | %02i:%02i:%02i'%(m/60,m%60,(60*m)%60) }}?

unreal merlin
#

{% set m=states('input_number.arming_time_zone1') %} {{ %02i:%02i:%02i'%(m/60,m%60,(60*m)%60) }} and see if it shows what it should be. Tricky as the documentation says arming_time integer (optional, default: 60) The time in seconds of the ‘arming’ state before effecting a state change.

velvet pawn
#

Does anyone have a guide that lists the templates for apple watch complications?

#

I know home assistant has a website dedicated to the Apple Watch Complications...but it's not exactly beginner friendly?

#

I don't mind doing reading/studying.

inner mesa
#

All templates are just Jinja

silent barnBOT
velvet pawn
#

@inner mesa for sure, im a newb programmer. I have some basic javascript and python under my belt

#

@inner mesa thanks for sending the site!

regal temple
#

Still out of luck... I can't get the template to render the time format. I am afraid this is out of my league. I tried to avoid this by using an input_datetime instead: "{{ states('input_datetime.arming_time_zone1') }}"I assigned it with the value of 00:00:30 but the config check still complains it needs a time formatted value. Turning it into a string also did not do the trick. "{{ states('input_datetime.arming_time_zone1') | string }}"

inner mesa
#

Because all states are strings

floral shuttle
#

is this the best way to cut the phrase from all 3 sensors? couldnt find a way to do it in the main bit per entity: {{(expand(state_attr('binary_sensor.flood_alert','entity_id')) |selectattr('state','==','off')|map(attribute='name')|join(', \n')) |replace(' flood sensor: Water Alarm - Water leak detected','')}}

#

seems to work. without the |replace is returns:Attic flood sensor: Water Alarm - Water leak detected, Attic heater flood sensor: Water Alarm - Water leak detected, Garage flood sensor: Water Alarm - Water leak detected and after adding that, is returns Attic, Attic heater, Garage

mighty ledge
#

yeah, that's probably the easiest

#

I dont see any benefit to changing it

floral shuttle
#

could it be done 'inside' the main structure? or would that require a ns construction...

#

btw, I just found out that these binary sensors, of platform group can be used in an auto-entities card with filter group: so that makes life so much easier 😉 and now I have an entity with unique_id (used groups for this before), which is another advantage. Iterating them is easy too, so a real cool addition, dont understand how I missed that...

#

anyways, thanks for confirming.

silent mulch
#

Hello. I think what I'm trying to do is add a "custom card". I'm looking for the www directory for HA. Where is it?

mighty ledge
#

I guess I don't follow what you mean

floral shuttle
#

Before I used regular groups but only yesterday discovered binary_sensor platform:group

#

And you can use these in an auto-entities card in filter: group

#

Even though it’s a binary_sensor 😉

mighty ledge
#

hmm, must be new

#

or newer, never heard of it

topaz galleon
#

I am trying to configure a Water Meter as a MQTT sensor. It reports in thousanths of a m3 (eg 193102 = 193.102m3) How do I represent that in my sensor config?

#
  • platform: mqtt
    name: Water Meter
    unique_id: meter_water
    state_topic: "rtl_433/9b13b3f4-rtl433/devices/SCM_/XXXXXXXX"
    unit_of_measurement: m³
    value_template: "{{ value_json.Consumption }}"
#

Is it as simple as value_template: "{{ value_json.Consumption * 0.001 }}"

inner mesa
#

What does that topic contain?

topaz galleon
#

103102 right now

inner mesa
#

That's it?

topaz galleon
#

Do you mean all of the other values?

inner mesa
#

Where did 'Consumption' come from?

#

The contents of that topic

topaz galleon
#

Ahh. rtl_433. It's read straight from my meter.

#

time = 2022-02-06 15:57:11
id = 75485917
ProtocolID = 0x1E
EndpointType = 0xAB
EndpointID = XXXXXXXX
Consumption = 193102
Tamper = 0x4900
PacketCRC = 0xAEA7
MeterType = Water
mic = CRC

inner mesa
#

Just like that?

topaz galleon
#

Yup

inner mesa
#

That's not JSON

topaz galleon
#

That's what MQTTExplorer renders it as.

inner mesa
#

You can't parse that as JSON

topaz galleon
#

{"time":"2022-02-06 15:56:11","model":"SCM+","id":XXXXXXXXX,"ProtocolID":"0x1E","EndpointType":"0xAB","EndpointID":XXXXXXXX,"Consumption":193102,"Tamper":"0x4900","PacketCRC":"0xAEA7","MeterType":"Water","mic":"CRC"}

inner mesa
#

That's JSON

topaz galleon
#

You think?

inner mesa
#

I do

topaz galleon
#

You weren't specific when you asked me for the contents of the topic. I gave you human readable.

inner mesa
#

It's all about how it's parsed

topaz galleon
#

David defaults to -h

inner mesa
#

You asked how to parse it

#

What you wrote should work

topaz galleon
#

How can I make 193102 into 193.102

#

I'll try restarting. Nothing changed.

#

Even after reloading MQTT sensors

inner mesa
#

It may need to update

#

But check the HA logs

topaz galleon
#

It is either being ignored or it's not working. Nothing in the logs.

#

Could it be a casting issue?

#

int to float?

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

topaz galleon
#

Did do that.

#

Oh I didn't do that. I trusted the UI check.

formal ember
#

can you do multiple calcuations in a template sensor? i.e.

{{ states('sensor.gamingrig_smartplug_energy_power') | (float * 24) / 1000 | round(2) }}

inner mesa
#

(float * 24) doesn't make sense

#

And you're rounding 1000

formal ember
#

ok, trying to multiply it by 24 and then divide by 1000

inner mesa
#

{{ (states('sensor.gamingrig_smartplug_energy_power') | float * 24/ 1000) | round(2) }}

formal ember
#

thank you very much - i see how it should be set out now!

blazing burrow
#

is there any way to check for a file's existence via a template? or other sensor?

#

basically, i have a folder of thumbnails, but some are jpg and some are png, so i want to use whichever one exists based on a template

#

i'm using this for a thumbnail of game being played on my quest, which reports a package name

#

and i have a folder of games, named by package, but with different extensions

#

got it working for jpg ones, but not for both

#

was thinking something like "if jpg doesn't exist, then png"

#

found a topic suggesting the filesize sensor, but it doesn't support templates

#

and i've currently got this:

sensor:
  - platform: template
    sensors:
      last_quest_app:
        friendly_name: Last Quest App
        value_template: "/local/quest/thumbnails/{{ states('sensor.quest_last_used_app') }}.jpg"
silent barnBOT
blazing burrow
#

does that support a template?

#

or work with an image?

#
sensor:
  - platform: file
    file_path: "/local/quest/thumbnails/{{ states('sensor.quest_last_used_app') }}.jpg"

Invalid config for [sensor.file]: not a file for dictionary value @ data['file_path']. Got "/local/quest/thumbnails/{{ states('sensor.quest_last_used_app') }}.jpg". (See ?, line ?).

#

i think not 🤔

silent barnBOT
floral shuttle
rotund hazel
regal temple
bright plaza
#

can anyone help me extract an ip address from a string? The string is formatted like this /ip4/1.2.3.4/tcp/12345

#

I'm trying to set it as part of a rest sensor value_template: "{{ value_json.data.status.listen_addrs[0] }}"

bright plaza
#

Thanks 👍

#

needed one / not two but you got me there

tulip harness
#

Hi, it is possible somehow get more info about log errors? For example I got errors like this: 2022-02-07 12:37:29 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'Occupancy' when rendering '{{ value_json['0x537D'].Occupancy }}' but I need some more info like what entity, what mqtt message fire this error ?

mighty ledge
#

You can put mqtt's log level in debug and see when the error occurs by watching the logs. Otherwise templates have no context of the field in which they reside. I.e. they can't trace themselves back to an entity.

tulip harness
mighty ledge
manic onyx
#

hi everyone. How do I compare the max value of all sensors of set type? Like I want to change button color based on an max value of all CO2 sensors in a house. Say, if one room is above 1000, but others are below, I want the button to be amber/red. When I click the button it will take me to the CO2 page with all CO2 sensors

spare summit
marble jackal
#

@spare summit something like this?```jinja
{% set x = 5 %}
{{ state_attr('climate.general_thermostat_v2_mode', 'temperature') | float + x }}

spare summit
#

action:

  • choose:
    • conditions:
      • condition: trigger
        id: '1'
      • condition: template
        value_template: >-
        {% set x = 5 %}
        {{ state_attr('climate.general_thermostat_v2_mode', 'temperature') | float + x }}

Would it be correct to use it likes this @marble jackal

mighty ledge
marble jackal
# spare summit > action: > - choose: > - conditions: > - condition: trigger >...

You are now defining a condition, I don't think you want that.
You should use what you had.
And you can also immediately use the number instead of first setting it.

          - service: climate.set_temperature
            data:
              temperature: "{{ state_attr('climate.general_thermostat_v2_mode', 'temperature') | float + 5 }}"
            target:
              entity_id: climate.general_thermostat_v2_mode
#

But you only said you wanted to increase it with x

marble jackal
mighty ledge
#

glossed over it

#

However, I would still change the template

manic onyx
#

@mighty ledge @marble jackal - template that @marble jackal suggested works fine, apart from that I cannot get to work with the button-card 😦

mighty ledge
#

If you using the built in card, you can't template in that

#

if you're using the custom-button-card, that uses JS templates

manic onyx
#

yeah, using a custom one. Is JS template different? 🙂 sorry

spare summit
marble jackal
#

@spare summit Yes

          - service: climate.set_temperature
            data:
              temperature: "{{ state_attr('climate.general_thermostat_v2_mode', 'temperature') | float + states('input_number.your_input_number') | float }}"
            target:
              entity_id: climate.general_thermostat_v2_mode
manic onyx
#

ok, ended up creating a template sensor and then using it with JS templates

marble jackal
mighty ledge
#
{{ states.sensor | selectattr(...) | selectattr('state','is_number') | map(attribute='state') | map('float') ...
#

to avoid default

marble jackal
#

ah nice

#

I missed that one, but that is a really good addition!

#

Well, I glossed over it, and though something like "| is_number was already existing, right? Maybe the forgot to mention it that time"

mighty ledge
#

yeah it was a filter, but not a test

#

i.e.

#
{{ '1' | is_number }}
#

returns true

#
{{ '1' is is_number }}
#

would fail

#

now it works

#

the benefit of it as a test is that you can now use it for selectattr etc

#

in the context above, it's pretty stupid

marble jackal
#

👍🏼

mighty ledge
#

by that i mean '1' is is_number context

marble jackal
#

I understood

#

Already figured out how to proceed on the test where you can cast an (attribute) state directly?

mighty ledge
#

no, if you're talking about what I posted a week or 2 ago

peak juniper
#

evening all! I seem to have missed when template sensors changed from platform: template to just template and I'm struggling to figure out how to reconcile the yaml whilst adding a new one with the new format

silent barnBOT
peak juniper
#

oops! Forgot it was over the limit

#

the -platform: template ones are fine and I'm trying to add in the new template: trigger one

#

any ideas where I'm going wrong with my indentation?

#

these are in a referenced sensors.yaml file

mighty ledge
#

your spacing is off

#

also, you don't need the trigger

peak juniper
#

I am trying to create a template sensor that will record the difference in a sensor value between what it was and what it has changed to

#

e.g. if sensor value changes from 40 to 50, then template sensor will record a value of 10

marble jackal
chilly ferry
#

is there any equivalent for the for used in conditions and triggers but inside a template?

mighty ledge
chilly ferry
mighty ledge
#

the example will depend on the source, it'll be different for most things

chilly ferry
#

it's based on a binary sensor

mighty ledge
#

trigger? condition?

chilly ferry
#

I'm trying to build another binary sensor based on it

#

(template binary sensors)

mighty ledge
#

I guess I need more of an explanation, because template sensors can be based on regular triggers

chilly ferry
#

sure

#

I have this one created:

- trigger:
    - platform: device
      device_id: b7de8cf77a53d4b9d2301145a884dcbc
      domain: nest
      type: camera_person
  binary_sensor:
    - name: 'Front door person detected'
      state: 'on'
      auto_off: 5
silent barnBOT
mighty ledge
#
- trigger:
  - platform: template
    value_template: "{{ all that crap }}"
    for:
      minutes: 5
  ...
chilly ferry
#

umm but that minutes condition it's only in one particular case, I was trying to cover more cases under the same sensor

mighty ledge
#

so states('binary_sensor.front_door_person_detected') off for 5 minutes?

chilly ferry
#

yes

mighty ledge
#

you have to get the state object

#

{% set bs = expand('binary_sensor.front_door_person_detected') | first %}

#

then you compare the current state against when it was last updated

#

(bs.last_updated - now()).seconds > 5 * 60

chilly ferry
#

nice thanks!

#

where could I find the interface of this objects?

#

usually I go to the dev tools and check the attributes they have, but didn't know about this last updated and whatnot!

marble jackal
#

It's also there, but it's not an attribute

#

So depending on the screen size they are shown right of, or below the attribute part.
But you could als put something like {{ expand('binary_sensor.front_door_person_detected') | first }} in devtools > templates, and see what is available

chilly ferry
#

Yeah that's what I did to explore it a little bit

mellow pulsar
#

Greetings! Is it possible to use a template to set an input_number? I am trying to define the variable input_number.temperature from an MQTT message rather than having to define it in configuration.yaml.

inner mesa
#

Yes, you can set the value:

silent barnBOT
inner mesa
#

Anything value under data: can be templated, and the payload from an MQTT trigger is available for that

mellow pulsar
#

thanks. I have it triggering on the MQTT message, Does the Payload(optional) field get the infor like this?

#

'{{ value_json.tempf if value_json.chan == 1 else states("sensor.outside_temp") }}'

#

for the given topic i want to subscribe to

#

that was what i used when i did the equivalent in configuration.yaml

#

the value in states would be ("input_number.temperature") if the helper is the same name I imagine?

inner mesa
#

There's an MQTT example toward the bottom

mellow pulsar
#

@inner mesa how would that be applied if I was trying to put that in the automation form? The terminologies are not lining up for me to apply what would be in configuration.yaml with the automation form. Or should i just give, and put it in configuration.yaml

inner mesa
#

see the example at the bottom of that page

#
automation 2:
  trigger:
    - platform: mqtt
      topic: "/notify/+"
  action:
    service: >
      notify.{{ trigger.topic.split('/')[-1] }}
    data:
      message: "{{ trigger.payload }}"
#

your service is input_number.set_value

#

there's an example in the input_number docs that shows how to call that

mellow pulsar
#

gotcha.... So it has to be done in configuration.yaml then... when I get to that point in the create automation form, the form only allows me to put a number in, and thats it... has to be hardwired in the automation form of the gui

inner mesa
#

It's an automation, so it goes where other automations go. that's probably automations.yaml if you're doing it with the UI, which is fine

#

no reason you can't do that in the UI

mellow pulsar
#

well.. I probably can if i edit it in yaml on the GUI. won't let the value be anything other than numeric... any other characters such as {{ to start a template are ignored

#

darn.. 🙂 I was hoping the gui would let me do such!

peak juniper
#

Evening all! Can anyone help explain what's wrong with the following:

  - platform: template
    trigger:
      - platform: state
        entity_id: sensor.starling_current_balance
    sensor:
      - name: "starling_balance_change"
        state: >
          {% set delta = trigger.to_state.state | float - trigger.from_state.state | float %}
#

I'm having some issues with my config not liking it

inner mesa
#

You didn't output anything

#

The whole thing is just jumbled.

peak juniper
#

ah, I have a load of template sensors using that old format (didn't even realise it changed). Do I need to change ALL my old template sensors in order to use the new format or can I mix n match?

inner mesa
#

No

#

You can use both, just pick one for a given sensor

peak juniper
#

ok, so I'm trying to create a sensor that will store the difference between the old and new value of another sensor when it changes

teal umbra
#

Can anyone tell me why {{ as_datetime((as_datetime(state_attr('timer.leaving', 'finishes_at')) - now()).seconds).strftime('%Hh %Mm') }} giving me this message TypeError: float() argument must be a string or a number, not 'NoneType'

shadow walrus
#

Hey guys im having trouble with a template sensor(i have no idea what i am doing). Heres what i have. It yields a result but not the right result. https://pastebin.com/twa2qNRA Im subtracting 2 numbers of ~ 60, the result should be close to zero or negative but is often close to one of the sensor values.

#

Any ideas?

marble jackal
marble jackal
marble jackal
peak juniper
#

Ah thanks. I appreciate that bit of info. I guess it’s just trial and error to work out the right indentation then

marble jackal
#

@peak juniper Just follow the example or the docs. But do note that this falls under thetemplate integration and not under the sensor integration. So if you place this in sensor.yaml it won't work

peak juniper
#

Oh my god! That’s it. That’s what I was doing wrong. I’ve been putting it in my sensors.yaml. Thank you so much!

supple radish
#

Hi Guys,
I have the script below. This was working well before 2022 update...
Do you know if something change with entity_id: all ?

#
service: light.turn_off
data: {}
target:
  entity_id: all
tidal heart
#

How can I make a input_datetime time to output without seconds? states('input_datetime.sleeping_finn_3') outputs hh:mm:ss I want it in hh:mm

marble jackal
tidal heart
marble jackal
#

whoops, replace the input_datetime with yours 🙂

marble jackal
onyx juniper
#

Hi guys,
I'm trying to create a temperature sensor that is just the average of two others. It kind of works. Though it doesn't show °C as the unit of measurement like a "normal" temp sensor does.
The unique ID is there because I wanted to assign it to a room (which worked) to then be able to integrate the sensor with the Google Assistant integration (which didn't work. I just doesn't show up in the list of stuff I can enable for Google Assistant).

bad_unten_durchschnitt_temp:
      friendly_name: "Badezimmer unten"
      unit_of_measurement: "C"
      unique_id: "c3fcc526e167dfe869e94eb2592013b5e08281c1def8e504de33651d92ccfdf2"
      value_template: >
        {% set temp1 =  states('sensor.bewegung_badezimmer_unten_temperature') | float %}
        {% set temp2 =  states('sensor.fenster_badezimmer_unten_temperature') | float %}
        {{(temp1+temp2) / 2}}

Any idea on how to solve these 2 problems?

marble jackal
#

Well, it doesn't show °C as unit_of_measurement because you did not add °C as unit_of_measurement. You added C

#

you also could add device_class: temperature so it is recognized as a temperature sensor

#

and you could rewrite your template to this, so it will also work if one of them is not available

{% set temp_sensors =  [ 
                        'sensor.bewegung_badezimmer_unten_temperature',
                        'sensor.fenster_badezimmer_unten_temperature'
                       ]
%}
{{ expand(temp_sensors) | map(attribute='state') | select('is_number') | map('float') | average }}
manic onyx
#

hi everyone. Can someone please tell me why automation does not like my formatting?

action:
scene:
"{% if is_state('input_select.main_ac_action', 'Turn off') %} scene.aicon_turn_off
{% elif is_state('input_select.main_ac_action', 'Turn on cool 24C') %} scene.aircon_cool_to_24degc_on_low
{% elif is_state('input_select.main_ac_action', 'Turn on heat 24C') %} scene.aircon_heat_to_24degc_on_low
{% endif %}
"

marble jackal
#

Because you should remove the double quotes, and add an > if you use a multi line template.
And next time please format your code as code 👍

  action:
    scene: >
      {% if is_state('input_select.main_ac_action', 'Turn off') %} scene.aicon_turn_off
      {% elif is_state('input_select.main_ac_action', 'Turn on cool 24C') %} scene.aircon_cool_to_24degc_on_low
      {% elif is_state('input_select.main_ac_action', 'Turn on heat 24C') %} scene.aircon_heat_to_24degc_on_low
      {% endif %}
silent barnBOT
#

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

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

manic onyx
#

it is complaining that string does not match a pattern for scene

#

also, interesting that it converted my code I put for another automation few days back. From this

 action:
    service: >
      {% if is_state('input_select.vacuum_room_selector', 'Random zone') %} script.robo_vacuum_random_zone
      {% elif is_state('input_select.vacuum_room_selector', 'Main zones') %} script.viomi_vacuum_main_zones
      {% elif is_state('input_select.vacuum_room_selector', 'Front Corridor') %} script.viomi_vacuum_front_corridor
#

to this:

  action:
    service:
      "{% if is_state('input_select.vacuum_room_selector', 'Random zone') %}\
      \ script.robo_vacuum_random_zone {% elif is_state('input_select.vacuum_room_selector',\
      \ 'Main zones') %} script.viomi_vacuum_main_zones {% elif is_state('input_select.vacuum_room_selector',\
      \ 'Front Corridor') %} script.viomi_vacuum_front_corridor {% elif is_state('input_select.vacuum_room_selector',\
marble jackal
#

The GUI does that, but actually the added \ make sure that this does work

#

But anyways, you can not activate a scene like you are tryint to do

#

you need to use service.scene_turn_on

#
  action:
    service: scene.turn_on
    target:
      entity_id: >
        {% if is_state('input_select.main_ac_action', 'Turn off') %} scene.aicon_turn_off
        {% elif is_state('input_select.main_ac_action', 'Turn on cool 24C') %} scene.aircon_cool_to_24degc_on_low
        {% elif is_state('input_select.main_ac_action', 'Turn on heat 24C') %} scene.aircon_heat_to_24degc_on_low
        {% endif %}
manic onyx
#

I just went by the example of manually creating an automation with a selected scene and tried adding extra code 🙂

marble jackal
#

I could not find that way of applying a scene in the docs, but that way probably does not accept templates.

#

target does

manic onyx
#

thank you again! 🙂 just when I think that I start to get the hang of working things out, I get to something stupid easy like that that breaks me 🙂

onyx juniper
sick haven
#

Hello, Did you know why this works : {% for entities in states -%} {% if entities.entity_id is search("72_weather_alert", ignorecase=False) %} {{ entities }} {%- endif %} {%- endfor %}and this {{ states.sensor.72_weather_alert }} return me : TemplateSyntaxError: expected token 'end of print statement', got '_weather_alert'
Or how to make it work ?

marble jackal
#

@sick haven Because your sensor object id starts with a number.

#

{{ states.sensor['72_weather_alert'] }} should work

sick haven
#

Thanks you so much. To far on the page 😅

marble jackal
#

I must admit that I knew it was in there somewhere, and searched for number, and then indeed found it all the way at the end 🙂

sick haven
#

Ok 🙂 i thought search for "_" ...

mighty void
#

I'd like to make an Mqtt sensor. The two values the topic returns is -1 (on) and 1 (off). I'd like the sensor to show 'on' and 'off' values rather than -1 and 1. How do I modify the sensor to display that. HA didn't like payloads for sensors

  - platform: mqtt
    name: "TV - Power"
    state_topic: "/remoteapp/mobile/broadcast/platform_service/data/picturesetting"
    value_template: "{{ value_json.menu_info[10].menu_flag }}"
    payload_on: "-1"
    payload_off: "1"
buoyant pine
#

Make it an MQTT binary sensor

mighty void
#

@buoyant pine that makes sense, thank you!

fallow gulch
#

Hi - bit of a simple question. I'm pulling in a numerical UV value from my weather station via MQTT. HA doesn't seem to be interpreting this as a number though. Here's the config entry for the UV template sensor:

#
  name: "UV Index"
  state_topic: "weather/UV"
  icon: mdi:sunglasses
  value_template: "{{ value | round(1) }}"```
#

should I be using float instead of value?

buoyant pine
#

You need to define a unit of measurement with the sensor (could be anything, including just 1

fallow gulch
#

UV Index is a weird one - doesn't really have a unit of measure as such

#

I think officially each UV Index increment is 25 mW of UV per m2

#

I've assigned it something and it's graphing properly now, thanks!

mighty ledge
inner mesa
#

I think even a space will do it

mighty ledge
sly quiver
#

Does anyone know of a good thermostat template I can use for my broadlink controlled A/C the issue I have is, there are individual or codes for each degree of temperature so a simple up or down wouldn't work.

#

For Lovelace

shy maple
#

Hi all! I'm trying to get the icon of a command_line sensor to change with it's state. But i won't get it to work. Searched the community but still no joy. Can someone help me please?

#

i have this in my configuration.yaml:

- platform: template
  value_template: states('sensor.buiten_camera_01_motion')
  name: Buitencamera01_Motion_Display
  icon_template: "{% if is_state('sensor.buiten_camera_01_motion', 'Detected') %}mdi:motion- 
  sensor{% else %}mdi:eye{% endif  %}"```

And i am getting the error:
```Invalid config for [sensor.template]: [value_template] is an invalid option for [sensor.template]. Check: sensor.template->value_template. (See ?, line ?).```
fossil venture
shy maple
fossil venture
#

Did you restart after making the change?

shy maple
#

no i did the "check configuration"

#

The sensor is:

  - platform: command_line  
    command: curl -k --silent "http://X.X.X.X:XXXX/cgi-bin/CGIProxy.fcgi?cmd=getDevState&usr=XXX&pwd=YYY"
    name: "Buiten Camera 01 Motion"
    value_template: >
      {% set status = value | regex_findall_index('Alarm>(\d+)</motion') %}
      {% set values = {'0':'Disabled', '1':'Clear', '2':'Detected'} %}
      {{ values[status] if status in values.keys() else 'Not Determined'}}
    scan_interval: 5
#

would i be able to add the state dependent icon to the sensor itself?

marble jackal
plush willow
#

I'm trying to split up my template covers from the configuration yaml file to a seperate covers.yaml file

When I check my configuration by the system the gear is continuous turning round so something is I think not good

in my configuration.waml file:

cover: !include covers.yaml

#

the covers. yaml:

  • platform: template
    covers:
    master_bedroom:
    unique_id: "masterbedroom_rolluik"
#

what do I wrong?

inner mesa
#

It's an incomplete template cover

plush willow
#

yes I didnot have pasted everything

silent barnBOT
plush willow
#

I have 16 of such blocks

ashen isle
#

hi, want to generate a list of entities with a name filter on it. eg "{{ states.button | map(attribute='entity_id') | join(',') }}" gives me "button.shelly1_76771b_ota_update,button.shelly1_76771b_reboot,... but i only want to list all *_ota_update entities, but not the *_reboot ones.
can someone tell me how to filter all the entities additionally for a certain string, to do so ? thank you !

raw jay
#

Hello all, I'm trying to find a solution to filter the parent path of a value
I tried the filter "dirname()" but it doenst work on Home Assistant
Can anyone help me?

marble jackal
marble jackal
raw jay
#
ender3pro_parent_file_path:
        friendly_name: "File Parent Path"
        value_template: '{{ pathlib.Path(states.sensor.ender3pro_sensor.attributes["print_stats"]["filename"]) | dirname }}'

result = test/lala.stl

#

I need the "test" but this can be "test/test1/test2"

#

they are folders

#

i need the path of the file, without the filename

inner mesa
#
{% set path='foo/bar/blah.jpg' %}
{{ path[:path.rindex('/')] }}
#

-> foo/bar

raw jay
#

I can set the path you the states(sensor.ender3pro_parent_file_path) I supose

inner mesa
#

Not quite

raw jay
#

I need the result here:

/server/files/gcodes/{{ states('sensor.ender3pro_parent_file_path') }}/{{ states('sensor.ender3pro_object_thumbnails') }}
ashen isle
marble jackal
#

It can be done with one search I guess

raw jay
#

tried this

#

there are an error in the config

#

:\

ashen isle
#

oh, but update button is not working in the first place, right now 😄

inner mesa
raw jay
#
ender3pro_parent_file_path:
        friendly_name: "File Parent Path"
        value_template: '{{ states.sensor.ender3pro_sensor.attributes["print_stats"]["filename"].split("/")[:-1] }}'
```
#
/server/files/gcodes/{{ states('sensor.ender3pro_parent_file_path') | join('/') }}/{{ states('sensor.ender3pro_object_thumbnails') }}
#

still doenst work

#

its strange the value of the ender3pro_parent_file_path is like that ['test']

#

don't know why

#

if anyone have any hint I will appreciate

inner mesa
#

I gave you a solution for your initial problem. Did you requirements change?

raw jay
#

The solution you gave me, you told me I can't use a variable in the set value

#

Unfortunately I need to use the value of a variable

inner mesa
#

you can

#

you just have to use proper syntax

#

it seems like you went off in a completely different direction

#
{% set path='foo/bar/blah.jpg' %}
{% set dir=path[:path.rindex('/')] %}
{{ dir }}
#

like that?

raw jay
#

The path can be a variable?

#

ender3pro_parent_file_path

#

This one

inner mesa
#

anything can be a variable

raw jay
#

How can I set the path as the value from ender3pro_parent_file_path

inner mesa
#

my comment was that this won't work: states(sensor.ender3pro_parent_file_path)

#

I'm not following the confusion. You set variables just like I showed above

#

I'm not writing exactly what you should type in your editor, but trying to give you the tools

raw jay
#

As I'm new into this, for me is a little bit confusing.
To have the value of the ender3pro_parent_file_path, I need to use this: {{ states(sensor.ender3pro_parent_file_path) }}
But you tell me, I can't use it

inner mesa
#

you need quotes

#

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

raw jay
#

I've tried with quotes and got an error

inner mesa
#

oik

#

that will work fine

raw jay
#

But I can try again

inner mesa
#

you're passing a string that's an entity_id

#

yes, please do

#

if you actually have such an entity in your system

#

if you don't, then that's something you'll need to figure out

raw jay
#

{% set file_parent_path='{{ states('sensor.ender3pro_parent_file_path') }}' %}
{% set parent_path=file_parent_path[:file_parent_path.rindex('/')] %}
{{ parent_path }}

#

This should work?

inner mesa
#

you added more quotes

#
{% set file_parent_path=states('sensor.ender3pro_parent_file_path') %}
{% set parent_path=file_parent_path[:file_parent_path.rindex('/')] %}
{{ parent_path }}
#

and you were again nesting templates

#

it's one template

#

you see the issue here?

#

{% set file_parent_path='{{ states('sensor.ender3pro_parent_file_path') }}' %}

#

there are two problems there - you're trying to embed a template in a template, when you just need to call the function directly, and that aside, you were using the same quotes inside and outside. That can't be parsed

#

and again, it all assumes that you actually have entity with that name

raw jay
#

I tried with a different approach by adding the split (all the rest is the same), yes, but it doesn't work

inner mesa
#

alright

floral shuttle
#

with my Hue light groups, there is an attribute lights, containing the Names of the lights. I am trying to get that back to a list of entity_ids with this first attempt: {% set ns = namespace(ligths=[]) %} {% for l in state_attr('light.living','lights') %} {% set ns.lights = ns.lights + ['light.'~l|slugify] %} {% endfor %} {{ns.lights}} but get a UndefinedError: 'jinja2.utils.Namespace object' has no attribute 'lights' error...

#

while {% for l in state_attr('light.living','lights') %} {{'light.'~l|slugify }} {% endfor %} shows the attribute to be valid and creates a list with all entity_id's

#

what is my mistake....?

buoyant pine
#
{% set ns = namespace(ligths=[]) %}
                        ^^^
floral shuttle
#

its a dark theme I am editing in........ thank you very much!

#
{% set group = 'living' %}
{% set ns = namespace(lights=[]) %}
{% for l in state_attr('light.'~group,'lights') %}
{% set ns.lights = ns.lights + ['light.'~l|slugify] %}
{% endfor %}
{{ns.lights}}
``` for ease of re-use. Ofc this is a string manipulation, and my coding hart says it would be better to compare the Name list with `integration_entities(Philips Hue)` but I think that is way more complex...wait, thats not available at all hmm, maybe it can only be done like this.
floral shuttle
#

talking to Marcel (author Hue integration v2):{% set group = 'living' %} {% set ns = namespace(lights=[]) %} {% for x in state_attr('light.'~group,'lights') %} {% for y in expand(integration_entities('Philips Hue 1')) %} {% if y.attributes['friendly_name'] == x %} {% set ns.lights = ns.lights + [y.entity_id] %} {% endif %} {% endfor %} {% endfor %} {{ns.lights}} to be more robust, especially if you dont have identical names between integration and HA lights

#

both cases let you do things like ```{{expand(ns.lights)|selectattr('state','eq','on')|map(attribute='entity_id')|list}}

torn meteor
#

will states("sensor.gpu_temp") with an Unknown or Unavailable state count as False?

#

usually this is an int, but on my history graph it disappears when my PC is off

#

hard to tell what state it is in during that period, but I want to catch it

#

i was about to use this set is_on = states(sensor.gpu_temp) > 0

#

i was hoping non-numbers would cast as False

#

nevermind. this works best: is_number(states(sensor.gpu_temp)) (confirmed that when it's off it shows as "unavailable" but I like this method)

hot lodge
#

Has data_template been deprecated? Trying to create an intent for setting thermostat temperature, and examples are using date_template, but I'm seeing one thread that says to just us data now???

inner mesa
#

A year or two ago, yes

#

It's the 21st century

hot lodge
#

😋 Thanks, I'll give it a go with just using data.

marble jackal
#

Since when does integration_entities() exist?

#

Is was still using a template from @mighty ledge I found somewhere on the community forum

inner mesa
#

That's a thing? I know it's been a request

mighty void
#

I have an MQTT binary sensor that works ok. The one problem is that when I reboot HA, the sensor state will remain unknown until there is a published topic which is infrequent.

Send an Mqtt request to publish the topic, but would it be possible to have the sensor send the request?

#

*I can send an MQTT request to publish..

mighty void
#

Can an Mqtt binary sensor listen to two topics?

buoyant pine
#

Can you enable the retain flag on whatever is sending the MQTT payloads?

#

@mighty void

#

@🌮

mighty void
#

@buoyant pine thanks, yeah I was looking at retain as an option. But would only want retain true for this one senor, and not all my others. And I'm not sure I can set that limitation of I set retain true from the publisher

#

You know what, I think retain may be my best easiest option here, I'm in

trim oak
# raw jay I tried with a different approach by adding the split (all the rest is the same)...

I use this bit of code to check what my template are actually doing. This help me. YMMV

#     # DEBUG CODE DELETE
#     - service: persistent_notification.create
#       data_template:
#         title: "Occupancy ON Triggering"
#         # message: "Test Message"
#         message: "Triggered by input_boolean.{{ trigger.entity_id.split('.')[1].split('_', 1)[0] | lower }} now occupied"

I was pulling fields out of a motion sensor here. But getting the actual code up on screen in a notification may provide some insights

trim oak
fleet viper
#

trying to figure out why this is breaking and giving "Invalid Date".

        var statestr = states['input_datetime.attic_fan_turn_off_time'].state;
        //statestring = "2022-02-09 19:35:57"
        var date = new Date(statestr);
        return date
fleet viper
#

well nm, it seems touchy. any ideas?

marble jackal
raw jay
#

i solved my issue by doing this:

value_template: '{{ states.sensor.ender3pro_sensor.attributes["print_stats"]["filename"].split("/")[:-1] | join("/") }}'
#

tks all for your help

mighty ledge
marble jackal
#

Didn't look at the code, but I need it for cast entities, and that one is supported

mighty ledge
#

It won’t work for yaml entries basically

marble jackal
#

it also works for group

#

Hmm, and this {{ integration_entities('') }} returns sensor.hacs

#

And it also works for utility_meter, which is set up using yaml

dense sleet
#

hi there i had the following template sensor working but it somehow stopped working in the past. Could somebody please check what could cause the problem? the sensor gives me "unknown"

    - unique_id: karls_pc_uptime
      icon: mdi:update
      device_class: timestamp
      state: >
        {% set s = states('sensor.pc_uptime') %}
        {{ as_timestamp(strptime(s ~ "0", "LastBootUpTime             %Y%m%d%H%M%S.%f+1200")) | timestamp_custom("%Y-%m-%dT%H:%M:%S") }}
sensor.pc_uptime
state:
LastBootUpTime             20220210100830.500000+060

Thanks in advance

marble jackal
#

Does the state actually include the words LastBootUpTime and all these spaces?

#

And could you please format your code as code

silent barnBOT
#

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

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

dense sleet
marble jackal
#

While changing it, you removed a part of your template

#

Could you add that back? 🙂

dense sleet
mighty ledge
marble jackal
#

aaah 🙂

marble jackal
# dense sleet oups yeah sure i did.

Looking at your strptime function it seems to be expecting +1200 at the end, but it now shows +0600. Did you recently go from wintertime to summertime (or the other way round)

dense sleet
marble jackal
mighty ledge
#

| as_datetime | as_local

chilly ferry
#

how can I get the last_updated value for a group reporting home/not_home?
I've done if for other things with expand, but in this case I get every member of the group

mighty ledge
#

lastly, if that's a timestamp template sensor, you have to return a datetime object

#

days of returning a string are in the past on that one

marble jackal
outer socket
#

Hi all.
Trying to monitor if my server drops any disks - it's happened a couple of times. I have a bash_script I would run every 15_minutes which will output if any disks are dropped. the script writes a file with this format: $date;$disksDropped (where disksDropped is comma-separated).

Meaning I have the date of the scripts last runtime - and a value containing 1 or more dropped disks. This gives me a state in HomeAssistant which is currently - "data1,data5". How would I then split that state into multiple values so I can get a lovelace-line/entry for each dropped disk?

Or, is there another way of monitoring the amount of disks connected?

mighty ledge
#

well the strptime is pointless then

marble jackal
#

@mighty ledge do you have any idea when context changes? I'm trying to use it in a script, but it already seems to change when touched by a template

mighty ledge
#

the +60 is most likely minutes or seconds timezone offset

#

so, I'd wager that the template is already off

#

by 60 minutes or seconds

marble jackal
#

Yes, I also saw that, normally that should be +0100

mighty ledge
#

anyways, the context only changes when context is available, i.e. during automations or scripts

#

otherwise the context is empty in the normal state machine

marble jackal
#

Okay, but eg if I use states.media_player in an automation, the context of all media_players will change?

mighty ledge
mighty ledge
#

thats from the state machine

#

it'll have an empty context

#

if it's from a trigger, it'll have context

#

context is momentary

#

context is also passed through service call actions

#

like if you press the UI, it knows what user pressed the ui, in the service call

#

which is typically only accessable through state_changed events, or trigger objects

#

make sense?

#

basically, you have to make an automation or a template that's based on a trigger

#

for context

marble jackal
#

Okay, I will fiddle around a bit more.. Maybe I'll be back with a concrete example 🙂
What I'm trying to do is resume media players when they are interrupted by a script. I was trying to use context to determine which entities were interrupted by this specific script, and resume those

mighty ledge
#

you should be able to do that through an automation on the media player state change themselves

floral shuttle
mighty ledge
#

so the trigger should be using the media_player state change, which will have the context of the script when it changes

marble jackal
#

Ah okay, I'll give that a try, thanks!

chilly ferry
marble jackal
chilly ferry
#

thanks!

#

is there anywhere I can learn about all this different options?

chilly ferry
#

ok, I'll give them a look step by step, thanks again 🙂

marble jackal
#

@mighty ledge sorry to bug you again, but could you enlighten me in what happens here, and why the media_player gets the context of the resume script.
I made a simple script to test, which calls my (really simplified for testing) resume script, and then stops the media_player.

    - alias: "test context"
      service: script.turn_on
      target:
        entity_id: script.google_home_resume_simple
    - delay: 1
    - alias: "turn of media_player"
      service: media_player.media_stop
      target:
        entity_id: media_player.floris_mini
#

The code of script.google_home_resume_simple is:

    - wait_template: >
        {% set context_list = expand(integration_entities('cast')) | map(attribute='context.id') | list %}
        {{ states[this.entity_id].context.id in context_list }}
    - service: persistent_notification.create
      data:
        message: >
          {% set ns = namespace(context = []) %}
          {% for player in integration_entities('cast') %}
            {% if states[player].context.id == states[this.entity_id].context.id %}
              {% set ns.context = ns.context + [ states[player].entity_id ] %}
            {% endif %}
          {% endfor %}
          {{ ns.context }}```
#

This returns ['media_player.floris_mini']

#

So my media_player somehow gets the context.id of the script.google_home_resume_simple script, but I don't know why or when based on your earlier explanation

mighty ledge
#

you're still getting the context from the state machine

#

which doesn't hold the actual context, it just has a blank context object

#

this should contain the context object

#

for that script

#

basically, this.context.id vs states[this.entity_id].context.id

#

states = state machine

#

this = momentary state object populated on the fly

marble jackal
#

okay, but why is this context from the states machine the same for the script, and the entity?

mighty ledge
#

because they are both empty context objects which are the same

#

it's like saying 1==1

#

well they aren't empty

#

they contain a context_id for itself

#

FYI, you should be looking at parent_id

#

that's what calls it

#

if it came from a user pressing a button, user_id

#

if it came from an automation or script service call, parent_id

#

if a presses a button that calls a script that calls a script, both should be populated

#

on the second script

marble jackal
#

{{ states['media_player.floris_mini'].context }} #Context(user_id=None, parent_id=None, id='5f24935499f0ae463bd4ee3b4eaa297f')

mighty ledge
#

Yes, because thats from the state machine

#

that's not a momentary state

#

state machine will have no context

#

states = state machine

marble jackal
#

Yes, it's beginning to fall

mighty ledge
#

trigger.to_state = not state machine, momentary state

#

state_changed events with to_state and from_state should also have this info

#

this should also have this info

#

I'm sure there's plenty of other scenarios where they will be populated, but the states machine will never have this context

marble jackal
#

ah okay, so I should compare trigger.to_state.context.parent_id of the changed entity with this.context.id of the script

mighty ledge
#

Not fully understanding what you’re doing but that could be correct. Either way, you can make a persistent notification in your script to view the momentary context objects to understand the process

marble jackal
#

should it also work with trigger based template sensors? I tried with this sensor:

trigger:
  - platform: state
    entity_id: media_player.floris_mini
    from: ~
sensor:
  - unique_id: 80dee1e6-8843-44e9-83ca-a038da85978a
    name: test context 2
    state: "{{ now() }}"
    attributes:
      context: >
        {{
          dict( id = trigger.to_state.context.id, parent_id = trigger.to_state.context.parent_id, user_id = trigger.to_state.context.user_id)
        }}
#

But that gives the exact same result as the context from the state machine

steep kiln
#
 grep "however this template will fail to render in Home Assistant" home-assistant.log |wc -l                                                                                         ✔  chris@metis  16:56:06 
105236

#

first time I'm really afraid to press the update HASS button

acoustic arch
#

Can a value template time calculation act as a automation trigger? Or do I need to make a sensor for it first?

inner mesa
#

yes, you can create template triggers

#

there are some limitations to what you can use in those triggers, which are specified in the docs, so it depends on what you're trying to do

hollow girder
#

Hello all, I tried to do the config split like this and it's not working... the second does not appear. Should't this work?

template: !include_dir_merge_list ../templates
template new: !include_dir_merge_list ../entities/templates
#

They are included via package... Can it be it?

acoustic arch
#

will this trigger? Trying to run automation A if an automation B hasnt in after 24h

#

or does this need a binary sensor to track this calculation?

#

i found this on the forum somewhere. Not sure if and how this will trigger.

#

Do i need the IF statement in the first place?

inner mesa
#

It's not a great template

#

This is a better one:
{{ state_attr('automation.alarm_disarmed', 'last_triggered') < now() - timedelta(days=1) }}

hollow girder
torn meteor
#

is this still a valid warning?

#
Template warning: 'int' got invalid input 'unavailable' when rendering template '{{ trigger.to_state.state|int > trigger.from_state.state|int }}' but no default was specified. Currently 'int' will return '0', however this template will fail to render in Home Assistant core 2022.1
inner mesa
#

You should fix it

torn meteor
#

and if so, should i be using ..|int(0) or ...state|default(0)|int

inner mesa
#

I guess causing to fail didn't make it into the build

ruby vault
#

I am getting it like mad as well

torn meteor
#

no. do you have a link to the change record on this?

inner mesa
#

The former, not you should evaluate the template and decide what's best

#

There's a nice thread in the forum on it

torn meteor
#

is it that the Jinja int() will no longer provide a 0 default, or will no longer provide defaults at all?

inner mesa
#

Just what it says

#

It returns 0 for now and will fail completely later

torn meteor
#

is |int(0) valid or do I need the key |int(default=0)?

ruby vault
#

so just going

int(0) sets the default and thats it?

hollow girder
torn meteor
#

yeah, i'm still very confused as to if HA wants me to use the default() filter or add an explicit int(default) parameter to the int filter

ruby vault
#

well, for me its on my fronius inverter and when there is no solar/sun it turns off and becomes unavailable.. I'll find out soon enough. ;)(

#

anyway, seems to be the clue I was lookijng for. I"ll try int(0) for now and if that fails i'll try default()

tired galleon
#

copies guid 'don't mind if i do'

snow laurel
#

I am trying to use a utcnow().month within an if statement. as in {{ if utcnow().month == 2}} for instance. What is the proper syntax for this?

inner mesa
#

depends on what you're trying to do

#

{{ utcnow().month == 2 }}

#

returns a boolean

#

your example is incomplete

snow laurel
#

I would like to write an if statement where it checks the current month and returns a state based on that

inner mesa
#

ok

snow laurel
#

Was my error that I was using two {{ ?

inner mesa
#

no, yours was just incomplete

#

"if xxx" is only part of what you need. then what?

snow laurel
#

Something like this.

inner mesa
#

that's one way to do it

#

I'm not sure what you're asking

snow laurel
#

If my syntax is correct:)

#

I think I was using {{ to enclose my if statement when I should have been using {%

inner mesa
#

what you had above was incomplete

#

so, wrong

#

perhaps it would help to review the Jinja docs

silent barnBOT
inner mesa
#

{% %} is for logic, {{ }} is for output

#

you can also do something like this: {{ "foo" if utcnow().month == 2 else "bar" }}

snow laurel
#

Thanks for your help as always!

marble jackal
#

If you want to use it as a condition you can also use the new iif.
{{ iif(utcnow().month == 2) }}

soft sail
#

I am trying to change the color background of my view based on the reading of rgb_color attribute of one of my lights. This is what I've come up so far but it's not working. Could someone please help me out?

#

background: >
[[[
return rgb(${states['light.my_smart_bulb_2'].attributes.rgb_color})
]]]

#

I hope this is the right place to ask.

floral shuttle
#

that would be a #frontend-archived question, and you'd probably need card-mod-theme and the lovelace-background variable

unreal merlin
#

howdy 🙂 having a hard time with adding multiple areas to a filter. Any ideas why this would work:

#

|selectattr('entity_id','in',area_entities('Terasz (Hátsó)'))

#

but this wouldn't:

#

|selectattr('entity_id','in',[area_entities('Terasz (Hátsó)'), area_entities('Terasz (Első)')])

#

what's the right way to chain area_entities in selectattr is what I'm asking I think 😉

glossy viper
#

hi. how can i have friendly name instead of entity id in template : {{ states.light | selectattr("state","eq","on") | map(attribute="entity_id")| list }}

buoyant pine
#

Replace entity_id with name

glossy viper
#

hm...not working (LE: silly me: friendly_name"

buoyant pine
#

Define "not working"

glossy viper
#

added friendly_name and works

#

ty

worldly hemlock
#

Hi guys

marble jackal
worldly hemlock
#

I'm starting do to some templating for my mqqt object

#

creation

#

this is my 'script' dirty and not functional

#

functional script but doesnt use the auto discovery so loses to many features

#

I just want a 1 on 1 replacement 🙂

#

It probably fails bigtime cause I'm trying to insert the logic in a dirty way

#

any help would greatly be appreciated 😄

unreal merlin
spare vector
#

Hi, is regex_replace working with value_template ? Want to cut off ".gcode" from the presented filename.

mighty ledge
#

or split on the extension

spare vector
mighty ledge
#

that's normal jinja or python

#

won't be covered in HA docs

worldly hemlock
#

any advice would be very welcome

spare vector
crimson coral
#

May someone explain me how it work "|" here *value_template: "{{ as_timestamp(value_json.result.uploadTime) | timestamp_local }}" *

inner mesa
#

It's a pipe. It takes the output of the thing on the left and feeds it into the thing on the right

#

Same as in nearly every shell command line

#

So, it takes a timestamp and passes it to another filter that converts it to a string

crimson coral
soft sail
onyx juniper
#

heyho,
can someone maybe send me in the right direction? I'd like to create a notification group that only notifies those people, that are currently at home.

notify:
  - name: everyone_at_home
    platform: group
    services:
      - service: mobile_app_person1
      - service: mobile_app_person2

Something like this, but of course person1 only if person1 is at home.

inner mesa
mighty void
#

Is it possible to have an MQTT sensor listen to 2 topics, or have the sensor temporarily listen to a second topic?

inner mesa
#

I don't see how it would know what to do with two topics

mighty void
#

Or just toggle between two different topics. I don't need it to listen to 2 topics simultaneously

buoyant pine
#

Nope. What's the objective behind that?

mighty void
#

The sensor gets it's status from one topic. I can request the status, but it's returned on a second topic

sturdy spindle
#

Sorry to comment on such an old message, but wondering if you ever solved this. For me, these errors are caused by an automation using a blueprint for ikea tradfri remotes in ZHA. When the tradfri switch goes to sleep, it fires a ZHA event without any of the attributes mentioned and causes this error.

celest tinsel
#

I'm trying to reference a trigger_id to build the name of a sensor so I can have a common notification scheme for multiple sensors. Currently have this:

message: >-
    {{ trigger.id }} PV is out of range. Current value is 
    {{states('sensor.{{ trigger_id }}_presvalue' ) }}. Set value is: 
    {{states('sensor.{{trigger_id}}_setvalue' ) }}

The sensor I want is called ferm_1_presvalue and the trigger_id is ferm_1

inner mesa
#

You're nesting templates

#

Construct the string from the variable

manic onyx
#

hi everyone. Can I use template in the utility sensor? Want to divide sensor value by 1000
utilities_fridge_power_daily:
source: sensor.fridge_power_usage
cycle: daily

inner mesa
#
message: >-
    {{ trigger.id }} PV is out of range. Current value is 
    {{states('sensor.' ~ trigger.id ~ '_presvalue') }}. Set value is: 
    {{states('sensor.' ~ trigger.id ~ '_setvalue') }}
#

@celest tinsel

celest tinsel
#

Cool. Thanks

inner mesa
#

you also have some trigger_id in there that I suspect you want to be trigger.id

celest tinsel
#

Ferm_1 temp is out of range. Current temp is 23.7. Set value is: 22.4

Perfect!

inner mesa
#

I'm surprised that works with a trigger.id with a capital letter in it

celest tinsel
#

why's that?

inner mesa
#

because entity_ids are all lowercase

celest tinsel
#

and case sensitive?

inner mesa
#

so it seems like you're constructing states('sensor.Ferm_1_setvalue')

#

yes

celest tinsel
#

interesting

inner mesa
#

it looks like it lowercases it

celest tinsel
#

Can I ask you this one? Same question. How can I use trigger.id in the entityid field to set this helper?

service: input_datetime.set_datetime
data:
  datetime: '{{ now().strftime(''%Y-%m-%d %H:%M:%S'') }}'
entity_id: input_datetime.ferm_1_last_alarm
inner mesa
#

if you indent it by another 2 spaces, yes

celest tinsel
#

how do I reference the trigger.id?
entity_id: 'input_datetime.' ~trigger.id ~ '_last_alarm' ??

inner mesa
#

that's not a proper template

celest tinsel
#

I see

inner mesa
#

it's completely different from the others that you've posted

celest tinsel
#

I'm learning something. one sec

#

somethign like this? entity_id: '{{input_datetime.' ~trigger.id ~ '_last_alarm}}'

inner mesa
#

no, kinda random

#

entity_id: input_datetime.{{ trigger.id }}_last_alarm

celest tinsel
#

Question for you. If I want to test this in Dev tools, how can I define a variable in jinja that I can reference in the template?

#

Oh, hell. Let me google that

inner mesa
#

sure

#

{% set trigger = {"id": "foobar"} %}

celest tinsel
#

thanks.

#

I'm working a cool project for a friend. He's a master brewer working with local craft breweries. He generally installs pid controllers to control fermentation temps. We're looking to use HA to monitor the controllers and alarm out if there's an issue.

#

I got the modbus stuff all working two weeks ago - now fine tuning the alarming part.

#

It's forcing me to really focus on some Ha stuff like templates that will help me here at home too

#

I love that I can do all of the alarming from a single automation even if there are 20 femrenters

strange geode
#

is it possible to link 2 ikea blind into one i HA ?

  • And customize it as a blind and not curtains with google home?
onyx juniper
noble fern
#

G'day. I think I'm missing something but best to ask. Can I apply the "default" scenario in a for loop in case the sensor that the for relies on is undefined?

#

As in: {% for package in states.sensor.seventeentrack_packages_delivered.attributes.packages %}

#

It seems to have changed the way it works shows - in the sensor instead of a number. I'd like to either make it 0 or have it skip the rest of the processing. Currently, it throws a: TypeError: 'NoneType' object is not iterable

signal lava
#

Hi, not sure if I am on the right chan. I'd like to add my graphite stack to home assistant, to be able to get metrics from graphite and show it with card like mini-graph-card. I didn't find any information about that. And I have check the doc that seem possible to add custom sensors with template.
Does anybody have already do that or have information about how to connect graphite to home assistant
thank you for your help 🙂

noble fern
#

I've had to wrap the for loop in an if (nesting I know but I don't see any other way to do it) with the 'defined' thing as it is showing 'None' for the state. Weird.
Eg: {% if states.sensor.seventeentrack_packages_delivered.attributes.packages != None -%}

inner raft
#

Hey 👋. Is there any way to share a macro in multiple template sensor ? Or I need to copy paste ?

#
{%- macro getRoomTemperature(room) -%}
  {{ expand(area_entities(room)) | selectattr('attributes.device_class', 'eq', 'temperature') | rejectattr('state', 'in', ['unavailable', 'unknown']) | map(attribute='state') | map('float') | average | round(1) }}
{%- endmacro -%}

{{ getRoomTemperature("Salon") }}

This would be the template itself.

inner mesa
#

no, there's no global scope for macros

inner raft
#

Ok thanks @inner mesa

thorny snow
#

Hi all,
I´m new to HA and currently first time touching templating.
I wanted to set up a cover template (followed the instructions on HA homepage), but maybe I have a special scenario:

  • my garage door is controlled via a switch/pulse on KNX bus. I just can trigger and it will open when closed and vice versa (when stopped, it will return on next trigger)
  • I have now two reed contacts for positioning, so finding out open/closed/opening/closing state should be easy with storing the last_state (open|closed).

I tried to build this up in the cover template, but somehow it does not work out.
What´s not clear to me:

  • I want to implement 'and' in my if condition. I´d assume Jinja should allow this.
  • Can I build nested ifs?
  • Can I read/write a helper entity (I created it in the automation page in my HA instance)

If meaningful, I can also put my existing configuration.

Thanks a lot in advance for any help/hint!

narrow surge
#

@high crater no, its missing the UTC part.

#

2022-02-12T21:29:00
high crater
#

thats the problem

narrow surge
#

Not sure what as_datetime converts the output to

#

But this wont work as well:

{{ states('sensor.motorola_one_hyper_next_alarm')|as_datetime - timedelta(minutes=30)  >= ('sensor.date_time') }}
#

TypeError: '>=' not supported between instances of 'datetime.datetime' and 'str'

#

But maybe I need to use as_timestamp instead, because after this I also need a default value, which as_timestamp supports.

high crater
#

I ran into an issue similar to this and I had to use as_timestamp for that reason it is unique for day and time so it should work just as datetime but you need to do the subtraction in seconds IE 300 seconds = 5 minutes

narrow surge
#

ow lol

thorny snow
#

cover - platform template covers garage_door device_class garage fr

narrow surge
#

{{ as_timestamp(states("sensor.motorola_one_hyper_next_alarm" ) - 1800)  >= as_timestamp(states("sensor.date_time").replace(",","")) }}
#

How can this be so hard 😦

#

Even with your example I'm getting an error:

{% set alarm_time = as_timestamp(states("sensor.motorola_one_hyper_next_alarm")) %}
{% set time_now = as_timestamp(states("sensor.date_time").replace(",","")) %}
{{ time_now >= ( alarm_time - 300 ) }}
#

TypeError: '>=' not supported between instances of 'NoneType' and 'float'

inner mesa
#

I'm not really following all this, but is this what you want?

#

{{ "2022-02-14T07:50:00+00:00"|as_datetime - timedelta(minutes=30) > now() }}

#

or something like that?

narrow surge
#

I want to create a condition that will be true half an hour before my alarm goes off, and the ability to set a default time as well.

#

Which as_timestamp(value, default) should be able to do

high crater
#

what is the output of {{states.sensor.motorola_one_hyper_next_alarm.state}}

narrow surge
#

2022-02-14T07:50:00+00:00

high crater
#

and you have a sensor.date_time in your entities correct?

narrow surge
#

I do not I see

high crater
#
  # Time/Date Sensor
  - platform: time_date
    display_options:
      - 'time'
      - 'date'
      - 'date_time'
      - 'date_time_iso'
      - 'time_date'
      - 'time_utc'
      - 'beat'

added it for me in config.yaml after a restart

narrow surge
#

Seemed I only had date and date_time_iso

#

Ok, now your example works!

#

Mine is returning a true instead of false, haha

high crater
#

switch >= to <=

narrow surge
#

ah ofcourse, had the current time and alarm time rotated!

#

Is there a tool to calculate the timestamp value of a specific time, I want to use that for the default value.

high crater
#

do not look for an exact match between them though, I have had it miss the event waiting for the numbers to match exactally

narrow surge
#

I will use it in a condition, so I dont think I will hit that issue?

high crater
#

you may, thay number is uniques to the milisecond I believe

narrow surge
high crater
#

mine fires from 5-6 minutes before my alarm

narrow surge
#

ouch, it also includes the date...

high crater
#

yup

narrow surge
#

So I cannot set a default value for the timestamp

high crater
#

but if you set your alarm for monday it wont go off saturday or sunday

narrow surge
#

Like, after 09:00 as default

#

Yeh true, but for the weekends for example. I want it to be true after 09:00

high crater
#

i would make a second trigger and use the chooser action maybe

narrow surge
#

Or just on the times I dont set an alarm

high crater
#

not sure about setting a default value

narrow surge
#

Thanks so far!

kindred arrow
#

Hey guys, I need your help, it's no big deal I promise!
I know how to get the last time a entity has been triggered, but I wish to get the time before that one to know the delta (timestamp) of thoses two
(I want to know how long it has been "on")

I though of create a manual sensor with the time the device has been turned on, or even create a sensor that take the last time the device has been triggered "on"
But you may (certainly) have a clever way than me! Thank youuu

To make it short: Possible to query the last time a entity was ‘on’?

torn meteor
#

is there a sane way of getting the keys of a json object, without the values?

#

say {myjson: data: { 'item1': 'value', 'item2': 'value' }}

#

i only want data's keys or labels

#

not the values

inner mesa
#

data.keys()

torn meteor
#

is that a thing i can do inside {{ }} or {% %}?

inner mesa
#

Either

#

It's a standard method on the Python dict

torn meteor
#

thanks!

#

is there a better place to find these filters/functions besides the jinja2 docs website? I hate navigating that thing

inner mesa
#

That's a Python method

#

Jinja uses Python data structures

torn meteor
#

uh oh. now i have a string dict_keys(['projector', 'hdmi_2x1_output_1', 'hdmi_4x2_output_1', 'hdmi_4x2_output_2'])

thin bronze
inner mesa
#

So use |list

torn meteor
#

i tried a|list filter on that and it broke it up into characters

inner mesa
#

{{ {"foo": "bar", "blah": "floop"}.keys()|list }}

#
[
  "foo",
  "blah"
]
torn meteor
#

ah i got it. i was running|list off the value of the sensor from another template sensor. i needed to do |list at the same place i did keys(). thanks

stuck bone
#

My first template: {{ (states('sensor.processor_temperature') | float - 32) / 1.8 | round(0) }}

inner mesa
#

You're rounding 1.8 to 0 decimal places, so probably not quite what you wanted

stuck bone
#

I need another set of (), right?

inner mesa
#

Yes

stuck bone
#

{{ ((states('sensor.processor_temperature') | float - 32) / 1.8) | round(0) }}

#

That's what I get for doing this after being awake for almost 24 hours now.

#

Thank you. Seems more accurate now.

#

Second (since the value comes in as watts and not kilowatts): {{ ((states('sensor.envoy_today_s_energy_production') | float ) / 1000) | round(2) }}

steep beacon
#

Hi all, I am not at all good with templates but I'm trying to use one in a Markdown card to extract the date only from a timestamp, but don't really know how to do it. Wondering if someone can please help me.
``
type: markdown
content: >-
ON THE WAY:

{% for package in
states.sensor.seventeentrack_packages_in_transit.attributes.packages %} {{
package.friendly_name }}:
Last tracked on {{ package.timestamp }} {{
package.info_text }}.

{% endfor %}
``
In the above I'd like the timestamp to only show the date, in the format dd-mm-yy. Could someone please show me how this is done, if it is actually possible?

marble jackal
#

For 24h time format

mighty ledge
#

I guess it shouldn't matter.

type: markdown
content: >-
  **ON THE WAY:**

  {% for package in
  states.sensor.seventeentrack_packages_in_transit.attributes.packages %} **{{
  package.friendly_name }}:** Last tracked on {{ (package.timestamp | as_datetime | as_local).date() }} {{
  package.info_text }}. 

  {% endfor %}
marble jackal
#

Oh whoops, he needed the date :)

narrow surge
#

How can I let the following statement only be true between 06:00 and 09:00?

{{ as_timestamp(states("sensor.date_time").replace(",","")) >=  (as_timestamp(states("sensor.motorola_one_hyper_next_alarm" )) - 1800) }}
#

It can now also be true at 13:00 for example, if I set my alarm to >= 12:30

nocturne kiln
#

I want to set a template sensor to true/on if a motion sensor is triggered. And I want it to reset to false/off each night. Is that possible?

nocturne chasm
nocturne kiln
#

Okey. I'll check it out.

dull aspen
#

I'm trying to set up a custom cover template. Is there any way to have the device set to "closing" and "opening" states for a set amount of time? (As it is set up anyone unfamiliar with the setup might assume it didnt work and click multiple times instead of waiting for the state to change)

mighty ledge
#
{{ today_at("06:00") <= states('sensor.motorola_one_hyper_next_alarm') | as_datetime | as_local <= today_at("09:00") }}
#

but again, that depends on the state of sensor.motorola_one_hyper_next_alarm

glossy aurora
#

is there something like as_date ? for just getting the date without the hour like as_datetime

#

i just wanna compare if the sensor is set to the same day of the month than now().date()

#

oh

#

i can do as_datetime(state_attr('calendar.niko_kalender','start_time')).date()

#

ty

narrow surge
#

Can I also do something like this: trigger.to_state.attributes.source == 'SHIELD' But then for both SHIELD and TV.

#

So it will try to match multiple different values in attributes.source?

inner mesa
#

Yes

#

trigger.to_state.attributes.source in ['SHIELD', 'TV']

narrow surge
#

Ah, awesome!

#

And not in eq !=?

inner mesa
#

Yes, or not x in y

mellow pulsar
#

Greetings!

silent barnBOT
mellow pulsar
#

my problem is the statistics template is not returning anything

inner mesa
#

Does that attribute exist?

#

I suspect not

mellow pulsar
#

from the statistics page,

#

distance_absolute The difference between the extreme values of measurements. Equals value_max minus value_min.

#

I am using 2022.2.1

#

no errors in the log

#

it is a state characteristic if that matters..

#

according to the table header on the statistics page

#

this also returns None : {{ states.statswdaccx.distance_absolute}}

mighty ledge
#

So your stats configuration is worng

#

change state_characteristic from mean to distance_absolute, then you just grab the sensors state

#

and you won't need the template sensor

mellow pulsar
#

ok, trying now

mellow pulsar
#

thanks @mighty ledge , I think I am all set now!

manic epoch
#

Hi all. Some code for a template was recommended to me. It seems to work, but I'm not sure how (this level isn't that familiar to me yet). The actual config is here - https://pastebin.com/qPhikFxY and I'm mostly curious about lines 35 and 60. I guess I'm looking for the mathematical sequence these lines work through so I can plug in the temperatures and calculate it manually to understand it.

stiff sandal
#

hi guys.. in a custom button card..
If I want the name shown to be from an attribute.. what is the right syntax.. I've tried so many things..

name: {{ state_attr('sensor.mealie_today_Recipe', 'name') }}

name: >
[[[
return (state_attr['sensor.mealie_today_Recipe'], 'name')
]]]

And all kinds of iterations..

Could someone point me in the right direction.

inner mesa
#

you're mixing up Jinja, which that card doesn't use, and Javascript, which it does

#

hopefully you reviewed the card docs?

stiff sandal
#

you're probably right... 🙂 Let me give it a go !

#

tried this:

name: >
[[[
var name = states['sensor.mealie_today_Recipe'].attributes.name;
return name;
]]]

which looks ok when looking at the documentation .. but alas ..

inner mesa
#

you have a capital R

stiff sandal
#

I changed it.. but the entity was also with a capital R

This worked though I am sure I tried it before:

name: >
[[[
var recipename = states['sensor.mealie_today_recipe'].attributes.name;
return recipename;
]]]

inner mesa
#

Entities are always lowercase

#

devtools -> States

steep beacon
# mighty ledge I guess it shouldn't matter. ``` type: markdown content: >- **ON THE WAY:** ...

Unfortunately as soon as I add the 'as_datetime' stuff the entire markdown card fails to display anything. The timestamp looks like this- timestamp: 2022-02-10T11:26:00+00:00 as an attribute of the sensor entity for the parcel being tracked
sensor.seventeentrack_package_33fqj3575849 Seventeentrack Package: Kogan Moon Lamp In Transit attribution: Data provided by 17track.net destination_country: Unknown info_text: In transit to next facility in MALAGA WA timestamp: 2022-02-10T11:26:00+00:00 location: origin_country: Australia package_type: Registered Parcel tracking_info_language: Unknown tracking_number: 33FQJ3575849 icon: mdi:package friendly_name: Seventeentrack Package: Kogan Moon Lamp

mighty ledge
#

that's a fully fleshed out datetime

#

how does states.sensor.seventeentrack_packages_in_transit.attributes.packages relate then

#

the other possiblity is that it's already a datetime objecdt

#

{{ package.timestamp.date() }}

steep beacon
mighty ledge
#

well, you aren't iterating over sensor.seventeentrack_package_33fqj3575849, you're iterating over sensor.seventeentrack_packages_in_transit's packages. So the attribute on sensor.seventeentrack_package_33fqj3575849 is essentially meaningless

steep beacon
steep beacon
# mighty ledge {{ package.timestamp.date() }}

Your example gives me the date only (as yyyy-mm-dd) which is great but is there a way to change that to dd/mm/yy. I tried a few variations with timestamp_custom( but it didn't work for me, obviously I have it wrong

warm isle
#

Might have an Idea if I can convince jinja to do my bidding?
{{ (state_attr("light.hue_ambiance", "brightness")) (( '+' , '-' ) | random ) ( '10' | int) }}
(Dim or increase brightness randomly )

buoyant pine
#

@warm isle {{ state_attr("light.hue_ambiance", "brightness") + range(-10,11) | random }}

buoyant pine
#

Oh you want plus or minus 10, not a range.

{{ state_attr("light.hue_ambiance", "brightness") + [-10,10] | random }}
silent barnBOT
manic onyx
#

hi everyone. Need a template guru 🙂 Just do not understand how the text permutations work ??
I have an inverter that sends the info. I am getting the info, but I want to somehow transform it on the fly, so that when it puts the values into the sensor this line "InvStatus": "Ok,SN=2100262842,FW=2.13.1A", becomes this line "InvStatus": "FW=2.13.1A", so in the end this:
"Timestamp": "14/02/2022 10:54:01", "SunRise": "14/02/2022 05:55:00", "SunSet": "14/02/2022 19:05:00", "InvSerial": 2100262842, "InvName": "SN: 2100262842", "InvTime": "14/02/2022 10:53:56", "InvStatus": "Ok,SN=2100262842,FW=2.13.1A",
will have its InvStatus changed to just FW version

inner mesa
#

are those attributes?

#

or is that the JSON that you're getting from something?

#

this will transform that particular string:

{{ "Ok,SN=2100262842,FW=2.13.1A".split(',')[-1] }}
manic onyx
#

these are attributes @inner mesa - its coming from MQTT

#

I just dont know if its possible at all to do on the fly. Or I will need to put that attribute into a new sensor to get the value?

inner mesa
#

this works, but sucks:

#
{% set newdata = {
  "Timestamp": data['Timestamp'],
  "SunRise": data['SunRise'],
  "SunSet": data['SunSet'],
  "InvSerial": data['InvSerial'],
  "InvName": data['InvName'],
  "InvTime": data['Invtime'],
  "InvStatus": data['InvStatus'].split(',')[-1] }
%}
{{ newdata }}
manic onyx
#

right...

inner mesa
#

{{ data|regex_replace("Ok,SN=\d+,", "") }}

#

that does it

#
{% set data = {
 "Timestamp": "14/02/2022 10:54:01",
  "SunRise": "14/02/2022 05:55:00",
  "SunSet": "14/02/2022 19:05:00",
  "InvSerial": 2100262842,
  "InvName": "SN: 2100262842",
  "InvTime": "14/02/2022 10:53:56",
  "InvStatus": "Ok,SN=2100262842,FW=2.13.1A" }
%}

{{ data|regex_replace("Ok,SN=\d+,", "") }}
#
{'Timestamp': '14/02/2022 10:54:01', 'SunRise': '14/02/2022 05:55:00', 'SunSet': '14/02/2022 19:05:00', 'InvSerial': 2100262842, 'InvName': 'SN: 2100262842', 'InvTime': '14/02/2022 10:53:56', 'InvStatus': 'FW=2.13.1A'}
manic onyx
#

wow! thats clean!

#

on the regex topic if you dont mind. If I wanted to use something like regex_replace("(?<=^).*(?=FW)", "") - what is wrong with my syntax? Trying to learn 🙂

inner mesa
#

Is your goal the same?

#

I don't know what that's trying to do

manic onyx
#

yeah, just using it as an example while learning regex 🙂

inner mesa
#

Ok. I still can't parse that in the context of the input data

manic onyx
#

{{ data|regex_replace("Ok.*FW=", "") }}

inner mesa
#

That's better, if you just want the firmware version

manic onyx
#

yes. Thank you! Learned few things today 🙂

#

hm... tried it on another example and found that I have an issue 🙂 {{ data|regex_replace("Ok.*FW=", "") }} would take first "Ok" and remove everything to the LAST "FW="
If I have multiple lines of the same pattern, then I am in trouble

#

and now I have learned about "greedy" * and "lazy" * 🙂 just use ?

inner mesa
#

It's usually better to match what you know

#

Rather than .* or ?

vital comet
mighty ledge
vital comet
#

No clue what it means by that

TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'
mighty ledge
#

state_attr('sensor.usg_wan_in_stats', 'sampling_size') doesn't exist then

#

@vital comet

vital comet
mighty ledge
#

the attribute sampling_size doesn't exist

#

specifically

vital comet
#

Yes, erm as a stupid follow-up. How does one fix that
That's what i've got

mighty ledge
#

You can't you can only access attributes that exist on the entity

#

you can see attributes that exist by looking at the entity in developer tools -> states page

vital comet
#

Well yes, The question is, as it's an entity created by me using stats...is there no way to fix it?

mighty ledge
#

if stat's doesn't provide that attribute, then you have to hard code that number in your template

vital comet
#

to be honest i need some tips in that department

mighty ledge
#

you have 2 state_characteristic options for change rate: change_second or change

vital comet
#

i think change_second seams to fit this the most...

mighty ledge
#

then you'd change your stats config to use state_characteristic: change_second and you'd update your template calculation to calculated based on a per/second change rate.

#

well, you probably don't even need the template

#

because it would already be per/second

#

Mbps, the ps, stands for per second

vital comet
#

ik

#

i struggled, I gave up for now, I'll be back at it when i have more time

mighty ledge
#
  - platform: statistics
    name: "USG WAN in Stats"
    entity_id: sensor.usg_wan_in
    sampling_size: 4
    state_characteristic: change_second
    max_age:
      hours: 24
    unit_of_measurement: "MBps"
tawny coral
vital comet
mighty ledge
vital comet
#

Figured it out ^.^ ```yml
template:

  • sensor:
    • name: "Internet Download"
      state: "{{ states('sensor.usg_wan_in_stats') |float /1000000 | round(2) }}"
      unit_of_measurement: "MBps"
    • name: "Internet Upload"
      state: "{{ states('sensor.usg_wan_out_stats') |float /1000000 | round(2) }}"
      unit_of_measurement: "MBps"```
mighty ledge
#

Yes, if your initial sensor is in bytes, then you'd have to convert it to MB

vital comet
#

just one issue, it's not rounding off

mighty ledge
#

wrap the entire equation in () before the | round

#

you're just rounding the 100000 without the ()

marble jackal
#

Which seems to be pretty round right now

mighty ledge
#

so ( before states(... and ) after the 1000000

vital comet
#

yep yep. works wonderfully

#

ima post an update to the forum thread xD

opal pulsar
#

hi guys, can some one help me please

#

switch:

  • platform: command_line
    switches:
    mediaplayer:
    command_on: "ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no root@192.168.100.55 'echo on 0.0.0.0 | cec-client -s -d 1'"
    command_off: "ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no root@192.168.100.55 'echo standby 0.0.0.0 | cec-client -s -d 1'"
    #command_state: "ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no root@192.168.100.55 'echo pow 0.0.0.0 | cec-client -s -d 1 '"
    #value_template: { { value != 'standby' } }
    friendly_name: "Reception TV"
#

how to get status of tv ?

#

comented rows dont work

#

ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no root@192.168.100.55 'echo pow 0.0.0.0 | cec-client -s -d 1 '

this command answer

power status: standby

or

power status: on

mighty ledge
#

your value_template should check against whatever this returns ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no root@192.168.100.55 'echo pow 0.0.0.0 | cec-client -s -d 1

opal pulsar
#

sorry but didn't get u

mighty ledge
#

when you run ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no root@192.168.100.55 'echo pow 0.0.0.0 | cec-client -s -d 1 on commandline, what does it return

opal pulsar
#

power status: standby

or

power status: on

#

depending of tv state )

#

if exactly

#

[core-ssh ssh]$ ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no root@192.168.100.55 'echo pow 0.0.0.0 | cec-client -s -d 1'
opening a connection to the CEC adapter...
power status: standby
[core-ssh ssh]$ ^C

mighty ledge
#

does power status: standby equal standby?

opal pulsar
#

yes

mighty ledge
#

how

#

please show me how power status: standby equals standby

#

pretty sure theres about 10 characters that don't match

opal pulsar
#

i have to delcare somehow that "power status: standby" = "standby" ?

mighty ledge
#

no, your value is power status: standby and your template is {{ value == 'standby' }}

#

so what should go on the right side of the equation instead of just standby

#

the only way {{ value == 'standby' }} will resolve true is if value is equal to standby. You already confirmed that your response is not standby, it's power status: standby

#

so... if standby is wrong, what should go in standbys place?

opal pulsar
#

power status: standby

mighty ledge
#

yep

#

if that doesn't work, we'll have to approach this differently, just let me know

opal pulsar
#

Configuration invalid )

#

Error loading /config/configuration.yaml: invalid key: "OrderedDict([("value == 'power status", "standby'")])"
in "/config/configuration.yaml", line 34, column 0

mighty ledge
#

post what you tried, you have synax error. I'm assuming you removed the quotes

#

the quotes should still remain

opal pulsar
#

value_template: { { value == 'power status: standby' } }

mighty ledge
#

don't put spaces like that on the template indicators

opal pulsar
#

when i save configuration yaml them put them back, spaces

mighty ledge
#

also, single line templates need to be wrapped in exterior qoutes. Because you'r eusing interior single quotes, you should be using double quote as the exterior quotes

#

field: "{{ 'something' }}"

#

see pin number 3

#

This pin

opal pulsar
#

nice, now configuration is valid

#

But status is shown incorrect

mighty ledge
#

ok, that means your command call probably has whitespace

#

change your template to

  "{{ 'standby' in value }}"
#

now, you're only checking to see if the value contains the word 'standby'

#

assuming that the command returns something different when the switch is off

opal pulsar
#

it must be something like " when i turn off the switch , status of this command contain standby"

when i turn on the switch , status of this command contain on ( or des not contain standby )

#

can be the check time problem ? i mean them is checking too slow status of tv ?

mighty ledge
#

the default polling rate is 30 seconds

#

if you want to check standby as being off, then..

"{{ 'standby' not in value }}"

your template must return true to equal on. So reversing the logic will mean standby == off

opal pulsar
#

you are my hero ) its working !!

#

is there any way to force update status after switch togle ?

#

I mean after i turn it on, the status is changing after 30 sec

mighty ledge
#

If the integration doesn't do that by default, you'll have to make a template switch that forces the update through a service call after you turn it on

#

You'd have to add a delay in it as well

opal pulsar
#

Got it

#

I will search how to do that tomorow )

#

thank you for help, is there any rating ) ?

mighty ledge
#

what do you mean rating

opal pulsar
#

How can i say "thank you" )

mighty ledge
#

oh, no, there's no rating

#

you're welcome

proper holly
#

Trying to template ALL devices that are a common model. I get one device by requesting this: {{ device_attr('light.dining_room_dimmer_current_value', 'model') }} but am looking for a list of all devices that have a common device model. Any thoughts?

#

Eventual goal is to move to z-wave multicast for all common model components (I can filter down in Node Red once I get a list of all entities to start).

mighty ledge
#

you should be filtering down to command class for multicast, not model

proper holly
#

Cool. Will review. My thought is I could optimize my "away" script to multicast all lights that are "on" and command them "off".

mighty ledge
#

well, good news, you don't have to do anything other than use the script I wrote

#

it handles zwave devices that have 0, 1, 2, or 3 channels for switches on a single device. You have to setup a configuration for it though.

proper holly
#

I was attempting to make the group more automated if I add devices in the future, is that currently possible (whether by group or templating or whatever?)

mighty ledge
#

yes that's what it does

#

i'm lazy and future me doesn't want to have any overhead

#

everything i make is so future me can be lazy

proper holly
#

Fantastic. Thanks for the help.

#

Glad someone else thinks ahead too 😄

chilly ferry
#

is there a way I can use a template in a transition for lights?

#

I'd like to have it dynamic, I created a template sensor for it and doesn't accept it, but I wonder if there's another way

mighty ledge
#

You're going to have to elaborate on that use-case

chilly ferry
#

I want to calculate the number of seconds between "now" and sunset, so then I'll turn on some lights and have a transition of that length

mighty ledge
#

most devices will not support a transition that long

chilly ferry
#

umm didn't think about it... what would be "that long" mean? byte size?

mighty ledge
#

it depends on the device

#

but I doubt any would accept minutes as a transition rate

#

also, what kind of light do you want on when the sun is up while matching the sun

chilly ferry
#

looks like half of the things I try to do are too crazy!

mighty ledge
#

usually, people will match color temps, not brightness

chilly ferry
#

so I have right now an automation that turns on the lights with some inclination is below 2

#

oh... that could be interesting...

mighty ledge
#

that's called circadian lighting

#

and many people have done that

chilly ferry
#

ah yeah, I saw adaptive lights in HACS

#

but it does the opposite I was looking for, let me explain quickly:

#
  • Inclination reaches triggering level
  • Sometimes at the same inclination the amount of light is too bright, so fully turning lights feels an overkill
  • My intention is to increase little by little the amount of light given until it's fully dark when the lights become white/100% brightness
#

I was testing a bit adaptive lights with my bulbs in the office and it didn't make much sense to me as by the time I turn on the lights it's already darkish, so it never has the full light, and also if not limited it becomes way too dark

#

does it make sense?

mighty ledge
#

not really

proper holly
#

Just cause I am here. I think what he is wanting is a general fading up of lights as the sun sets.

chilly ferry
#

yes, that's it... sorry English isn't my main language (even if I should be able to deal with it... lol)

proper holly
#

Basically start at 2 degree inclination and vary over time to 100% at 0 inclination.

#

Aka sunset.

chilly ferry
#

yep

#

color could be cool too... I just didn't play with it yet TBH

proper holly
#

I use circadian lighting and it is fantastic (and going through even further improvements) but I would also be interested in transitioning from overhead lighting to lamps as you have said. I assume sun.sun and time calculation template could be used to get a percent from 1 to 100 and that could be applied as brightness. I'll do this, but in Node Red as I am more familiar with that. Great idea!

chilly ferry
#

thanks!

#

well, I just tried as an example to set a transition of 10k and it worked at least with ikea lights

mighty ledge
#

adaptive lighting does that too, that's why I guess I don't understand why either of these integrations don't work for you

chilly ferry
#

ok so then I'm missing something... how can I achieve that with adaptive lights? honestly I don't wanna re-invent the wheel 🙂

mighty ledge
#

you adjust the offset time based on the sunset to your liking and adjust the transition time to match the overall transition time you want to meet

#

it's just a bunch of parameters that you have to play with until you get the desired result

#

circadian lighting will actually run the calc based on the sun

#

but it attempts to match daylight, not sure if that can be inverted

chilly ferry
#

exactly that's my point

#

I'm not trying to match the daylight

mighty ledge
#

right, so that's adaptive lighting

#

because circadian will match the sun

#

adaptive lighting is on/off based on sunset

proper holly
#

It is my understanding that adaptive lighting stays at 100% from sunrise to sunset (with offset), and adapts color from offset sunrise to offset sunset

#

I believe he is asking for 1% to be when elevation is at 2% above horizon (before sunset) and 100% at sunset.

chilly ferry
mighty ledge
proper holly
#

I'm not aware of that function in the current version.

mighty ledge
proper holly
#

Gotcha. I do not use CL so can't speak to that.

mighty ledge
#

it takes like 3 minutes to read the props

#

I haven't used either, but I spent 3 minutes loooking at the props

chilly ferry
#

oh ok wait... when you speak of circadian lightning you're not speaking of the adaptive ligthning HACS integrations, right?

mighty ledge
#

there's 2 integrations

#

circadian

#

adaptive

#

both are custom

chilly ferry
#

oh my... 😆

mighty ledge
#

both are filled with random crap that can do random crap

chilly ferry
#

for some reason I read that adaptive lightning does circadian that's why I was messing up with it!

#

thank you so much!

#

I'm gonna give it a look then 🙂

#

I can't see the time in the chart, but that suggests me is again the same? i.e. dark lights over nights, bright lights during the day

#

well, never mind... I'll try with the ones with colors and see how it works

mighty ledge
#

They both might do the same thing, as I said, I've never used either. Both have a plethora of extra parameters that change the behavior. A parameter in them may or may not exist that gives you the behavior you're looking for.

chilly ferry
#

Yeah, I don't think they do, I'm just trying a transition of 30 minutes with one of my bulbs and didn't fail, but not sure if it's working the way I'd expect

mighty ledge
#

@marble jackal I played around with context

#

in a script context will give you the current context this run, this.context will give the last time the script was called's context