#templates-archived

1 messages · Page 100 of 1

mighty ledge
#

that could be built in, same with a total list that gets appended to.

#

I have to get back to work though

dapper bridge
#

thanks for helping

#

I apprecaite it

#

I think python_script is the way to go - I didn't know about them

mighty ledge
#

@dapper bridge just realize you can't create methods in the python_script environment. So you won't be able to have a recursive function. You'll need to make a bunch of for loops and only go to a specific depth.

mighty ledge
#

@dapper bridge whelp, give it a try then. Last I remember, it wasn't possible.

#

memory could be wrong 🤷‍♂️

dapper bridge
#

memory could be wrong 🤷‍♂️
@mighty ledge It works! Thanks for your help

tropic hill
mighty ledge
#

@tropic hill your indentation is wrong for availability_template and you can simplify your template to:

{{ is_state('switch.shelly_shsw_pm_006037', 'on' ) or is_state('switch.shelly_shsw_pm_006037', 'off') }}
karmic oar
#

lordt this is driving me nuts. Can someone spot the reason my switch won't replace my variable with the proper data? command_on: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states('input_text.chargelimit_value') }} >> /dev/null

narrow quiver
#

noob trying to make a template sensor from api response. Got it to work pulling one attribute, but not sure formatting now if i do it within this same template, or if i create another sensor for each attribute / key and template for then grouping all the responses.

mighty ledge
#

@narrow quiver make 1 rest sensor to peel the information from. Place the whole json object into attributes, then use template sensors to grab the data out.

narrow quiver
#

Okay do I just shorten the value template aspect of that then to not be specific

steady trout
dreamy sinew
#

Does it show on the devtools > states entry for that entity?

steady trout
#

nope

#

because it's not part of the entity (I do not want the last_updated that comes when the value changes)

dreamy sinew
#

Probably SoL then

steady trout
#

but the last time HA received a message from this device

#

Probably SoL then
@dreamy sinew pardon me but... what's SoL ? 🙂

dreamy sinew
#

S**t outta Luck

steady trout
#

oh ok 🙂

orchid onyx
#

hi, i’m having a sensibo, (climate) and i am trying to exclude the fan as a seperate etinity - true that i need to use fan template ?

dreamy sinew
#

Haven't messed with that device but you could try it

silent barnBOT
orchid onyx
#

Thx, I have searched alot for exemples but can’t find alot that makes sense. Like this one :

’input_boolean.state’
What does input_boolean do? 🤦🏻‍♂️

dreamy sinew
#

Nothing on its own

#

Just a way to store a boolean value

orchid onyx
#

If I use the exemple you sent me, where do I write my climate entity? Cant figure that one out

dreamy sinew
#

configuration.yaml like the docs say

orchid onyx
#

So where it says: ’bedroom_fan:’ i should write ’climate.hall:’ ?

dreamy sinew
#

No

#

That like is the name of your new fan entity

orchid onyx
#

Ok, that’s what i Mean, where in this template do I link my climate...

mighty ledge
#

@narrow quiver you want to make sure your value template is a result that continuously changes. So it doesn't matter what you put in it as long as the main state field updates (value_template links to the main state field).

little gale
#

How do I set volume_mute in Universal Media Player
I've tried:

    volume_mute:
      service: media_player.volume_mute
      data:
        entity_id: media_player.ht_z9f_2
        is_volume_muted: '{{ is_volume_muted }}'
little gale
#

invalid boolean value {{ is_volume_muted }} for dictionary value @ data['is_volume_muted']

bronze mango
#

Question with jinja and yaml: how can I put a multi-line yaml variable into a jinja yaml template and have it properly indent the multiline value?

thorny snow
#

Hey You! Thank you for reading this 🙂 The following is an event that i am passing to an automation. I need to get the values from "event_response" to pass them in an Delay action. When i try:

seconds: '{{ event_response }}'
i get an error that there is no float in this variable and i noticed that it this variable is nothing (like a space)
The event_response_type is catching normal in the trigger... So how i can traslate it so the Delay action understands the number in event_response in seconds?
{
"event_type": "alexa_actionable_notification",
"data": {
"event_id": "actionable_notification_kucheon",
"event_response": 3,
"event_response_type": "ResponseDuration"
}

bronze mango
#

I found I could do something like {{ my_var | indent(width=6, indentfirst=False) | default('') }} but wasn't sure if there was something less fragile (i.e., if the rest of the YAML template changes and that indention line changes, I have to adjust that width value)

thorny snow
#

invalid boolean value {{ is_volume_muted }} for dictionary value @ data['is_volume_muted']
@little gale where did you got the is_volume_muted variable?

karmic oar
#

Can someone spot the reason my switch won't replace my variable with the proper data? command_on: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states('input_text.chargelimit_value') }} >> /dev/null

ivory delta
#

Is it just not evaluating the template, @karmic oar?

#

Does the correct command get executed but with the literal template as part of the path?

karmic oar
#

Yes, exactly

#

The same thing worked in my rest_command before I switched it to a command_switch

#

I've tried every iteration of quotations I could think of and it works in the template editor

ivory delta
#

You've tried wrapping the whole command in quotes?

karmic oar
#

I have

ivory delta
#

I can't find the page I saw the other day but there's a note on shell commands and elevated privileges. Something about not being able to use templates because it runs in a different context.

#

Are you able to do the curl without ssh?

#

D'oh. It's on the shell_command page, I just glossed right over it:

When using templates, shell_command runs in a more secure environment which doesn’t allow any shell helpers like automatically expanding the home dir ~ or using pipe symbols to run multiple commands.

karmic oar
#

Well apparently so did I

ivory delta
#

Try without piping to null?

#

The template itself should be fine. I remember someone having similar issues recently and they got templates to work.

karmic oar
#

No, I can't. Because I can't set up my reverse tunnel to port 22222 (home assistant host), I have to ssh to another pi on my network and run the curl command there instead

ivory delta
#

Makes sense. Skip the pipe to null?

karmic oar
#

?

ivory delta
#

>> /dev/null

karmic oar
#

No effect.

#

I added that hoping it was the curl response preventing the command from working

ivory delta
#

Hmm. I'm outta ideas. I'm a rookie when it comes to Linux.

karmic oar
#

If I could just get my reverse tunnel set up to the host I'd be all set

#

Then I could just use rest commands instead

#

Unfortunately it appears the ONLY way to setup ssh keys to the host is to import them from USB

charred dagger
#

The same thing worked in my rest_command before I switched it to a command_switch
@karmic oar see how in the docs rest_command says ”(supports template)”, but command_switch does not? I’d guess that has something to do with your problems. FR time?

karmic oar
#

We established that already. Thanks.

charred dagger
#

Oh. Sorry. Must have missed that. My bad.

karmic oar
#

Got any gouge on how to get an SSH key set up for port 22222 that doesn't involve importing from USB?

charred dagger
#

I must be having some problems with discord dropping messages or something, because this entire exchsnge makes no kind of sense to me, so I better drop out of this. But I’ve had quite a few problems with ssh from hass - all of which were related to the hass docker container running as root rather than as a user. After making my own dockerfile to fix that things worked much better.

karmic oar
#

I just need to be able to access the host

#

Normally to get SSH access you'd follow the instructions for importing a key via USB

#

I run HA in a VM so I can't. No way to do USB passthrough

cerulean cipher
#

I run HA in a VM so I can't. No way to do USB passthrough
@karmic oar what hypervisor? because I know you can do USB passthrough with virtualbox and with vmware

karmic oar
#

My VM is in FreeNAS

elder moon
#

is it allowed to use # comments in multiline templates ?

rugged laurel
#

You can use jinja comments

#

{# My awesome comment #}

granite pilot
#

Hey. Not sure if this is the right place but here we go:

Is it possible to combine scripts to define an entity of its own?

I have an ac unit which I cannot directly integrate with. So I'm doing it through ifttt and scripts into home assistant.

I am going to create turn on and off scripts.
Turn up and down the temperature scripts.

Would be nice if I could template a air conditioner device somehow like mqtt devices or adb devices.

little gale
#

@karmic oar
Does this work?
command_on: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 -t curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states('input_text.chargelimit_value') }} > /dev/null

#

How do I set volume_mute in Universal Media Player
I've tried:

    volume_mute:
      service: media_player.volume_mute
      data:
        entity_id: media_player.ht_z9f_2
        is_volume_muted: '{{ is_volume_muted }}'

Any help guys??

karmic oar
#

It shouldnt

#

A shell command won't evaluate variables

rugged laurel
#

it does

karmic oar
#

Well, it certainly hasn't yet.

rugged laurel
#

You need to quote the entire line

karmic oar
#

I've tried that. I've tried every variation of quotation I could think of

#

Almost everything works in the template editor. Nothing works in practice.

#

Command failed: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states("input_text.chargelimit_value") }} >> /dev/null

#

That's all I ever see

rugged laurel
#

Why ssh to a remote to execute a curl?

karmic oar
#

Because I don't have access to my host

#

So the reverse tunnel to port 44462 is set up to another rPi instead and I SSH there to run the command

#

Otherwise if I could set up my reverse tunnel directly to the host I would do that and just use a rest command

#

But I can't do that

#

Because the only way to set up SSH to the host is by importing keys via USB

#

and I can't do that

#

Because I run HA in a VM on FreeNAS that doesnt allow USB passthrough

#

I tried manually entering my key via VNC to my host

#

But I've either still got a typo or I've got the key stored in the wrong spot

#

Either way, documentation is lacking

rugged laurel
#

K

karmic oar
#

Yeah, that's about the response I normally get.

ivory delta
#

@karmic oar Are you certain the rest of the command is valid and working? I remember that the log entries echo out the template and not the evaluated value of said template. I would ignore the unevaluated template in the logs - it's probably a red herring.

karmic oar
#

I'm actually trying the shell_command now. Before some of the users were confused as I was using the command_line switch. I'm trying to run a shell command now but it's still not evaluating the template correctly

ivory delta
#

Try the same command but insert a static value yourself. i.e.:

ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value=3 >> /dev/null```
rugged laurel
#

That will work, and so will

shell_command: "echo {{ states('input_text.chargelimit_value') }} > test.txt"
ivory delta
#

Well... it'll work if there's nothing wrong with that command and it connects to the target host okay.

#

Removing the template from the mix is just to prove it's probably not the template that's causing it to fail.

karmic oar
#

I'm rebooting now... but I think it's supposed to be this > set_chargelimit: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 "curl 'bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states("input_number.chargelimit_value") | int }}' > /dev/null"

#

Find out in a few minutes when it comes back up

ivory delta
#

Piping it to an int seems unnecessary since you're just immediately concatenating it onto a string... but wrapping the remote command in quotes might be a good shout.

#

Your next problem will be that you're not using mixed quotes 😉

#

The quotes starting at "curl end at states(".

karmic oar
#

Well I am... Double, single, double

ivory delta
#

Not in all the places that matter.

karmic oar
#

Since I tried just escaping them and the the validation tool got very upset

ivory delta
#

That's to be expected. devtools > Templates will want real quotes.

karmic oar
#

Okay, so that works

#

Will there? Most of mine use single quotes for all my sensors

#
        friendly_name: 'Solar Generation (Raw)'
        device_class: power
        unit_of_measurement: W
        value_template: "{{ state_attr('sensor.neurio_raw', 'channels')[3]['p_W'] }}"```
ivory delta
#

Single or double is fine, as long as you're mixing them to avoid the need to escape.

#

Valid: value_template: '{{ states("input_number.chargelimit_value") | int }}'
Also valid: value_template: "{{ states('input_number.chargelimit_value') | int }}"
Invalid: value_template: "{{ states("input_number.chargelimit_value") | int }}"

karmic oar
#

Right

#

Which is why I did Double, Single, Double

ivory delta
#

In your shell command, it looks like it's evaluating the template before trying the shell command, which is why it works.

#

If it looked at the pairs of quotes first, you'd have two double quoted strings and some gibberish in between.

#

But it works, which is what matters.

obsidian nacelle
#

If I want a notification message to contain the device and action that triggered it is that something I need to use a template for?

ivory delta
obsidian nacelle
#

Can't make much sense of that page to be honest

#

It doesn't explain the syntax of how to refer to an entity state

ivory delta
#

Inside of an automation, you can use the trigger object. You have information like the new state (to_state) an the old state (from_state).

So you could, for example, get the new value of whatever triggered the automation using {{ trigger.to_state.state }}

#

Likewise, you can get its friendly name with {{ trigger.to_state.name }}

obsidian nacelle
#

Sorry I don't understand what you mean by that and it doesn't look like anything I'm seeing in the automation triggers YAML or the states > entity view

ivory delta
#

Why would it look like anything in States? It's a template. States are just single values.

#

It watches for the change in state of two switches. It doesn't matter which one changes, the template near the end knows what the new value of that switch's state is.

obsidian nacelle
#

I have an entity called sensor.26c2_battery - if I want to include the current state in a message would that be {{ state.sensor.26c2_battery }}?

ivory delta
#

Better to use the states function in case it doesn't return a value: {{ states('sensor.26c2_battery') }}

#

But that's nothing to do with what 'triggered' anything...

obsidian nacelle
#

How would you refer to the triggering state change then?

ivory delta
#

🤦‍♂️

#

I gave you an example. Scroll up.

#

I don't know what part you don't get, so I don't know how to make it any clearer.

obsidian nacelle
#

Tried making the notify message {{ trigger.to_state.state }} and it changed to '[object Object]': null after saving

#

🤷‍♂️

ivory delta
#

What are you actually trying to do and what don't you understand?

#

So far your feedback has essentially been 'I don't get it'.

obsidian nacelle
#

I have 10 devices that can send tilt, vibrate or drop alerts. When any device does any of those 3 things I want to trigger a noticifcation that says 'device' has 'dropped/tilted/vibrated

#

I have one automation with all the triggers and I want the Action to be Call the service and send a message that says what trigger has fired

ivory delta
#

I'm not sure how my previous answers don't give you the solution 🤷‍♂️

obsidian nacelle
#

ok thanks for your help

slim sage
#

Is there some way to set a temporary variable within a sensor template? I have over 30 door sensors I want to check, and I want to generate a sensor that outputs the status of any that match a condition. e.g. if door's X and Y are open but the other 28 are closed, the sensor would read: "Door X is open. Door Y is open.". Ideally, I would set a few temporary variables, "sensorText", "sensorName" and "desiredState". If sensorName.state != desiredState, then text should be "sensorText sensorName is sensorName.text", otherwise the text should be nothing. I'd then list out all 30 entities with those three variables set, so that the sensor is blank if everything is closed, and only looks like "Door X is open. Light Y is on." if the entities are not in the desired state.

#

Ultimately I'm seeking to have a service named "going to bed" that then sends me a message on telegram confirming that it has run the necessary things (e.g. turned off some lights) but also report out on any door/window sensors that aren't in their desired state. I think the sensor is the best start.

dreamy sinew
#

You can make variables in jinja but they only live in the context of that one template

slim sage
#

@dreamy sinew Thank you, that helps. I'll start digging into it.

paper hazel
#

Is it possible for 'wait_template' to have multiple entities in it? For E.g: ```
wait_template: {{ is_state('binary_sensor.alarm_part1', 'on') AND is_state('binary_sensor.alarm_part2', 'on') AND is_state('binary_sensor.alarm_part3', 'off' AND is_state('binary_sensor.alarm_part4', 'off')) }}

buoyant pine
#

Yes, but don't capitalize "and"

paper hazel
#

Cool! I got an error with the capital letters, then built this workaround which might work, but if the lower case and works its first prize. Appreciated!```
wait_template: >-
{% if is_state('sensor.risco_alarm_garage_status', 'armed_away') and
is_state('sensor.risco_alarm_outside_status', 'armed_away') and
is_state('sensor.risco_alarm_living_area_status', 'armed_home') and
is_state('sensor.risco_alarm_master_bedroom_status', 'armed_home') -%}
True
{%- else -%}
False
{%- endif %}

buoyant pine
#

Better off using what you had first and making the AND lowercase

rose pawn
#

Hi guys! Does anyone know how I can create a volume slider? Right now I have several buttons that control the volume of my home HiFi in intervals of 10 but it is pretty ugly and bad for voice assistants.

buoyant pine
#

input_number and an automation that fires whenever the state of that slider changes

inner mesa
buoyant pine
#

Ah thanks

undone shard
inner mesa
#

‘Doesn’t work’ means what?

undone shard
#

When I use the 'check configuration' from the server controls, I get the some what cryptic: Invalid config for [sensor.template]: [unique_id] is an invalid option for [sensor.template]. Check: sensor.template->sensors->ac_history_stats_hrs->unique_id. (See ?, line ?).

inner mesa
#

hmm, works for me

#

VSCode doesn't like it, but config check passes

#

I'm using 0.114.1, tho

undone shard
#

Thanks RobC, I'll pull the new docker image tomorrow and see if that resolves my issue

inner mesa
#

is the last line really on a separate line?

#

it looks like you have a newline, with the second half of the expression starting at the beginning of the next line

#

or maybe it's wrapped and is confusing pastebin

undone shard
#

no, it's all on 1 line..i

#

I messed it up when I paste.ubuntu 'd it

inner mesa
#

ok. yeah, I dunno. I didn't know that you could manually assign unique IDs, so that's news to me

undone shard
inner mesa
#

I'm trying to find it in the release notes, but failing so far

#

docs were updated 14 days ago

#

I'm guessing it came into 0.114

#

Add optional unique_id attribute to the template platforms (@michaelarnauts - #38011) (template docs)

undone shard
#

I just looked at that 'pull note' < sorry i don't know the prpoer term

dreamy sinew
#

Pull Request

undone shard
#

Thank you ---

inner mesa
#

I’m mainly just satisfying my own curiosity

undone shard
#

Thanks again folks, I will pull the newer docker tomorrow and try this again

nocturne chasm
#

anyway to get uptime with this mess?
{{now().strftime('%H:%M') - state_attr('binary_sensor.ozw_network_status', 'TimeStamp')|timestamp_local }}

dreamy sinew
#

I hate working with time in templates

inner mesa
#

Me too. I’m never surprised when it doesn’t work 🙂

#

‘I’ll be of no help here, moving on’ 🙂

orchid onyx
#

Hi, trying to create a fan from a climate integration. Here is an error I got, what could be wrong
Invalid config for [fan.template]: required key not provided @ data['fans']['hall_fan']['turn_off']. Got None required key not provided @ data['fans']['hall_fan']['turn_on']. Got None. (See ?, line ?).

obsidian nacelle
#

I get the same error even if I remove {{ trigger.from_state.state }} from the message

nocturne chasm
#

Are you triggering it through the device or the UI?

orchid onyx
#

@nocturne chasm you have a clue for my problem? 2 posts up...

nocturne chasm
#

No, is your yaml consistent with the docs. Use hastebin to post what you have done

silent barnBOT
orchid onyx
obsidian nacelle
#

@nocturne chasm through the device

obsidian nacelle
#

So now is there some way of making it so if ANY sensor state changes to drop, or tilt it will trigger and send {{ trigger.entity_id }} and {{ trigger.to_state.state }}

brisk temple
#

is there a generic entity you can use for an else in a data_template? Similar to homeassistant.update_entity in a service_template? I don't want anything to happen

#

i guess i can just create a input_boolean that does nothing

mighty ledge
#

@obsidian nacelle you can't use state triggers, you'd have to use event triggers for that

#

which would completely change your template as well

#

@brisk temple make a condition template prior to that action

brisk temple
#

ya, i definitely need a condition, it triggers the action non-stop

#

but needed the kids to go to school and wife to work so i can think

mighty ledge
#

yes, so put a condition prior to the action and the action wont execute. Instead of a 'blank entity' in the else.

#

post your action section and I can help.

obsidian nacelle
#

I can't see any examples for that - I imagine its not an that uncommon - to have multiple motion sensors and an automation that alerts which one has triggered

brisk temple
#

the sensor.stats_ states update constantly while they are on their laptops, it's a history_stats sensor

mighty ledge
#

you should just make 2 template sensors

#

well, lets take a step back.

#

how are you populating input_text.aislin_laptop_time?

brisk temple
#

that actually isn't needed in the trigger state, i just took it out, but it's manually done setting how many minutes the kid can be on the electronics

mighty ledge
#

ah ok

#

and sensor.stats_aislin_laptop_daily updates once a minute?

brisk temple
#

i was thinking of a or template condition that would filter until the time is under 7 minutes for each

#

it's a history_stat sensor and i couldn't find the refresh interval

mighty ledge
#

ok

brisk temple
#

it's fed by a ping sensor, so if that's the interval every 5 seconds

mighty ledge
#

and you just want to notify at 3 minutes and 7

brisk temple
#

ya

mighty ledge
#

you don't want a notification every 5 seconds either

brisk temple
#

i have another automation that initiates the notification only once, when the input_boolean turns to on

mighty ledge
#

Ok, if you make these 2 sensors:

#
sensor:
- platform: template
  sensors:
    notify_orla_laptop:
      value_template: >
        {% set child = 'orla' %}
        {% set v = (states('sensor.stats_orla_laptop_daily') | float * 60) round(0) | int %}
        {% set t = states('input_text.orla_laptop_time') | int %}
        {{ t - v }}
    notify_aislin_laptop:
      value_template: >
        {% set v = (states('sensor.stats_aislin_laptop_daily') | float * 60) round(0) | int %}
        {% set t = states('input_text.aislin_laptop_time') | int %}
        {{ t - v }}
#

they will count down.

brisk temple
#

k i actually have a count down senor for that

mighty ledge
#

ok, then why are you doing the input booleans?

#

if you already know when 3 and 7 minutes are hit?

brisk temple
#

i wasn't sure it would hit exactly

mighty ledge
#

why even turn on booleans?

#

are you firing a script?

#

if you have the countdown sensors, build an automation based on the count that notifies the correct script based on the number

#

no need for input booleans

brisk temple
#

and then in the action do the notification?

mighty ledge
#

yea, unless you have different messages. But if you're just saying '3 minutes' or '7 minutes', just do that.

#

using the sensors I posted above...

#
trigger:
- platform: state
  entity_id: sensor.notify_orla_laptop, sensor.notify_aislin_laptop
condition:
- condition: template
  value_template: "{{ trigger.to_state.state | int in [ 3, 7 ] }}"
action:
- blah
#

I can help you with the action, but i'd need to see what you intend to notify.

brisk temple
#

thanks, i'll give it a go

mighty ledge
obsidian nacelle
#

I read that but it didn't help, thanks.

mighty ledge
#

event_type would be state_changed

#

{{ trigger.event.data.entity_id }}

#

you'll have to register to the event to see the shape of data to properly grab out the to_state.state. I would assume it's:

trigger:
- platform: event
  event_type: state_changed
condition:
- condition: template
  value_template: "{{ trigger.event.data.to_state.state in ['tilt','drop'] }}"
action:
- service: persistent_notification.create
  data_template:
    message: "{{ trigger.event.data.entity_id }} reports {{ trigger.event.data.to_state.state }}"
    title: motion
mode: single
obsidian nacelle
#

thanks @mighty ledge, thats really helpful - just knowing to subscribe to events is very useful

mighty ledge
#

yep, it's in the developer tools > event tab

slim sage
#
{% set entityDesiredState = "off" %}
{% set entityTextToSend = "Door Sensor 3 is open" %}
{% if is_state(entityName, entityDesiredState) %}
  {# do nothing #}
{%else%}
  {{ countOfEntities }}) {{ entityTextToSend }}
  {% set msgText = msgText ~ newLineChar ~ countOfEntities ~ ") " ~ entityTextToSend %}
  {% set countOfEntities = countOfEntities + 1 %}
{%endif%}``` I am considering using this text 30+ times in a sensor, so that I have some text to send myself in a Telegram bot that reports out on every entity that is not in a desired state. (use case: heading to bed, want to know if any doors are open).   Any reason to not have such a lengthy and computationally complex sensor?
#

Ooh, I could maybe set up an array so that each device, desired state, and text to send is on one line, then i just iterate through the length of that array.

slim sage
#

Ok, that text works in the Template editor, but when I create a sensor template with it it only seems to update when HA is first started. How can I force this to update?

#

Ah, homeassistant.update_entity may work.

ruby vault
#

is there a way I can reload sensors only?

#
          {% if state == "50:1A:A5:4E:55:1F" %}
            Jabra
          {% elif state == "FC:62:B9:27:AC:6B" %}
            Golf
          {% elif state == "B4:EC:02:97:83:34" %}
            Tiguan
          {% else %}
            NotConnected
          {% endif %}
        {% endfor %}
#

this sensor works in the templating tool but not as a sensor.... trying to work out whats up but restarting every time is pain

inner mesa
#

nope, unfortunately

#

looks pretty straightforward. Can you share your whole template sensor definition?

buoyant pine
#

Yeah, also explain what you mean by not working

ruby vault
#

so the sensor, right now with noting connected... shows nothing as the state.. but when it was connected to the 'Tiguan' showed, 'NotConnected'.

#

and with the Jabra connected, it actually shows Jabra.

#

now funnily in the teplating tool, I am just realising it is not showing 'NotConnected'. hmpf

#

so I am thinking it is not looping, since htere is nothing in the attr array

inner mesa
#

I'm pretty sure you could do that better with a map

ruby vault
#

sure but I think I need an if that checks the length of the list first.. if the list is length 0 then say Not Connected... else a case/family of if statements

inner mesa
#

kinda confused what that's trying to do

#

do you want one thing out of that whole for statement or several things?

ruby vault
#

well the attr connected_paired_devices is a list

inner mesa
#

sure, so you could do something like this:

#

blah. There's almost certainly a better way to do that, but I need to devote more brain cells than are currently available 🙂

ruby vault
#

seems to get me closer

inner mesa
#

I don't think you really want a for, but instead a set of if xxx in "connected devices"

ruby vault
#

ah, yeah. True

inner mesa
#

and it would bail after the first one found

ruby vault
#

well the for would return the first one found also

inner mesa
#

it actually won't

#

it will go through all the connected devices

#

that's where it starts to confuse me

ruby vault
#

ah, yeah. so you would get the last

inner mesa
#

yep

#

which could be your problem

ruby vault
#

does jinja have a case statement?

#

can I say 'if NotNull in "connected devices' somehow?

inner mesa
#

(you can set a variable at the top for the state_attr() clause and simplify the rest...)

#

what are you trying to do with "NotNull"?

ruby vault
#

oh, just the length test.... eg. there being a mac address I dont' recognose vs being not connected

inner mesa
#

your length test is fine, IMO

ruby vault
#

n1

#

is there a function for variable assignment in jinja or asdf = blah

inner mesa
#

there's lots of Jinja documentation

#

🙂

ruby vault
#

yeah, but you were making life easy for me? 😛 lol

inner mesa
#

random example from the docs:

#
{% set iterated = false %}
{% for item in seq %}
    {{ item }}
    {% set iterated = true %}
{% endfor %}
{% if not iterated %} did not iterate {% endif %}
#

in your case, {% set devices = state_attr('sensor.jurgen_bluetooth_connection', 'connected_paired_devices') %}

ruby vault
#

yeah, I just found it. n1

#

I haven't really used jinja since my ansible days

#

Legend, tyvm for your assistance... super appreciated @inner mesa

inner mesa
#

np, glad to help

ruby vault
#

I could probably use 'set' in a lot of my templates, tbh

inner mesa
#

it's just template-scope, so kinda limited

ruby vault
#

yeah, sure but I have some hectic templates that are a ballache to read

inner mesa
#

helps to avoid typos, too. Or at least localize them 🙂

ruby vault
#

hey, one ting that has already annoyed me in HASS is when you restart... when you click on a sensor or switch the 'time since last state' is actually counting back to the last restart.... not the last state change..

inner mesa
#

I think that's a known issue. making "last_changed" restorable

#

I vaguely remember Paulus mentioning it recently

ruby vault
#

ok, I restarted. It seems to be looking better now. We will see over time

slow vine
#

is this valid syntax?

  condition:
    - condition: template
      value_template: "{{is_state('trigger.payload_json['TRIG'], 'SINGLE') }}"
inner mesa
#

Nope

#

You have an extra quote to start

#

I would get rid of is_state() and just use ==

slow vine
#

like this? value_template: "{{ trigger.payload_json['TRIG'] == 'SINGLE' }}"

inner mesa
#

Looks reasonable

slow vine
#

ok thanks.

mild hull
#

Hi all, I have a couple of template switches that are supposed to get their values from input booleans. I've noticed that only do they turn off a couple seconds after activation, but they always have an 'update for switch failed' message in the log whenever I restart. Is there anything I can do?

inner mesa
#

~share your templates?

silent barnBOT
mild hull
#

Thank you:

#

Hope I shared that right!

inner mesa
#

First thing I notice is that calling the scripts like that will cause them to run in parallel

#

Is that your intention?

mild hull
#

Yeah - I've set up some motion detected lights in the kitchen that turn off after X seconds of no motion. The idea is to have an option to turn the lights on via voice and keep them on, so the template turns the lights on and ignores motion detection

inner mesa
#

Point is that motion_stop and lights_on will run concurrently

mild hull
#

Ah OK. I haven't noticed an issue with its functionality to date, but if it could cause issues down the road how would I get them to run one after the other? Big fan of stability!

inner mesa
#

Change them to - service: script.xxx

#

If that doesn’t help, please share the scripts

mild hull
#

Just trying that now

inner mesa
#

I switched all of my scripts to run concurrently and then realized that order actually matters for some

mild hull
#

Just made the change and functionality is retained - thank you, I didn't know scripts could be called like that

#

Still having the issue of the switch value itself not being updated. When I turn it on/off/via alexa, the lights work, but the switch value doesn't change. When I flip the switch myself through the lovelace interface, the lights work fine, but the switch itself flips off after a couple seconds (but the lights stay on so that's good)

inner mesa
#

So nothing actually changed

#

Share the scripts

mild hull
#

Sure thing

#

Just mqtt messages really. Node red handles the logic

inner mesa
#

ah, the plot thickens

mild hull
#

Thankfully the lights themselves work exactly how I need them to

#

It's literally just that switch acting weird in lovelace, though it does what I want it to

inner mesa
#

there's nothing there that I can see that would cause the lights to turn off shortly after turning them on, so there must be something else going on

mild hull
#

Thats the strange thing - the lights themselves don't turn off, they work as intended

#

the lights stay on, but the switch in lovelace interface flicks back to off after a couple seconds

inner mesa
#

oh, I see that now

mild hull
#

If I didn't look at lovelace/error logs, I wouldn't even know there was an issue

inner mesa
#

you could just remove the value_template: completely if you like, and it will just assume that it turns on when you flip the switch.

#

oh, this is wrong:

#

is_state('input_boolean.kitchen_boolean')

#

you need to use is_state('input_boolean.kitchen_boolean', 'on')

#

that's probably causing both problems

mild hull
#

That did it! And helped clean up my config/script code! Thanks a lot

inner mesa
#

np. couldn't see it staring at my phone, but it was clear when I pulled out my laptop 🙂

hollow girder
#

Hello, is it possible when defining, or loading, a input_select to define a value/label pair? Like display Heat but the value is heat! Or display Eco Mode but the value is eco! Or to use in channels display Name but the value is the channel number!..

ivory delta
#

Nope

#

Not for the input itself. You'd have to do template magic to go from a display value to some other value.

noble herald
#

Hello, hope i'm in the good channel, otherwise, i'm sorry but i was creating a script and it throws me an error to the last line column 14 and i don't know what is bad, can you help me ? ```yaml
test:
alias: Test Script
mode: single
sequence:

  • data_template:
    entity_id: input_select.select_sound_cdj_speaker
    service: input_select.set_options
    options: '{{states(''sensor.cdj_speaker_sounds_list'')|from_json}}'
#

Why is there a red cross emoji on my message ?

#

ah ok, i will post my code to hastebin

inner mesa
#

because it's not valid YAML

noble herald
#

i don't see where is the problem

inner mesa
#

if you really have those '' instead of ", that's a problem

noble herald
#

i need to change the last line to that ?```yaml
options: '{{states("sensor.cdj_speaker_sounds_list")|from_json}}'

inner mesa
#

you have to nest things properly

noble herald
#

in the examples, there's not an example with a sensor state

inner mesa
#

that doesn't matter

#

options: and entity_id: are both children of data_template:, but that's not what you're written there

#

your indentation and ordering are wrong

noble herald
#
  - data_template:
    service: input_select.set_options
      entity_id: input_select.select_sound_cdj_speaker  
      options: '{{states("sensor.cdj_speaker_sounds_list")|from_json}}'
inner mesa
#

still wrong 🙂

#

follow the examples

#
  - service: input_select.set_options
    data_template:
      entity_id: input_select.select_sound_cdj_speaker  
      options: '{{states("sensor.cdj_speaker_sounds_list")|from_json}}'
#

there may be other issues, but at least that's the properly format

#

see the difference?

noble herald
#

i'm trying what you've wrote

#

and i will tell you

silent barnBOT
noble herald
#

what is the best way to do ?

#

the 2nd i think

inner mesa
#

I can't tell what's going on there

silent barnBOT
noble herald
#

ok

#

i'm restarting hass with the first to try and see

#

ok the script runs well but not add the options like i want

#

this is the state of the sensor ["beep","cigales","humans","test"] and this is the only option i have in the input select ['beep', 'cigales', 'humans', 'test']

#

do you know to get that working properly

inner mesa
#

you don't like the quotes?

#

otherwise they're the same

noble herald
#

i have not write that ['beep', 'cigales', 'humans', 'test'] myself

#

it's the script

#

you don't like the quotes?
i've no problem with quotes

#

i don't understand where the problem is because when i do the trick manually it works but not when the script does that i explain :

#

when i paste {{states("sensor.cdj_speaker_sounds_list") | from_json }} in the template dev tools it outputs me ['beep', 'cigales', 'humans', 'test'] and if i paste this in the options : in the service call dev tools it works well and set the options according to the list but when the script does this the only option in the input select is ['beep', 'cigales', 'humans', 'test'] do you know what's going on ?

#

RobC help me please I beg you

inner mesa
#

why are you using "|from_json" if the state, as you mentioned earlier, isn't JSON

noble herald
#

this ["beep","cigales","humans","test"] is json no ?

inner mesa
#

that's a list

#

just like in teh example

noble herald
#

yes but a json formatted list

noble herald
#

yes i know but i just tested without |from_json and it is the same problem but now the ' ' framing the item are now " "

#

so, that doesn't solve the problem

#

i forget to mention but the state of the sensor comes from a command line sensor

buoyant pine
#

The problem is that templates always return a string even if it looks like a different data type

#

So while that looks like a list, it's actually a string since it's the result of a template

noble herald
#

and it can't be converted into a list ?

buoyant pine
#

Nope

noble herald
#

so, what i want to do is impossible ?

buoyant pine
#

Is it going to be a fixed length list?

noble herald
#

no but i can put a limit if necessary

buoyant pine
#

You'd basically need to ensure the list is a fixed length and then do something like

data_template:
  options:
  - "{{ states('input_select.whatever')[0] }}"
  - "{{ states('input_select.whatever')[1] }}"
    ...
noble herald
#

i will explain what my first need is. I want an input select have all the filenames in separate options of a linux folder in a raspebery pi without the extension visible if possible so like that i can choose i file in the frontend and call a script with the state of the input select inside it

buoyant pine
#

What is the ultimate goal here though

noble herald
#

to have a play button aside from the input select and be able to start playing a music on the raspberry pi 3.5mm jack but i want to have the hability to upload new .wav files in the specified folder in ftp and that home assistant refreshes the input select automatically or with a refresh button

#

the only part that is not working for now is the automatic update of the input select, all of the rest works perfectly fine

#

but if it is impossible to do, i will add options to the input select manually but this is not very fun to do

#

😢

#

so, i can conlude this isn't possible ?

buoyant pine
#

Not in they way you're trying at least. Home assistant isn't really meant to be a media server though

noble herald
#

yes i know

noble herald
#

Thank you anyway

dusky bison
#

Hi everyone. I'm having an issue with a light template whereby using unique_id results in an invalid option error although it's in the documentation. https://www.home-assistant.io/integrations/light.template/#unique_id

Invalid config for [light.template]: [unique_id] is an invalid option for [light.template]. Check: light.template->lights->living_room_light->unique_id. (See ?, line ?).

light:

  • platform: template
    lights:
    living_room_light:
    unique_id: living_room_light

Home Assistant 0.113.2

ivory delta
#

If you want to use all the newest features, you need to be on the newest version. You're a major version behind.

#

I believe the unique_id fields were only added in 0.114, @dusky bison

#

If you follow the link from the docs to the GitHub for that integration, you can see the commit that added that feature was only made 17 days ago.

dusky bison
#

@ivory delta Thanks. That makes perfect sense.

coarse tiger
#

I want a sensor to tell me how long I'm away from home -
device_tracker.me_2 is my mobile phone which shows that I left home as 08:10 and arrived at work at 08:24

though {{ states.device_tracker.me_2.last_changed }} reports 09:00

dreamy sinew
#

create 2 input_datetimes. Create 2 automations, one to set one of the inputs when you leave, one to update the other when you get home. Add a template sensor to subtract 1 from 2

#

would probably need additional handling for when you're currently away

coarse tiger
#

alright, thanks @dreamy sinew

silent barnBOT
orchid onyx
#

Anyone?

hollow bramble
#

You're missing required entries for turn_off and turn_on

orchid onyx
#

So this part
{% if states('climate.hall') in ['heat_cool','heat','cool','dry','fan_only'] %} on {% else %} off {% endif %}
dont help me a shit then?

#

Thx

hollow bramble
#

That just defines the state. You still need to give it services for turn_on and turn_off

orchid onyx
#

Will this solve my problem:
turn_on: service: climate.turn_on data: entity_id: climate.hall turn_off: service: climate.turn_off data: entity_id: climate.hall

#

No error so I will try now 🤩

#

Wow it works, thx alot. Been trying to make this work for weeks now,

#

thx alot for help

orchid onyx
#

Can you explain what thisone does:
oscillating_template: > {% if is_state_attr('climate.hall', 'swing_mode', 'Off') %} False {% else %} True {% endif %}

hollow bramble
#

Defines a template to get the osc state of the fan. Valid value: true/false

orchid onyx
#

I have those modes avaible:
swing_modes: stopped, fixedTop, fixedMiddleTop, fixedMiddle, fixedMiddleBottom, fixedBottom, rangeFull
should I use this instead to controll osc:
oscillating_template: "{{state_attr('climate.hall', 'swing_mode')}}"
and
set_oscillating: - service: climate.set_swing_mode data_template: oscillating: "{{ oscillating }}"

#

The code worked but the result is these:
`speed_list:

  • quiet
  • low
  • medium
  • medium_high
  • high
    oscillating: null
    speed: null
    friendly_name: Sensibo fläkt
    supported_features: 3` so it did not work :/
ivory delta
#

If you use 3 backticks at each end, those code posts will be a lot less ugly 😉

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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

orchid onyx
#

Thx for info, learning something all the time 😄

silver pewter
#

me and my wife charge both our phones in the same smart power outlet. Is there a template i can use to turn off the plug when both phone is above 80%? I'm really new to this,
If anyone can write a template that would work would be really nice! 😄

dreamy sinew
#

an automation with a template trigger

#

{{ states('sensor.phone_a_batt')|int > 80 and states('sensor.phone_b_batt')|int > 80 }}

silver pewter
#

Thank you so much !!! 😄

silver pewter
#

{{ states('sensor.phone_a_batt')|int > 80 and states('sensor.phone_b_batt')|int > 80 }}
@dreamy sinew Thanks it works 🙂 But i use the battery sensor from HA android app. Is there any better way to get battery sensor that updates more often ? 😄

inner mesa
#

The phone charging mode should mostly take care of the problem that I think you're trying to solve

silver pewter
#

What do you mean ? 😛

inner mesa
#

if you're just trying to avoid charging to 100% to avoid stressing the battery, most modern phones take that into account. iOS tracks your battery usage/charging behavior and dynamically chooses how much to charge and when to stop

#

in other words, you'd be gaming something that's already optimized

silver pewter
#

oh ok i did not know that! i have a huawei p30 😛 must look that up 🙂

#

p30 pro *

ivory delta
#

Since this isn't the first time you've asked this question, I'm going to repeat my answer from last time - modern battery tech doesn't 'remember' charging like old battery tech did. What you're trying to do is a complete waste of time, even on Android.

buoyant pine
#

@ivory delta but charging to 100% reduces the overall number of charge cycles you get out of the battery before it reaches EOL (supposedly)

ivory delta
#

I'm sure that's a myth. I remember Apple's official guidance on it was always that charging from 50% to 100% only counts as half a charging cycle for the purposes of working out total battery life.

#

Unless you discharge and recharge, it's not actually contributing to wear.

#

The IC's in the chargers take care of overcharging.

silver pewter
#

it it the first time about charging 🙂

inner mesa
#

I think the only no-no is leaving it completely discharged for long periods of time?

#

which happens to all the gadgets in drawers and closets

buoyant pine
#

Indeed, leaving it discharged for a long time isn't great

ivory delta
#

I've been charging my 3-year old mobile to 100% every night forever. Still only gets back down to about 60-65% at the end of a day.

buoyant pine
#

Wait, we're in templates, oops

ivory delta
#

No noticeable decrease in capacity over 3 years.

inner mesa
#

My Apple pencil died from lack of use and wouldn't work at all

#

somebody else started it...

buoyant pine
#

@ivory delta A N E C D O T A L E V I D E N C E

#

Jk, idk. I'm not an expert

ivory delta
#

If I had thousands of devices to test, I'd be happy to carry out a more thorough study 😉

buoyant pine
#

any battery experts here?

inner mesa
#

and the plural of anecdote isn't data 🙂

#

fat chance they'd be hanging out in templates

buoyant pine
#

Is jōk

silver pewter
#

Then i use the template to turn off the charger when both is at 100% 😄

buoyant pine
#

NO DONT!

#

Jk

uneven edge
#

Hi everybody. I am planing to create a floorplan using https://www.youtube.com/watch?v=XV4xzgraNEk using Drzzs tutorial. I'm planing to add a binary sensor using zwave and phoscon. However, I'm don't understand what is platform, state_topic and name in this yaml. I gone through the doc but still don't understand how the yaml works for binary sensor..

#

any tutorial can cover this topic?

inner mesa
#

It’s a tall order to ask folks to watch a video to figure out what you’re asking about 🙂

#

It sounds like you need to research MQTT sensors

uneven edge
#

Sorry for that. Let me simplify. I am using Zwave sensor and switchs to create a 2D floor plan but i don't really understand how binary sensor setting in yaml. any tutorials link can cover more about this part of yaml? i watch few video but difficult for me to links the dots together

inner mesa
#

Yes, the documentation

silent barnBOT
inner mesa
#

Actually that’s not a good link. You need to look for the type of binary sensor that you care about

#

Etc

uneven edge
#

Thanks for the quick response and the links. I noticed that each binary sensor type have difference setting and i should not blindly follow the tutorial yaml setting. Newbie here😅 . Thanks for clearing that up and navigate me to the correct direction. Appreciate your help.!

graceful iris
#

Hey...
I'm trying to show IP as a mqtt sensor with the following configuration

- platform: mqtt
unique_id: oTeWg7KnYNo36rqBdbGJCsiWCDt
name: "testroom_main_light_ip"
state_topic: "tasmotas/testroom_main_light/tele/INFO2"
value_template: "{{ value_json.IPAddress | string }}"
availability_topic: "tasmotas/testroom_main_light/tele/LWT"
payload_available: "Online"
payload_not_available: "Offline"
icon: mdi:eye
#

But I'm getting unknown state

wary helm
#

I have a template for the outside temperature that only refreshes every 3 hours.
Can I change the refresh rate or is this because of the integration not refreshing?

      outside_temperature:
        friendly_name: "Outside Temperature"
        unit_of_measurement: '°C'
        value_template: "{{ state_attr('weather.home', 'temperature') }}"

I've tried the met.no integration aswell as the météo france integration

buoyant pine
#

template sensors update when the entities referenced in them update, so this would be an issue with the weather integration

zealous jacinth
#

Hey everyone, I'm using a led strip where the effects change (add/removed). I have a list of the effect names sent over mqtt-json. Is there a way to make a template for the effect_list?

quick crane
#

Hi
I have to make a daily and cumulative counter which feeds according to the state of a sensor. I created a counter but I do not know how to retrieve the value of the sensor to increase the value of the counter.
Regard

brisk temple
#

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

chrome temple
safe hemlock
#

Hey guys! wondering if someone can help with a data_template? Im trying to use input text to send a song or artist to the alexa integration.

#
  • alias: Select Music on Alexa
    trigger:
    • platform: state
      entity_id: input_text.music_select
      action:
    • service: media_player.play_media
      data_template:
      entity_id: media_player.kitchen
      media_content_type: "AMAZON_MUSIC"
      message: "{{ states.input_text.music_select.state }} in everywhere group"
ivory delta
#

states.input_text.music_select.state? 🤔

safe hemlock
#

Im trying to return the text entered and am confused

ivory delta
#

states('input_text.music_select')

safe hemlock
#
  • service: media_player.play_media
    data_template:
    entity_id: media_player.kitchen
    media_content_type: "AMAZON_MUSIC"
    message: "{{ states('input_text.music_select') }} in everywhere group"
#

like that?

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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

ivory delta
#

Looks better. Try it out and see what happens. But you didn't tell us what's actually wrong, I'm just pointing out the obvious mistakes.

safe hemlock
#

Just does nothing lol

ivory delta
#

It'll do something, even if that something is an error in the logs.

safe hemlock
#
- alias: Select Music on Alexa
  trigger:
    - platform: state
      entity_id: input_text.music_select
  action:
    - service: media_player.play_media
      data_template:
        entity_id: media_player.kitchen
        media_content_type: "AMAZON_MUSIC"
        message: "{{  states('input_text.music_select')  }} in everywhere group"
#

Ill check the logs

inner mesa
#

it might not like this: message: "{{ states('input_text.music_select') }} in everywhere group"

ivory delta
#

If you're using it in an automation, you can also use the trigger object in later steps. The new state of whatever changed would just be trigger.to_state.state

inner mesa
#

try

#
message: >-
  {{ states('input_text.music_select') }} in everywhere group
#

but just kinda guessing without anything in the logs indicating a problem

safe hemlock
#

While executing automation automation.select_music_on_alexa
4:14:01 PM – Automation (ERROR)
Select Music on Alexa: Error executing script. Invalid data for call_service at pos 1: extra keys not allowed @ data['message']
4:14:01 PM – Automation (ERROR)

ivory delta
#

😉

#

So you need to check which keys that service does allow:

silent barnBOT
safe hemlock
#

now im even more confused lol

ivory delta
#

It tells you that media_player.play_media takes 3 arguments, none of which are optional: entity_id (the target player), media_content_id (the thing you want to play) and media_content_type (the type of media).

#

No message.

#

What are you trying to do?

inner mesa
#

I feel like I've had this discussion before...

safe hemlock
#

probably many times lol

#
- alias: Select Music on Alexa
  trigger:
    - platform: state
      entity_id: input_text.music_select
  action:
    - service: media_player.play_media
      data_template:
        entity_id: media_player.kitchen
        media_content_type: "AMAZON_MUSIC"
        media_content_id: "{{ states('input_text.music_select') }} in everywhere group"
#

Bingo... winner winner... chicken dinner!

#

Thanks for the help friends!

buoyant pine
#

states.input_text.music_select.state? 🤔
@ivory delta that is valid, just not recommended

dreamy sinew
#

But not within states()

violet oyster
#

so much easier to type tho!

buoyant pine
dreamy sinew
#

Ah, skimmed it

trail estuary
#

Hey folks! I get an error (Can not read an implicit maping pair; a colon is missed) on the template after his one:

      air_quality_inverted:
        friendly_name: Luftkvalitet
        value_template: '{{ ((states('air_quality.air_quality_norway')) | float) - ((states('air_quality.air_quality_norway'))| float * 2) }}'

The template works as expected in the template editor....??

ivory delta
#

You need to mix your quotes.

trail estuary
#

Meaning

#

?

ivory delta
#

You're currently telling HA to read: '{{ ((states(' and then some gibberish, and then ')) | float) - ((states(' and some more gibberish, and then '))| float * 2) }}'

#

None of that makes any sense.

trail estuary
#

Ahhh

ivory delta
#

You need double quotes around it if you're using single quotes inside 😉

trail estuary
#

So " on the outer boundaries and ' inside?

ivory delta
#

Exactly. Or the other way round.

trail estuary
#

Ha! Been doing this for 3 years and never knew!

#

Well; TIL! 😉

ivory delta
#

You just have to remember that computers treat things more literally than humans do. When you read your string, it makes sense that the quotes at either end match. A computer just looks for the next matching quote to complete a pair.

trail estuary
#

It totally makes sense! I feel like this fits well with the "Month of WTH"! 🙂

little gale
#

What am I doing wrong here? ```yaml
value_template: >-
{% if is_state_attr('light.tv_lamp','effect','Night Lamp') and is_state_attr('light.tv_lamp','brightness',3) %}

ivory delta
#

What does it resolve to in devtools > Templates? And what do you think it should resolve to?

buoyant pine
#

@little gale that's not a complete template. Are you just trying to return True/False based on that?

#

Also follow what mono said and you'll get a hint

little gale
#

yeah sorry I fixed it, but yeah, that's just the offending part I pasted.

silent barnBOT
tribal rock
#

Yikes, sorry. I didn't realise it was so long

#

So, I've only recently started using hass, and I could use some additional help setting up a Template Switch with a value_template.
The goal is to consolidate two separate switch entities into one template switch for controlling and monitoring the assumed state of both. I'm using SwitchBots to control the separate "Cool" and "Off" buttons on my A/C. The issue is, because they are button pressing bots, switch.turn_on and switch.turn_off provide the same function of pressing their respective buttons. This makes Google searching difficult for what seems like a niche issue.
The code here works, but I just need to add a value_template to set the state of the template switch based on the successful execution of the corresponding on/off service
Pretty code: https://bit.ly/3gfAGRK

inner mesa
#

I'm confused because I would assume that simply leaving out value_template: should put the template switch into "optimistic" mode, which should do exactly as you say

#

in other words, it just assumes that the switch is on when you turn it on, and off and then you turn it off

tribal rock
#

Right, however the SwitchBot service isn't always reliable, and I want to make sure that it catches errors when the occur. Also, I'd like the interface to be a toggle switch rather than two buttons whose state is based on that assumption

#

Sorry if I'm not making any sense 😰

inner mesa
#

how do you know when it wasn't successful?

#

yeah, you'll need a value template for it to show up as a toggle switch

#

we're probably going to end up with an input_boolean.x or something

tribal rock
#

That's one thing I'm trying to figure out, programatically at least. I know an error appears in the logs when it's unsuccessful, but I don't know how to translate that to a template.

#

Ah yeah, I noticed input_boolean in one of my Google searches, that would probably work, I have to look into it more though

inner mesa
#

would be better to actually read the state of the device you're controlling

#

it's just a way to store a bit of data, so it's only useful if you know what that bit should indicate at any given point in time

#

so, you either need to know whether the switch actually did what you asked, or if the device is actually in the state you expected it to be in

tribal rock
#

Right on point, so I just need some way

...to know whether the switch actually did what [I] asked

inner mesa
#

how are you controlling the "switchbot" with switch.turn_on and switch.turn_off? What error do you get in the log when it doesn't work?

tribal rock
#

how are you controlling the "switchbot" with switch.turn_on and switch.turn_off?
Both services cause the SwitchBot to press the button.
What error do you get in the log when it doesn't work?
Good question. It looks like its
WARNING (SyncWorker_11) [switchbot] Cannot connect to Switchbot. Retrying (remaining: 2)...

inner mesa
#

so what do you want to do if it fails? retry? it seems like it already has some retry logic built in

#

just be okay with the fact that it didn't do what you asked and let you flip the switch again?

#

I would create an input_boolean.xxx to indicate the state of the switch, use that in the value_template: and put a condition in the turn_on and turn_off sections that determines whether to turn theinput_boolean on or off based on whether the last_run_success attribute is true

tribal rock
#

I've never heard of Switchbot before, but the docs tell you how to determine if it succeeded...
How did I miss this? This should be what I'm looking for
so what do you want to do if it fails? retry? it seems like it already has some retry logic built in
Fair point, however I think just having the last_run_success will allow me to create a value_template for a toggle switch, should be fine for now

inner mesa
#

yep

#

sometimes it just takes another pair of eyes

tribal rock
#

Thanks, I really appreciate it too, because I've been looking at this for an uncomfortable amount of time, lol

obsidian nacelle
tribal rock
#

You may want to look at value_json in your search

inner mesa
#

probably something like: value_template: '{{ value_json.RfReceived.Data }}'

obsidian nacelle
#

Where would I define what value I wanted the Data to match?

inner mesa
#

no, you'd compare that with what you want to see

#
value_template: '{{ value_json.RfReceived.Data == "foo" }}'
tribal rock
#

Oh my bad, I apparently can't read either rn

#

time to take a break

inner mesa
#

np, happens 🙂

obsidian nacelle
#

Message malformed: Expected a dictionary @ data['condition'][0] 🧐

silent barnBOT
inner mesa
#

your condition should look something like this:

#
  condition:
    condition: template
    value_template: '{{ value_json.RfReceived.Data == "foo" }}'
#

your values will undoubtedly vary

obsidian nacelle
#

Hmm, I’m missing something - it’s giving an error in the log saying value_json is undefined

silent barnBOT
inner mesa
#

we're just guessing at what you're actually doing

obsidian nacelle
inner mesa
#

looks like the key was trigger.payload_json.xxx

obsidian nacelle
#

Thanks for your help @inner mesa

distant plover
mighty ledge
#

@distant plover because it's only updated on startup, you don't have anything else sparking the update

#

add entity_id: sensor.time and integrate sensor.time to have it update minutely.

distant plover
#

Simply adding time_date sensor made it work apparently. But it doesn't wait 5 minutes before sending a notification it seems. It looks like it runs immediately after restart of HA and then again quite shortly after.

#

Why isn't the delay of 5 minutes in the package working?

young jacinth
#

hey, i have a quick question.
{{ is_state('media_player.ps4', 'standby') }}

#

i want to have is_not instead of is_state
how would i do this?

buoyant pine
#
{{ not is_state('media_player.ps4', 'standby') }}
young jacinth
#

thanks that worked
feel like an idiot now lol

buoyant pine
#

Lol it's all good

pine bison
#

Can anyone assist? I'm trying to get my GH to play media. I had play_media before which is now media_play. Now, however, I'm getting an API error:

"Call-service API error. Error Message: extra keys not allowed @ data['media_content_id']"

Here is the content of the JSON:

{
    "media_content_id": "http://172.16.x.x:8123/local/media/catbowl.mp3",
    "media_content_type": "audio/mp3"
}
mighty ledge
#

yeah, you should be using play_media. Look at the service caller in developer tools.

pine bison
#

smacks head
Thanks

crude crest
#

I've got to find a way to evaluate if the current day is the 4th saturday of the month. Not even sure where to start with that one.

ivory delta
#

You could have a look at using now().isocalendar(). Not quite the same as your request but I have something that cares about odd/even week numbers:
{% if now().isocalendar()[1] % 2 %}

#

Although that only gives year, week number, day number. There's probably a better way.

crude crest
#

but now() is probably the right starting point

ivory delta
crude crest
#

/shudder

#

string formatting

halcyon ridge
#

Hi, could you please explain me what is wrong with this template sensor ? This code works in templates tab:

{{ ( as_timestamp(now()) - as_timestamp("2020-07-29 15:00:00"))/3600/24 }}

but in yaml file it show errors:

- platform: template
  sensors:
    left_hospital:
      friendly_name: "Doma z nemocnice"
      unit_of_measurement: 'days'
      value_template: "{{ ( as_timestamp(now()) - as_timestamp("2020-07-29 15:00:00"))/3600/24 }}"
ivory delta
#

You need to mix your quotes.

#
      value_template: "{{ ( as_timestamp(now()) - as_timestamp('2020-07-29 15:00:00'))/3600/24 }}"```
buoyant pine
#

I think you could check if the day of the week is Saturday (6) and if the date is between 22 and 28 @crude crest

#

Between or including

halcyon ridge
#

ah, ok, thx @ivory delta

ivory delta
#

22 and 28, right?

#

29 could be the 5th Saturday of a month.

crude crest
#

I need a now().day_name

ivory delta
#

.isocalendar() gives you a tuple where the 3rd value is the index of the weekday.

crude crest
#

looking through the python datetime documentation right now

ivory delta
#

now().isocalendar()[2] == 5

crude crest
#

that would work as well

ivory delta
#

Hmm. Looks like it's not zero-indexed... might need == 6.

crude crest
#

6

ivory delta
#

The 5 in my first one was deliberate. Almost everything's zero-indexed.

#

Python is weird. Dates are weird.

crude crest
#

except like matlab and 2 things

#

and we just found one of them

ivory delta
#

I work with NodeJS. JS dates are odd... Year is what you'd expect. Date is what you'd expect. Months are zero-indexed...

#

Like, wth?

crude crest
#

fuck it, just give me unix timestamps, i'll do the math myself.

#

{{ now().isocalendar()[2] == 6 and now().day > 22 and now().day < 28 }}

#

So this should only ring true on the 4th saturday of the month.

ivory delta
#

You'll want to change those to 21 and 29 if you're not using inclusive comparators.

crude crest
#

oh, let me add the =

#

well, too bad the last trigger was last night, but i might temporarily change it around to see if it'll trigger tonight.

#

Not like we were able to have anyone over for game night last night anyways. Gotta love the pandemic in the US. People here still haven't gotten their shit together.

#

I appreciate your help though. I figured it would be pretty straight forward, but I didn't think about the date range.

ivory delta
#

Nor did I. Tediore is one of the brainy ones round here.

buoyant pine
#

22 and 28, right?
@ivory delta yep, thanks 😅

hybrid spoke
#

hello gents recently i flashed a wifi vacuum cleaner with Tasmota and I get the state and the battery % in this message {"SerialReceived":"AA1C06FF000406000000000000000000000000000000000000000000006473"}
The last 4 numbers are the battery % and the state of the vacuum, can i have a sensor only showing that part of the message?

cerulean cipher
#

some form of concat I'd imagine

#

not sure how to implement this in HA but I'd imagine something like this

#
var SerialReceived = "AA1C06FF000406000000000000000000000000000000000000000000006473";
var lastDigits = SerialReceived.Substring(SerialReceived.Length - 4, 4);
#

does it return the string the same length everytime?

buoyant pine
#
{{ value[-4:] }}
``` where `value` is a reference to the sensor that has that value
#

but the problem would be if the battery is 100%

trail estuary
#

I was wondering if someone could help out with a rest sensor....
I have a sensor set up like this: https://paste.ubuntu.com/p/Crm9DncmR4/
It filters on this data: https://paste.ubuntu.com/p/Zk68kmvfYJ/
Ideally I want it to return the state (started|stopped) for every addon in that json data, but it only returns the state fir the first addon in the list.... I am new to this, so hoping I am doing something wrong....

cerulean cipher
#
{{ value[-4:] }}
``` where `value` is a reference to the sensor that has that value

ohhhhh so it's even easier than my wrong way

#

so just {{ SerialReceived[-4:] }} is all he needs then Tediore?

buoyant pine
#

@trail estuary

{%- for x in range(0,value_json.data.addons | length) -%}
{{ value_json.data.addons[x].state }}{%- if not loop.last -%}{{ ', ' }}
{%- endif -%}
{%- endfor -%}
``` is a start. that will return all the states separated by commas. of course, you could exceed the state length limit this way
trail estuary
#

That will return all the states as a state?

buoyant pine
#

based on the source data that will return

started, started, started, started, started, started, started, started, started, started, started, started, started, started
trail estuary
#

Hehehe

buoyant pine
#

not sure what your goal is though

trail estuary
#

In the end I wanna set up a Grafana dashboard monitoring the state of all installed addons.... But I need to get that data somehow

#

The nice thing with the rest sensor is that it will return the name of the addon and the state as attributes...

#

But if I set up a sensor for each addon (which I have done) when installing/uninstalling addons, the sensors need updating

violet oyster
#

i am trying to pull the 'message' from a service call. specifically I have an event trigger for an automation that fires each time 'tts.amazon_polly_say' is called. I am trying to pull the 'message' from that service call using

{{ trigger.event.data.service_data.message }}

i know that is wrong but i can't figure out what else to try. ive tried just trigger.message and many others. any ideas?

inner mesa
#

If you listen for the event in devtools -> Events, what does the structure look like?

violet oyster
#
{
    "event_type": "call_service",
    "data": {
        "domain": "tts",
        "service": "amazon_polly_say",
        "service_data": {
            "entity_id": "media_player.volumio_mpd",
            "message": "test of the thing"
        }
    },
inner mesa
#

that actually looks okay to me based on some of my own examples for other events

#

what does your automation look like?

violet oyster
#

getting this error


    record tts to file: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'homeassistant.core.Event object' has no attribute 'service_data'
    While executing automation automation.record_tts_to_file
    record tts to file: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'message'
    record tts to file: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'data'

#

automation is

  - alias: record tts to file
    trigger:
      - platform: event
        event_type: call_service
        event_data:
          domain: tts
          service: amazon_polly_say
    action:
      - service: notify.tts_recorder
        data_template:
          message: "{{ trigger.data.service_data.message }} {{ states.sensor.formatted_date.state }} {{ states.sensor.local_time.state }}"   
#

really seems like it should be working. ha

inner mesa
#

here's an example of mine:

violet oyster
#

oh i just got it haha

inner mesa
#
    value_template: "{{ trigger.event.data.control in ('DON', 'DOF') }}"

violet oyster
#

{{ trigger.event.data.service_data.message }}

inner mesa
#

yeah, exactly

violet oyster
#

thanks man

inner mesa
#

that's exactly what you had above?

violet oyster
#

wait yeah it is

#

wtf haha

inner mesa
#

{{ trigger.event.data.service_data.message }}

violet oyster
#

why did it work this time haha

inner mesa
#

to which I replied, "yeah, that seems about right..."

violet oyster
#

i must have done something dumb like forget to reload the automation or something

#

or tried it again too soon

inner mesa
#

well, glad it's working

violet oyster
#

yeah me too, thanks

cerulean cipher
#

so just {{ SerialReceived[-4:] }} is all he needs then Tediore?
no ?

buoyant pine
#

Hard to say without context. If that value is stored in a sensor, you just need to reference the sensor itself

hybrid spoke
#
{{ value[-4:] }}
``` where `value` is a reference to the sensor that has that value

@buoyant pine worked perfectly thanks!

inland crypt
#

not sure is this is the right place for this question but it sort of relates to templating. I have this {% if (as_timestamp(now()) - as_timestamp(states.switch.kitchen.last_updated)) < 10 %} line but if i press the switch the timestamp does not change

#

so its always false

#

the kitchen switch is a momentary one, so it's only "on" for a short while, but does that matter? The state change should still be logged right?

inland crypt
#

😐 nevermind, im dumb

#

forget to link the switch to a value_template

mighty ledge
#

@inland crypt That won't ever update in a template sensor, switch, etc. That will only be correct if it's a condition in a script or automation.

north helm
#

Good morning! I can't seem to make this damned template work. Looked all over the web. You folks can probably spot the error a mile away. Basically this is going in the middle of a notification to Alexa.

#

`

#

data_template:
message: >
{% set diff = states('sensor.indoor_v_outdoor')|int %}
{% if diff > '0' %}
warmer
{% elif diff == '0' %}
the same
{% elif diff < '0' %}
cooler
{% endif %} ``

#

data_template: message: > {% set diff = states('sensor.indoor_v_outdoor')|int %} {% if diff > '0' %} warmer {% elif diff == '0' %} the same {% elif diff < '0' %} cooler {% endif %}

#

Sorry

buoyant pine
#

remove the quotes around the number

#

also:

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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

buoyant pine
#

you were close the second time, you just need three backticks instead of one (you can also edit messages)

#

here's an alternative btw:

data_template:
  message: >
    {% set diff = states('sensor.indoor_v_outdoor')|int %}
    {% if diff > 0 %}
      warmer
    {% elif diff < 0 %}
      cooler
    {% else %}
      the same
    {% endif %}
#

@north helm

north helm
#

Let me try that!

#

OMG you guys are awesome.

#

Thank you!

buoyant pine
#

no prob. when you put quotes around something it turns it into a string, but you want it to be a number

north helm
#

Makes perfect sense.

#

Muchas gracias!

buoyant pine
#

de nada

cerulean cipher
#

hey Tediore

#

sup DenverBowiee

north helm
#

I have a follow-up if you're willing....

#
  type: tts
message: >-
  It feels like {{ states ('sensor.smartweather_feels_like')|round(0) }} degrees
  out. {{ states('sensor.indoor_v_outdoor') | round(1) | abs }} degrees
  {% set diff = states('sensor.indoor_v_outdoor')|int %}
  {% if diff > 0 %}
     warmer than inside.
  {% elif diff == 0 %}
     the same as inside.
  {% elif diff < 0 %}
     cooler than inside.
  {% endif %}```
#

I'm getting an annoying pause between the word "degrees" and the conditional message.

#

TTS isn't really this forum, though, is it?

cerulean cipher
#

not really but how about a delay of some sort until it works out the math?

north helm
#

Just change the order of operations, maybe? Put the 'variable degrees' in the conditions?

cerulean cipher
#

that might help

#

work out all the math first then announce would be my thinking

north helm
#

Even better!

cerulean cipher
#

I used to run into this issue with call centers often

#

the metrics would hold up the auto-attendant so in some cases I just did the math before the announcements 😄

#

same principle applies 😄

#

but then again Avaya vectors are almost my native language LOL

north helm
#

hehe

#

I'm so used to calculations being almost instant in Cherwell that it never occurred to me that basic comparisons could be a bottleneck.

#

But it makes sense.

cerulean cipher
#

well my mind works on basics for the most part LOL

#

I try to break things down into little smaller problems instead of running after windmills with my sword 😄

#

BTW did you try data_template: ?

north helm
#

Very good thinking, Senor Q

cerulean cipher
#

😄

north helm
#

Originally, yes.

cerulean cipher
#

I completely suck at templates BTW

north helm
#

Oh wait.... Do you mean make a new sensor that's a data template?

cerulean cipher
#

😉

north helm
#

So it's basically pre-calculated...

cerulean cipher
#

😉

#

just my simple thoughts

north helm
#

I likes it. I likes it!

cerulean cipher
#

you probably know way more about templates than I do as I said 😛

north helm
#

Not at all.

cerulean cipher
#

I wrote my first one yesterday or day before .....

#

I've never had a use for them until now

north helm
#

Good thing I have some downtime right now to play with this new idea.

cerulean cipher
#

I did a lot of things in node-red directly, but since I'm trying to learn automations in HA... I deleted everything from Node-red and I'm starting from scratch in automations and templates

north helm
#

Ummmm, then yes... I probably know a shade more.

#

😛

cerulean cipher
#

when I tell you I'm dumb you should believe me 😛

#

if mono tells you I'm dumb you should believe him too

#

lol

north helm
#

Now if only I can get my automation to announce this when the state changes from negative to positive in time for it to actually test when the temp changes!

#

😛

cerulean cipher
#

well my one template was on sending telegram messages to my phone when the weather state changes at home

#

so maybe right up my alley LOL

north helm
#

I'm sick of guesswork on when to open and close the windows.

#

So.... Which of us is dumber?

cerulean cipher
#

this is why I have the weather sent to my phone via telegram

#

so I can know if it's rainy and shut the windows

north helm
#

I'm going with the guy who needs to be told that it's warmer outside.

#

Rain is different

cerulean cipher
#

rain comes here in a FLASH

#

LOL

north helm
#

Ok. How about equally dumb?

#

Or at least similarly

cerulean cipher
#

I still think I'm dumber than you good sir

#

😛

north helm
#

Let's have a headbutting contest!

cerulean cipher
#

who deletes a working system to figure it out all over again in another way

#

< this dummy

north helm
#

That's pretty bad.

cerulean cipher
#

Let's have a headbutting contest!
@north helm I warm up on concrete just FYI

north helm
#

It's drastic, but it's motivating!

orchid onyx
#

Hi, I recently made a fan.template so I can controll my AC thru homekit- it all works great. But I saw an error in my logs:
`Logginformation (WARNING)
Logger: homeassistant.components.homekit.util
Source: components/homekit/util.py:315
Integration: HomeKit-brygga (documentation, issues)
First occurred: 16:39:34 (1 occurrences)
Last logged: 16:39:34

['quiet', 'low', 'medium', 'medium_high', 'high'] does not contain the speed setting off as its first element. Assuming that quiet is equivalent to 'off'`

does it mean i should put 'off' in front of quite?

cerulean cipher
#

try 'off', 'low', 'medium', 'medium_high', 'high'

north helm
#

Getting a different error now

#
    sensors:
      difference:
        data_template:
        {% set diff = states('sensor.indoor_v_outdoor')|int %}
        {% if diff > 0 %}
          {{states('sensor.indoor_v_outdoor')}} degrees warmer than outside.
        {% elif diff == 0 %}
          the same as outside.
        {% elif diff < 0 %}
          {{states('sensor.indoor_v_outdoor')}} degrees warmer than outside.
        {% endif %}```
#

Is returning:

#
found character '%' that cannot start any token
  in "/config/sensors.yaml", line 363, column 10```
#

Line 363 is the first line after "data_template:"

cerulean cipher
#

you may need to double brace

#

or quote

#

column 10 is likely the first % on 363

#

{%

north helm
#

Where would the close brace go, then? After the {%endif%}?

cerulean cipher
#

🤷‍♂️

#

LOL let's see

north helm
#

lol

#

Now it doesn't like column 11.

cerulean cipher
#

im pasting your temple piece by piece into the tester

#

try {% set diff = states(('sensor.indoor_v_outdoor'))|int %}

#

that stopped my error

#

actually

#

I think that's me being dumb again

#

yeah so nothing I did seemed to be right

north helm
#

Me either.

cerulean cipher
#

not to worry, someone will show us the ignorance of our ways, possibly calling us dumb also

#

{}'s for it

buoyant pine
#

@north helm @cerulean cipher data_template: needs to be value_template:

#

and you need a > if it's multi-line (like it is)

cerulean cipher
#

see Denver, I told you we're dumb

buoyant pine
cerulean cipher
#

well you knew this about me already

north helm
#
    sensors:
      difference:
        value_template: >-
        {{% set diff = states('sensor.indoor_v_outdoor')|int %}
        {% if diff > 0 %}
          {{states('sensor.indoor_v_outdoor')}} degrees warmer than outside.
        {% elif diff == 0 %}
          the same as outside.
        {% elif diff < 0 %}
          {{states('sensor.indoor_v_outdoor')}} degrees warmer than outside.
        {% endif %}
        }```
#

Tried it as value_template :> and value_template: >-

buoyant pine
#

remove the extra braces at the beginning and the end

cerulean cipher
#

that was my dumb suggestion #1

#

runs

inner mesa
#

and I always indent the template block by 2 spaces

buoyant pine
#

heh, was just about to say that

north helm
#

Still doesn't like that %

#

The paste is making it not look indented.

silent barnBOT
rugged laurel
#

{{% is not valid

buoyant pine
cerulean cipher
#

so instead of one person calling me dumb we got everyone out today 😄

north helm
buoyant pine
#

indent everything under value_template: > two spaces like rob said

north helm
#

Oh, blessed relief! That was it!

#

Thank you everyone! .... Except @cerulean cipher

#

😛

cerulean cipher
#

I knew that was coming

#

LOL

north helm
#

You kept setting us up for it.

cerulean cipher
#

I did make a disclaimer that I knew less than you did about the templates 😛

#

so I outlined that I'm dumb but willing

#

😛

#

I either have really good ideas or really bad ones, not much in between

#

and often the bad ideas are more common

#

than the good

north helm
#

Well, I've learned a lot this morning!

cerulean cipher
#
  1. Don't listen to KrAzIe242
#
  1. use data_template:
#
  1. value_template:
north helm
#

Of course, this is all preliminary to @cerulean cipher 's idea to remove the pause in my announcement.

cerulean cipher
#

did it work tho?

#

the pause gone?

north helm
#

Not there yet.

#

But the value of the new sensor is "6.4 degrees warmer than outside."

cerulean cipher
#

I'm excited to see if at least I helped in some way other than to obfuscate things

#

But the value of the new sensor is "6.4 degrees warmer than outside."
@north helm well that's a step in the right direction no?

north helm
#

It works like a charm.

#

I feel much gratitude for all.

cerulean cipher
#

so this maybe my second win today

north helm
#

I'd better get back to actual work that I'm getting actually paid for.

#

Thanks again all!

cerulean cipher
#

paid? Error, process not found.

brisk temple
#

Can you do a character return in a templated message?

buoyant pine
#

newline? yeah, i have this as part of a template:

 + '\n'
dreamy sinew
#

seems to depend on whatever is ultimately rendering the output though

inner mesa
#

could be. this works for me:

#
  test:
    sequence:
      service: persistent_notification.create
      data_template:
        message: '{{ "test test\ntest2 test2" }}'
#

but I also recall there being forum messages exhibiting weird and inconsistent behavior

brisk temple
#

thanks, i'll give it a go

thorny snow
#

Hello everyone! Looking for a jinja guru to streamline an integration of 17track. How can I add a filter on the below template sensor to only look for entities that contain 'seventeentrack' ?

  sensors:      
    seventeentrack_packages_not_found:
      value_template: "{{ states | selectattr('state','eq','Not Found') | list | count }}"
orchid onyx
#

try 'off', 'low', 'medium', 'medium_high', 'high'
@cerulean cipher

i have no 'off' in fan_modes:
here is my code:
speed_template: "{{state_attr('climate.hall', 'fan_mode')}}"
speeds:
- 'quiet'
- 'low'
- 'medium'
- 'medium_high'
- 'high'

halcyon ridge
#

hi, how to correctly round value in template sensor ? this works on template tab, but not in file , don't know why
value_template: "{{ (( as_timestamp(now()) - as_timestamp('2020-07-29 15:00:00'))/3600/24)|round(0) }}"

dreamy sinew
#

.share the full thing

silent barnBOT
halcyon ridge
#
- platform: template
  sensors:
    left_hospital:
      friendly_name: "Doma z nemocnice"
      icon_template: "mdi:timer-outline"
      unit_of_measurement: 'days'    
      value_template: "{{ (( as_timestamp(now()) - as_timestamp('2020-07-29 15:00:00'))/3600/24)|round(0) }}"
dreamy sinew
#

that will never update as you don't have an entity in there

halcyon ridge
#

I'm talking about round that calculated value,. When I run this in template tab, the output is 26, but when this is in file, output is 26.29683224312409

dreamy sinew
#

should work, but you'll still have the problem i talked about so you should work on resolving that first

halcyon ridge
#

I've added entity_id sensor.date, and after restarting HA is result rounded

#

is there a way how to read value for entity from yesterday ? II know, that I can create another sensor and save current value at 23:59 to the new sensor, but that is not what I want

#

I've found history_stats but it looks, that it does not return value from selected time

solid dock
#

hi, how do i set up a similar template for rgb_color instead of kelvin?

  entity_id: light.entity
  kelvin: "{{ state_attr('sensor.circadian_values', 'colortemp') | int }}"```
cerulean cipher
#

i have no 'off' in fan_modes:
here is my code:
speed_template: "{{state_attr('climate.hall', 'fan_mode')}}"
speeds:
- 'quiet'
- 'low'
- 'medium'
- 'medium_high'
- 'high'
@orchid onyx but you posted an error "['quiet', 'low', 'medium', 'medium_high', 'high'] does not contain the speed setting off as its first element. Assuming that quiet is equivalent to 'off'"

#

does not contain the speed setting off as its first element is why I told you to try putting off there

proud igloo
#

how to convert a sensor from bytes to TB? {{ states.sensor.bytes_sent | filesizeformat() }}/s would this work? I assume replace filesizeformat with GB?

proud igloo
#

yea I was looking at that

inner mesa
#

just guessing, since I hadn't seen "filesizeformat()" before

#

so just use the other examples that do real math

proud igloo
#

where filesizeformat is would I put the 1000000000?

#

nvm I think I'll try a few to see which one works 🙂

inner mesa
#

yes, something like that. depends on whether you want round numbers or binary

proud igloo
#

thanks 🙂 I'm still learning this stuff, I'm getting addicted to home assistant lol

#

hmm results showing up as 0 probably doing the formula wrong =/

inner mesa
#

this yields a non-zero result:

#
{% set bytes = 2000398934016 %}
{{ bytes|float / 1099511627776 }}
#

you're probably missing the |float

#

so it's converting to an integer or something

proud igloo
#

I have that one in there to

dreamy sinew
#

String math

#

It does some wonky things

proud igloo
#

value_template: "{{ states('sensor.lances_nas_volume_free')|float / 1000 }}"

#

converting gb to tb btw I thought it was bytes at first

inner mesa
#

even this works ok:

#
{% set bytes = "3" %}
{{ bytes|float / 2 }}
proud igloo
#

oh well now its working lol

inner mesa
#

magic

proud igloo
#

right? lol

#

hmm browser caching issue I think

#

anyone to reload the config.yaml without rebooting?

inner mesa
#

only parts of it

#

sensors? no

proud igloo
#

I was about to ask that

inner mesa
#

configuration > Server Controls for the list of things that you can reload

#

and feel free to request sensor reloading 🙂

silent barnBOT
#

If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.

inner mesa
#

there's probably already a request

proud igloo
#

if I do a | round(0) will that take out the decimal places?

#

so if I have a result of lets say 89.978 how would I get rid of the .978? I assume round does it

inner mesa
#
{% set bytes = "3" %}
{{ (bytes|float / 2) |int}}
#
{% set bytes = "3" %}
{{ (bytes|float / 2) |round(0)}}
#

truncate or round, your call

proud igloo
#

thanks!

inner mesa
#

(parens matter)

proud igloo
#

I noticed the config yaml is very picky with lots of things lol

inner mesa
#

in this case, you want to filter the result of the division and not just the "2"

proud igloo
#

when I tried round it put me to 0 again, trying out int to see what it does

inner mesa
#

I'm testing all of that in devtools -> Templates

proud igloo
#

"{{ states('sensor.lances_nas_volume_free') | float / 1000 | int }}" like this right?

inner mesa
#

no, that's not what I wrote 🙂

#

like I said, parens are important, including where they are

#

you didn't use them at all

proud igloo
#

would I incase the senor name in with it as well?

inner mesa
#

put your sensor in place of bytes in my example

#

{{ (states('sensor.lances_nas_volume_free') | float / 1000) | int }}

proud igloo
#

missing 1 ) in that right?

#

oh nvm

#

I see it

inner mesa
#

your version is just truncating the 1000 and not the result of the division

proud igloo
#

I have lots to learn with this stuff

inner mesa
#

indeed. this is just order of operations in Jinja

#

but I have to admit that I usually just play around with it until I figure it out

#

and then back into "why"

proud igloo
#

thats pretty much how I work

#

poke it till it works then try to figure out how the gears turned

#

still getting a decimal value

#

trying float 🙂

#

err

#

round(0)

#

round did it

inner mesa
#

you can test all of this in devtools -> Templates, if you don't know

#

instant results

proud igloo
#

oh?

#

oh wow thats nice

inner mesa
#

invaluable

proud igloo
#

one of my new playgrounds lol

#

still gotta work out another bug in node red to

inner mesa
#

that's how I was able to try three things at once 🙂

proud igloo
#

I'm just fumbling around in home assistant but I'm loving tying everything together into one place

north helm
#

I've got another puzzle for you. (You'd think I'd be better at this by now...) And this MIGHT be more of an #integrations-archived question. My end goal is to make persistent variables between restarts using the custom component variables and MQTT. My idea is to publish 3 values to a retain'ed MQTT topic. In my native environment, this is simplicity itself, but value_template syntax continues to elude me.

#
      ```
#

is my payload to MQTT

#

Well, my DESIRED payload

inner mesa
#

I’m not sure I can visualize the whole thing from that snippet. Seems like it would be easier to use separate topics

north helm
#

Good point. I think I'm just failing to grasp how to group the multiple sensors and their labels into a single object.

inner mesa
#

Sounds unnecessary. Topics are free

north helm
#

If payload: >- were what you're trying to group those into...

inner mesa
#

You’re over complicating this

north helm
#

LOL. Usually.

#

I think it's the bracketing nature of HA that's causing all of my problems.

dreamy sinew
#

{{ {"east": states('sensor.east_blinds'), "west": states('sensor.west_blinds'), "dining": states('sensor.dining_blinds')}|tojson }}

#

@north helm give that a shot