#templates-archived
1 messages Β· Page 85 of 1
yeah... not clicking a dropbox link from a random person on the internet π
Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
Also, showing code as images is why image posting is banned by default π
oh... aaaaaaaand I missed that it was 2 different attributes
No worries {{this and that}} works great
building a generic_thermostat that flips on when sleeping that controls the upstairs
jinja ninjas or programmers out there.
I have 2 numbers and want the higer one
I bet thats possible but I dont know how π
Found it something! max
@warm isle {{ [2, 4, 7, 212, 45, 23] | max }}
aaah thanks - would have take me ages to find out that I have to put them in square braces
"{{ [(states('input_number.bath_movement')|int), (states('input_number.kitchen_movement')|int)]|max }}"
Square braces is a list in almost all programming languages except lisp. Even matlab(sic!).
"R" you kidding me
@rugged laurel we could block Dropbox if there are concerns over security.
Dropbox itself is pretty secure, random folks on the internet, not so much
Hey guys, I'm having some issues with my code and I'm hoping someone can point me in the right direction.
I'm trying to add a sensor using rest
But I get the following error: Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See ?, line ?).
@viral wadi posted a code wall, it is moved here --> https://paste.ubuntu.com/p/b2wJsNggD2/
Looks fine. What's immediately after this?
Nothing, this is it ^^;
That's the absolutely last line in your configuration.yaml?
Ah it's not in my config.yaml, I've split my config, this a file inside my ..\entities\sensors folder
I have 2 lines in my confiig.yaml
But that's the last lines of the file?
Yes
Can you narrow it down by commenting parts out?
Good suggestion, I'll try and give that a go. I'm also just trying to add it as an integration to see what it does.
Ah that's actually resolved it.. how weird. So I guess the code was fine but it's not working when it lives as a 'sensor' outside my configuration.yaml
Thank you @charred dagger π
It should, if you include it correctly.
That's probably it. Did you do sensor: !include filename?
I moved the yaml file from ../entities/sensors to ../intergrations and it works right away
Yeah it's linked
You may want to take a look at packages, btw: https://www.home-assistant.io/docs/configuration/packages/
sensor: !include filename in your case would result in yaml sensor: sensor: - platform: rest ...etc...
Which could be fixed by removing the first line and dedenting the entire file.
Yeah so I've got:
sensor: !include_dir_list ../entities/sensors
Which should pull all my sensors into HA correctly.
Then you get ```yaml
sensor:
- sensor:
- platform: rest``` if the file is what you linked
With !include_dir_list you'd have to split each sensor platform into its own file with just yaml platform: rest ...etc... and yaml platform: template ...etc...
I see what you mean
I did try that but that returns:
Error loading /config/configuration.yaml: mapping values are not allowed here in "/config/integrations/../entities/sensors/zeversolar.yaml", line 10, column 7
It's working as I've got it now so I'll leave it like this π
Hi folks. I'm trying to understand templates, to allow me to calculate a difference from one reading of a pulse counter to the next. I'm clearly missing a fundamental concept, though. From my understanding, I can use the state of the counter to retrieve the previous value, and extract the current value from the JSON message received via MQTT. I can then calculate the difference. So far, so good.
My problem comes in when the NEXT reading arrives. What value is now in the state of my counter? My calculated difference, or the previous counter value?
i.e. state(counter1) = 12345, json(counter1) = 12349, calculate difference = 4
next: state(counter1) = (4 ? 12349), json(counter1) = 12357, calculate difference = ??
@oak juniper if you are just looking for the difference from last to current, you can simply get it from trigger.to_state.state and trigger.from_state.state. If you want to do some advanced math, you may want to use some sort of variable, where you do the math and store the value and use it later.
Can I then publish that difference under a different entity id somehow?
Otherwise it seems that I will still end up in the same place, having replaced the previous counter value with a calculated difference.
@queen meteor Thanks for taking the time to respond to me, btw
Yes. Best way is to use some sort of variable.
When you create a new variable, it will be a different entity_id.
or am I missing the plot entirely? Can I just add an additional variable name to the entity, as e.g. the statistics plugin does?
You mean an attribute?
yes
You canβt add a new attribute dynamically in jinja. You have to use python script or app daemon for that.
ah, I see. This is the formula I tried to use:
value_template: >
{{
( value_json.Counter1 -
(states("sensor.pool_pump_flow") | int)
)
/
( as_timestamp(value_json.Time) -
as_timestamp(states.sensor.pool_pump_flow.last_updated)
)
}}
but I got nowhere with that, and ended up questioning my entire approach
Assuming that is a template or mqtt sensor?
a sensor
@oak juniper posted a code wall, it is moved here --> https://paste.ubuntu.com/p/N9fNcYyGqH/
oops
No worries. In that case pool pump flow will be overridden with the new value.
and on the next update?
It does the same thing. It keeps overriding the value with the new calculated value
it will calculate the difference between the new multi-billion pulse count value, and the previously calculated difference?
which is completely useless
Yes. Because you are using states(β...β). It will get the previously calculated value.
so what is the correct way of doing this?
I can't believe this is an unusual situation for people to find themselves in?
Not really. Usually folks get the logic wrong.
in your code, you have a sensor Pool pump Flow, where you are setting the value using value_template by grabbing the value from mqtt subtract with Pool pump flow value divided by the time difference. whatever the value that is, it becomes the Pool pump Flow value. that value will be used next time the sensor updates.
if that's not what you want, you may have to change the logic
Objective: Know the average rate of pulses from the pool pump sensor, given that MQTT reports a total (monotinically increasing) pulse count.
the idea is to be able to detect anything that is making the pump slow down, such as an obstruction, or a clogged filter, etc.
and if the average rate falls below a threshold, turn the pump off and trigger a notification.
so the first step is to establish that average pulse rate between updates.
ok...
have you seen the output of that in the template editor? you can simulate the scenario there
yes, I did.
It gave me the average pulse rate, which is exactly what I wanted.
BUT, that was based on the previous state being a complete pulse count, not a difference
you mean not an average?
if you use a different template sensor to store that value, you could calculate the difference
ok, so how do I store it into a different template sensor?
When I'm getting a float value in an entity's attribute (e.g. 0.05) and want to multiply this by 100 and then get an int value (no decimals), how do I do this in a template sensor? I have this right now, but it still return 5.0 instead of 5: {{ state_attr('climate.flur', 'level') * 100 | int }}
ah, I forgot the brackets, so it casted the 100 as an int, this works now: {{ (state_attr('climate.flur', 'level') * 100) | int }}
probably still getting some string math in there
{{ (state_attr('climate.flur', 'level')|float * 100)|round() }}
Hi I ordered 2-way RF switches/buttons to implement a multi state toggle. For examle: If I press once, the light should turn on, if it was off. Pressing again should toggle predefined brightness levels e.g. 10, 50, 100 and the next press should turn it off. In the documentation I've found a solution via "template light" and scripts. Before I start changing the Hue light config, I wanted to know, if there are smarter/easier options?
Hello, I never made a template, so I can not make the sample works
- platform: template
envoy_lifetime:
friendly_name: "Envoy Lifetime Production"
unit_of_measurement: 'kWh'
value_template: "{{ states('sensor.envoy_lifetime_energy_production')|multiply(0.001) }}"
I try to put this in sensors.yaml and give me an error
Error loading /config/configuration.yaml: mapping values are not allowed here
in "/config/sensors.yaml", line 21, column 19
π€ͺ is late, so I am thinking of leave it for tonight, but this is my last shot
I guess is also late for everybody, I'll try it other day!!, Have a good night!! π΄
or too early. You should format your message by with three backticks on both sides so it shows up correctly `
hey i need to create template for sensor and i think im to dumb for it. It need to read data from distance sensor and show percentage level like if sensor show 0.25 and above its 100% and if its 0.50 and below its 0%
anyone have some idea ?
@queen meteor 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

@wispy lodge pretty close, but the if should have corresponding endif and they should be wrapped in {% and %}
also, you can't do that in customize: section
if you are trying to do it in lovelace, you may try in #frontend-archived channel
@queen meteor thanks. i will try in frontend channel
@wispy lodge that's Custom UI, you need custom UI installed. You need to wrap all your values in state == "value" in quotes.
You also, need a failsafe if none of those if statements are met. Disregard what @queen meteor said because that only pertains to Jinja.
I figured it is the lovelace code in the end π
His code is set up exactly like custom ui
I hate how that crap still floats around the forum
it just confuses new users
It's the really old way to customize the states UI
I wouldn't know... not a big fan of UI. just the basic ui is good enough for me, and never tried that custom ui stuff
ya, when states page ruled king, i didn't use it either
maybe we should mark `Obsolete" on older stuff as we find them in the community site
Is there a way to do that?
states page is going away
Yah, thank god
well, it doesn't hurt that it's there
but can't wait for the attributes to go away
I am not sure if we can mart it obsolete, but we can make the thread readonly or gray it out
yeah... something to keep in mind though
I think I answer 3ish threads a month about people trying to configure custom UI without realizing it's not part of the standard install
oh wow!
it's enough for me to know how to use it... haha
lol
I finally upgraded to 0.150.0 after a month or so...
now I see two minor versions π
I want to update tonight, what minor versions you talking about?
oh, that it's already at 105.2
I usually wait til .3
but... i'm impatient
yes i have custom UI. But can I do this (change the color of the icon and icon?) Without using a custom UI?
0.150.0? F U T U R E
@wispy lodge yes, card-mod
but it requires configuration in each place you put it in the UI
instead of the opposite.
Ok. π i will try tomorrow
Hello. Does anyone know how to remove the white space from unit_of_measurement:?
For instance it displays as 22.22 '
I would like to see 22.22
22.22'
Hi everyone silly question how do I type Celsius into the config on Home Assistant
Hey guys, I'm trying to create a template (linked to an automation) that turns on the corresponding light (or group of lights maybe, for future proofing) of each sensor
This is what I got so far https://paste.ubuntu.com/p/tGc39Z24Qx/
The action section of the automation is all a work-in-progress, as I'm guessing I'd have to use a map but I don't really know
If somebody has the time to help me out It'd be greatly appreciated
@past moth just use trigger.entity_id instead of map. There is always one trigger in the action part. If multiple lights trigger, the same automation runs multiple times with different entity_id
@terse mural for custom sensors, you can set unit_of_measurement. Globally it should take it from temperature _unit configuration.yaml.
@queen meteor I don't understand, how can I associate a motion sensor with a group of lights then?
You can have if statements in the action section of automation.
If the trigger is x, turn off light x. Else if trigger is y, turn off y...etc.
Or you can define a map as a variable, and use map[trigger.entity_id].
I am on mobile, and canβt type code properly. Hopefully this gives you an idea.
@past moth Something like this in your action part: action: - service: light.turn_on data_template: entity_id: >- {% if trigger.entity_id == 'binary_sensor.name' ) %} light.name {% enfif %}
I would rather use a map, because I'd have to use 6 ifs
But it's only a matter of style really this will do too
@waxen rune replace state.state with state.attributes
I have learned that it's better to use
{{ states.binary_sensor.status_smoke_sensor_0.state }}
than
{{ states('binary_sensor.status_smoke_sensor_0') }} to avoid errors and error message when the entity isnβt ready yet (e.g., during Home Assistant startup) according to https://www.home-assistant.io/docs/configuration/templating/#states
But how to alternate this?
{{ states.binary_sensor.status_smoke_sensor_0.last_updated }}
I tried {{ states('binary_sensor.status_smoke_sensor_0.last_updated') }} and {{ states('binary_sensor.status_smoke_sensor_0', 'last_updated') }} but that was not the way to go.
Suggestions?
you can't
last_updated is part of the state object so you need to use the states.domain.object_id method
@waxen rune you got it backwards
yeah, that seems to be my thing regarding home assistant π
state_attr('entity_id', 'attribute')
note that last_updated isn't an attribute though
but {{state_attr('binary_sensor.status_smoke_sensor_0', 'last_updated') }}doesn't work eiuther
exactly π
that's where my brain melted
that would be one of those things that you would have to access directly then
yup, that's what i said π
so to avoid errors before there is an actual value, it could look something like this, I guess?
{% if states.binary_sensor.status_smoke_sensor_2.last_updated is defined %}
{{ as_timestamp(strptime(states.binary_sensor.status_smoke_sensor_2.last_updated | string | truncate(19,True,'',0),'%Y-%m-%d %H:%M:%S:%f')) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}
{% else %}
Not updated yet
{% endif %}
or are there better ways (less characters)
i don't think an exception is avoidable
if binary_sensor.status_smoke_sensor_2 doesn't exist, it'll crash out
ok. a restart will tell π
and your pi will spontaneously combust
@past moth posted a code wall, it is moved here --> https://paste.ubuntu.com/p/hG63dktZrB/
Yeah, I meant to put code quotations but I probably failed even those
Anyway, help is greatly appreciated. I can't seem to figure out templates
There is no enfif. @past moth it is either elif or endif
Also. You have a few extra )
Give me 5 min. Iβll put you out of misery. I know you are at this the whole day. Just arrived home. @past moth
@past moth here you go ```yaml
action:
- service: light.turn_on
data_template:
entity_id: >-
{% set entity_map = {'binary_sensor.0x00158d0004242a03_occupancy':'light.lampadina_camera_lorenzo',
'binary_sensor.0x00158d0004473fa7_occupancy':'light.lampadina_camera_lorenzo',
'binary_sensor.0x00158d000421cbe4_occupancy':'light.lampadina_camera_lorenzo',
'binary_sensor.0x00158d00041f2d87_occupancy':'light.lampadina_camera_roberto',
'binary_sensor.0x00158d0004111ab9_occupancy':'light.lampadario_sul_tavolo'
} %}
{%- set entity = trigger.entity_id -%}
{{ entity_map [entity] }}
change the entity_ids as you like.
Oh wow thanks
How can I replicate a similar behavior with the condition?
As in, only perform the action not only if the sun is set but also if the illuminance sensor reads X
you already have the condition, keep it as-is. just add another condition for illuminance check
Yeah but how can I make it so that it checks the same sensor that triggered the action
do you have an entity for luminance? or is it an attribute value?
both actually
if you share the entity id for the luminance, I can help you add that condition. otherwise you can check the docs and figure out how to do it.
for instance sensor.0x00158d0004111ab9_illuminance is the one in the kitchen
it's just the suffix that changes
By the way this doesn't seem to be working I don't know if I'm doing something wrong
https://paste.ubuntu.com/p/jpBXPMsM6G/
are you seeing any errors?
also, are you sure it is dark outside?
you can try this.... I added condition code. https://paste.ubuntu.com/p/KSbPhqjBgF/
this should give you an idea. good luck!
Where would I check for errors? In home assistant.log?
yeah or developer tools > logs
Hey guys, hate to come here asking for help. Last resort, I promise.. I've been trying to do this for days now. Literally. But I just can't seem to get anywhere. I've tried scripts and I've triued templates to get mt Broadlink rf blaster to show up as an 'entity' to place onto a card so that I can control my blinds. I currently have them workig as a switch with on/off lighning bolts, but I'd like to make it so that they're shown as a cover so that I can have up/down/pause commands with arrows. I know it's been asked a hundred times already, and I've searched the depths of google and tried all the results and suggestions in previous forum postings but I still can't get it to show, only as a switch. Would someone mind taking a look at my .yaml and tell me what I'd doing wrong/point me in the right direction? I'd really appreciate it.
I have placed the following in my config file:cover:
- platform: template
covers:
cover_1:
friendly_name: "Living Room Blinds"
open_cover:
service: script.cover_1_up
close_cover:
service: script.cover_1_down
stop_cover:
service: script.cover_1_pause
and the following in my scripts file:
@formal ruin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/WpKtQR2PkD/
@thorny snow scripts donβt get called via their name they are used script.(a number) the number is random but if you look at your scripts.yaml file in your config folder you should be able to figure out which is which
Hey ppl
need help with this script.. im kinda stuck..
dimma_lysen:
sequence:
- service: light.turn_on
data_template:
entity_id: >
{% if states.light.hallen.state == 'on' %}light.hallen,{% endif %}
{% if states.light.kok.state == 'on' %}light.kok,{% endif %}
{% if states.light.kontor.state == 'on' %}light.kontor,{% endif %}
{% if states.light.sovrum.state == 'on' %}light.sovrum,{% endif %}
{% if states.light.vardagsrum_fonsterlampa.state == 'on' %}light.vardagsrum_fonsterlampa,{% endif %}
{% if states.light.vardagsrum_taklampa.state == 'on' %}light.vardagsrum_taklampa{% endif %}
transition: 6
brightness: >
{% set lux = states.sensor.lux_median.state | int %}
{% if 100 >= lux and 50 <= lux %}
'10'
{% elif 49 >= lux and 30 <= lux %}
'20'
{% elif 29 >= lux and 20 <= lux %}
'30'
{% elif 19 >= lux and 10 <= lux %}
'40'
{% elif 9 >= lux and 1 <= lux %}
'10'
{% else %}
'1'
{% endif %}
i get error on the data_template -> entity_id
Hey. Thanks, @copper flower . I can't see any randomly generated numbers in my scripts.yaml, nor do any of the guides I've followed refer to any numbers, so I'm a tad confused! The only numbers I see are the line numbers.. unless that's what you're referring to?
@quartz beacon 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
Okay, so this is now in my config file, no longer showing any errors in the log..
cover:
- platform: template
covers:
cover_1:
friendly_name: "Living Room Blinds"
open_cover:
service: script.cover_1_up
close_cover:
service: script.cover_1_down
stop_cover:
service: script.cover_1_pause
And the matching script:
cover_1_pause:
alias: "Cover 1 pause"
sequence:
- service: broadlink.send
data:
packet:
- packet: '*****'
(repeated for down and pause)
I thought the service script.script_title in the config file pointed to the name of the script in this case; cover_1_pause = script.cover_1_pause? Whatever i'm doing wrong, it's stopped throwing errors about not matching what's expected in the config.yaml but I can't get this to show as a card in the main interface. Where should I be able to see this, entities, devices, etc.? Thanks again. I'm really no good with any of this.
@quartz beacon have you isolated whether each of the entityid is correct? Because you have "," at the end of each condition, it is possible that the last condition is not true and there is a "," hanging. Try each entity separately and instead of light.hallen, try - light.hallen and so on for each entity
@thorny snow does broadlink.send work fine? have you tested it separately?
@wispy lodge what type of card you are using? Also #frontend-archived
@rare panther posted a code wall, it is moved here --> https://paste.ubuntu.com/p/NQYH9TDnSX/
@rare panther Had to rewrite it with for-loop, solved it :)
good to know.
Do someone of you think its possible to template a telegram keyboard?
huh?
@rare panther type: entities
@warm isle Anything can be templated.
Except your wife. Don't try, trust me
@thorny snow Iβm talking about the line above alias in your scripts.yaml file.
@thorny snow I send you a message with an example of what Iβm referring to
π€£ @mighty ledge
Wel then hear out my problem. I comand sensor'd out the unfineshed items on my shopping list.
Getting a nice textfile out with every item in a new line (there are another problem limiting the output of the command to 250 characters but thats for later fixed head -c )
What I would like to get is a keyboard with in the case for now adds /D in front of every item that youre able to delete it from the shopping list
https://hastebin.com/cibecuxusa.coffeescript
example list:
https://hastebin.com/qabijakiye.shell
i think my issue is to get a dash in front of every line
- {item}: /D {item}
@queen meteor I'm trying to test the automation and yeah, it isn't working
This one you provided me with: https://paste.ubuntu.com/p/KSbPhqjBgF/
The log doesn't show anything though
I don't know what I would begin to debug this
HI, I am trying to get my door sensor working right.
It is a ZW120 Door Window Sensor Gen5
by AEON Lab. I have configured it in HA and it works fine. But it is not working in Homekit and only shows as a motion sensor. Can you help me? Thanks
value_template: >
{% set lastAppStart = (as_timestamp(now()) - as_timestamp(state_attr('sensor.fullykiosk', 'lastAppStart') | default(0))) %}
{% if lastAppStart | timestamp_custom("%d") | int-1 == 1 %}{{ lastAppStart | timestamp_custom("%d") | int-1}} dag siden
{% elif lastAppStart | timestamp_custom("%d") | int-1 >= 2 %}{{ lastAppStart | timestamp_custom("%d") | int-1}} dager siden
{% elif lastAppStart | timestamp_custom("%H") | int-1 == 1 %}{{ lastAppStart | timestamp_custom("%H") | int-1}} time siden
{% elif lastAppStart | timestamp_custom("%H") | int-1 >= 2 %}{{ lastAppStart | timestamp_custom("%H") | int-1}} timer siden
{% elif lastAppStart | timestamp_custom("%M")|int == 1 %}{{ lastAppStart | timestamp_custom("%M") | int}} minutt siden
{% elif lastAppStart | timestamp_custom("%M")|int >= 2 %}{{ lastAppStart | timestamp_custom("%M") | int}} minutter siden
{% else %}Mindre enn 1 minutt siden
{% endif %}
Any idea why this fails?
What does it say when you try it at developer tools > template?
Hi, anyone have an idea why this template doesn't work when used in an automation?
- id: '1581240429894'
alias: Mobile app notification Fritzi phones while alone
description: ''
trigger:
- entity_id: sensor.fritz_box_call_monitor
platform: state
to: dialing
condition:
- condition: template
value_template: '{{state_attr("sensor.fritz_box_call_monitor", "from") | string == "0123456789"}}'
action:
- data:
message: Fritzi ruft an
service: notify.mobile_app_fabian_seins
When I use the same exact template in the UI Template Editor it works
What does it say when you try it at developer tools > template?
@buoyant pine
"Unkown error when rendering template"
@final abyss try each of the pieces separately with the variable and see what happens
Trying to use templates for the first time. Building a automation using HA automation via the front end...
Trigger type is template and the value template is
{% if is_state_attr('climate.upstairs_heating','state.attributes.preset_mode', 'boost') %}true{% endif %}
Is this valid ? The hive heating system I use always shows off during boost so I am trying to trigger off the preset_mode. Was not sure if I could even do that
let me try that !
value_template: '{{ is_state_attr(''climate.upstairs_heating'',''preset_mode'', ''boost'') }}'
That is what I have now in the front end. Going to turn the heat on and see if it fires π
That worked thanks so much !
Anyone recall off hand what the syntax is to change the output text and fill color/shape in a function? I can't seem to find it following losing my nodes (sd card death) a few months ago. I'm right on the cusp of it following https://nodered.org/docs/creating-nodes/status but can't recall how I was able to do that from within a function.
@nimble marsh #node-red-archived
Whoa I don't know how I ended up in #templates-archived... Thank you.
One moment I was searching #node-red-archived the next I was in #templates-archived π
Just sharing for sharing's sake. I couldn't find an example of this anywhere else, and spent over an hour getting it to work, so I figured I'd share it with others.
It's a water bill estimator template sensor.
https://www.reddit.com/r/homeassistant/comments/f1w26d/created_my_longest_template_sensor_yet_a_water/
Hi all, wondering if I could get some help - I'm trying to do an if statement template, but i constantly get Unknown error rendering template...
I've copied this basically right off the templating page, but no dice...
{% if states('sensor.gas_meter') | float > 20 %}
It is warm!
{% endif %}
@small valley what do you see when you try this in template editor? ```
{{ states('sensor.gas_meter') }}
Same thing... Weird... I'd expect that to spew the value of that sensor.
but obviously thats a problem
that means, it is not a valid entity. check the states tab for the correct entity id
yeah thats where i got it from..
it's there in the states tab, has a value under the states columb
*column
screenshot?
sure. assume i've to post it on imgur or something?
yup
try {{ states.sensor.gas_meter }} and share what you see?
Ha! My browser session must have timed out. I refreshed the page now its working as expected!!!
now both my code and your code works.
Wouldn't have expected to see the Unknown error in that case, but I guess I learned something today!
Thanks for your help. Off to get this working!!
weird, but glad it worked!
How do I find out what's causing this?
https://pastebin.com/zvsJSQL7
Looking at the last line, it looks like youβre trying to concatenate an int to a string somewhere. Depending on what youβre trying to do, you may just need to add |string to the int value to convert
But just complete speculation based on the amount of detail provided
Am trying to create a template sensor to see how many media_player devices are on but the learning curve is a bit too steep...
anyone who can help me on my way ?
what i've got so far is this, but it doesn't work
"num": 0
} %}
{% if is_state('media_player.samsung_55q80r', 'on') %}
{{var.num + 1}}
{% endif %}
{% if is_state('media_player.chromecast_beamer', 'playing') %}
{{var.num + 1}}
{% endif %}```
this just outputs two "1"'s
@bold valley suggested the following
{{ [states('media_player.bathroom_speaker'), states('media_player.bedroom_speaker'), states('media_player.chromecast_beamer'), states('media_player.chromecastaudio5312'), states('media_player.living_room_display'), states('media_player.mibox4_3'), states('media_player.playstation_4'), states('media_player.slaapkamer')] | select('playing') | list | count }}
but then I get an error Error rendering template: TemplateRuntimeError: no test named 'playing'
nevermind, already found it π
is_state('media_player.bathroom_speaker', 'playing'),
is_state('media_player.bedroom_speaker', 'playing'),
is_state('media_player.chromecast_beamer', 'playing'),
is_state('media_player.chromecastaudio5312', 'playing'),
is_state('media_player.living_room_display', 'playing'),
is_state('media_player.mibox4_3', 'playing'),
is_state('media_player.playstation_4', 'playing'),
is_state('media_player.samsung_55q80r', 'on'),
] | select('true') | list | count }}```
seems to do the trick..
asking for help somehow seems to help in figuring it out π
I'm trying to get data from my electricity meter. Everything works fine, but how can I change my code so it fetches the data from yesterday?
http://192.168.1.187/api/v1/powergas/day?limit=1&sort=asc&json=object&round=off&starttime={{ now().strftime('%Y-%m-%d') }}%2023:59:59
So what I need is to change this so it enters yesterdays date. How can I do this?
{{ now().strftime('%Y-%m-%d') }}
Hi guys. I trying to pass a value template into a shell command and am having some trouble with formatting, config check does not like it (quotes?). Here is what I have so far:
shell_command:
mail_merge: {{ states('sensor.mail_merge_command') }}
Put quotes around the template
When I put it in quotes I get this returned: Error running command: {{ states(sensor.mail_merge_command) }}, return code: 2
NoneType: None
2020-02-11 13:02:26 DEBUG (MainThread) [homeassistant.components.shell_command] Stderr of command: {{ states(sensor.mail_merge_command) }}, return code: 2:
b'/bin/sh: syntax error: unexpected "("\n'
2020-02-11 13:02:26 ERROR (MainThread) [homeassistant.components.shell_command] Error running command: {{ states(sensor.mail_merge_command) }}, return code: 2
NoneType: None
I suspect you can't template the whole command then
You'd have to pass that to a shell script, and have that call whatever it is you wanted
Pretty much
shell_command:
mail_merge: test.sh {{ states('sensor.mail_merge_command') }}
Somewhere in there - always good practice to full path it (eg /config/test.sh ...)
humm, PermissionError: [Errno 13] Permission denied: '/config/test.sh'
let me try that, ty
Closer hah: OSError: [Errno 8] Exec format error: '/config/test.sh'
I thought this would be pretty straightforward π
looks like this: convert -delay 300 -loop 0 -coalesce -fill white -dispose Background /config/www/mail_and_packages/1041778041-017.jpg /config/www/mail_and_packages/1041778056-017.jpg /config/www/mail_and_packages/mail_today.gif
oh no, that is not in front
That's not a shell script then π
if I paste that into the ssh add-on at the prompt it works. Although, that is something different?
That's just a command
So maybe I need something like...
shell_command:
mail_merge: "#!/bin/bash" + "{{ states('sensor.mail_merge_command') }}"
An actual shell script would be
#!/bin/bash
convert -delay 300 -loop 0 -coalesce -fill white -dispose Background /config/www/mail_and_packages/1041778041-017.jpg /config/www/mail_and_packages/1041778056-017.jpg /config/www/mail_and_packages/mail_today.gif
No, because that's a comment then...
You could possibly try
mail_merge: "/bin/bash {{ states('sensor.mail_merge_command') }}"
will try that <standby>
2020-02-11 13:33:53 DEBUG (MainThread) [homeassistant.components.shell_command] Stderr of command: /bin/bash {{ states('sensor.mail_merge_command') }}, return code: 127:
b'/bin/bash: convert: No such file or directory\n'
2020-02-11 13:33:53 ERROR (MainThread) [homeassistant.components.shell_command] Error running command: /bin/bash {{ states('sensor.mail_merge_command') }}, return code: 127
NoneType: None
So... you need to provide the path to convert
Assuming it's even installed in that container...
down the rabbit hole :). I think I follow, let me see if I can locakte the package
oooo found it! /usr/bin/convert
Does mail_merge: "/bin/bash {{ states('sensor.mail_merge_command') }}" become mail_merge: "/usr/bin/ {{ states('sensor.mail_merge_command') }}"
/bin/bash is the shell that runs the script/command
You might get away with just the template now you've provided the full path
Otherwise, no, not /usr/bin {{...
Hi at all! I'm new to HomeAssistant and am trying to get a grip. For my first project I tried to put my diy CUL to use and configured 2 shell commands in the configuration.yaml:
shell_command:
Plug01_on: echo is0FFFF0FFFFFF > /dev/ttyUSB0
Plug01_off: echo is0FFFF0FFFFF0 > /dev/ttyUSB0
But when I try to use it like this:
switch:
- platform: command_line
switches:
Plug 1:
command_on: Plug01_on
command_off: Plug01_off
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
I get error messages
Well, yes, those aren't valid entities π
Have a look at the example in https://www.home-assistant.io/integrations/shell_command/
action:
service: shell_command.set_ac_to_slider
I saw that but it was a step further. so the first part should be ok?
switch:
- platform: command_line
switches:
Plug 1:
command_on: shell_command.plug01_on
command_off: shell_command.plug01_off
You can check in
-> Services
Ah I see
Is a blank a nonallowed symbol in the name Plug 1? I guess it is what the log is trying to make clear to me?
Geting rid of all upper cases and the space got rid of the notification, it was something about invalid slug and pointed to my names. Seems ok now.
///invalid slug Plug01_on (try plug01_on) for dictionary value @ data['shell_command']. Got OrderedDict([('Plug01_on', 'echo is0FFFF0FFFFFF > /dev/ttyUSB0'), ('Plug01_off', 'echo is0FFFF0FFFFF0 > /dev/ttyUSB0')]). (See /config/configuration.yaml, line 26).
That was the entry for reference
Yeah, see the link above about entity names
Great, thanks a lot, I guess after you get this specialties it looks very powerfull. Do you have another nodge in the right direction how to get a basic switch on the overview/dashboard?
Have you created the switch?
I found that I have to add a entity on the overview and have the switch on the overview
currently debugging why it isn't working in the physical world
The #frontend-archived will only display things that exist
Check
-> States to see if it exists
Yes, it is on the states list and on my overview with a flash and crossed out flash symbol and i can switch back and forth
Thanks for your help Tinkerer. Seams like the echo is0FFFF0FFFFFF > /dev/ttyUSB0 isn't working in the shell either, so not HAs fault. Logs show a error from the system after switching the switch and it snaps back to the other side. Strangely the echo command on a RaspianOS would switch my sockets, but here nothing, despite the LED on the arduino flashing for incomming data...
If you're using #330944238910963714 then you need to ensure the stick is passed through
Even though I used the webshell? And it must be ok because i got traffic on the usb2serial led on the arduino.
Hello. I'm new to HAS. Is it possible to create a state in a template switch? This is my end goal: I have a door sensor hooked up to home kit. I want to be able to detect the state of the door via HAS. The sensor is HomeKit BTLE so it can't be added via HAS. I want to create a custom switch in HAS that is exported to homekit. I'd then setup an automation in homekit to toggle the HAS exported switch when the sensor changes. My thought was to basically create a template switch with an action assigned to it. But I'd need to implement state for it. I was thinking the state would just be set when on and off were called.
Or maybe there's an existing integration that allows for mock switches and I just can't find it.
sounds like you might want an input_boolean
@deep sparrow binary_sensor? that may work
I'll check those out. Thanks!
input boolean was perfect. Thanks.
cool! you're welcom
So, I'm using the UPnP integration for my DDWRT router, but the issue I'm having is the data I'm getting is measured in bytes, and it rolls over to zero quite often. I want to get a sensor that tells me the gigabytes used for today, this month, and this year.
How can I do this? Can Template Sensors do this?
@oak summit you should be able to do it with https://www.home-assistant.io/integrations/history_stats/
How can I get the previous state of a sensor?
Typically when a state change happens, it overrides the old value with the new one. You could, however, have an automation that triggers on state change, and store the old value in a variable or some sort. If you are really want to go back in the history, you could use SQL sensor.
@oak summit posted a code wall, it is moved here --> https://paste.ubuntu.com/p/gJBbbPR8ry/
I mean... that wasn't a code wall but okay >.>
I'm going to make a more detailed post on the community forums, I feel like this problem may be much more difficult to handle than I thought.
The Alexa integration exposes the time of the next timer (when it ends) and I can get this time with {{ states("sensor.kitchen_next_timer") }}. Templating is not my strong suite - how do I subtract the current time from this value? Basically I'm trying to get the remaining time on the timer. Possible?
I just thought of something... what if I figure out what the max value is, the value that it resets at... then make an automation where anytime the sensor goes down from the previous reading, it increments a counter, and then use that to calculate out the gigabytes...
Is there a template trigger for an automation where I can say if the new value is less than the previous value to trigger? I've figured out that the UPnP bytes sent/recieved just keeps resetting at the 32bit unsigned integer limit, but home assistant basicly never sees it hit that number, it always catches the value just after the roll over, so it goes from 4bil to like 2k and just starts counting up again.
@oak summit state trigger, then in your condition check the state using trigger.from_state.state | float < trigger.to_state.state | float
hello guys i have created my template, im sure its worked in the past but its not now, i used the states editor but its thowing an error
platform: template
battery_level:
friendly_name: "x's Note 9 Battery Level"
value_template: "{{ state_attr('device_tracker.sm_n960f', 'battery_level')|int }}"
device_class: battery
unit_of_measurement: '%'```
``Error loading /config/configuration.yaml: mapping values are not allowed here
in "/config/configuration.yaml", line 21, column 12``
Is it possible to create a template to show my Daily power usage and production (seperated) of the day before?
Would be nice to check it once in a while, since a have Solar Panel for a month now
sensor:
- platform: history_stats
name: Verbruik vandaag
entity_id: sensor.power_consumption_watt
state: '????'
type: time
end: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
duration:
hours: 24
Not sure what state i need to use, it shows the Power Usage which does not have a static "state"
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
@balmy moth your indentation is off, see the example here: https://www.home-assistant.io/integrations/template/
Hi guys, to grab some data from an API I would need a sensor with yesterdays date. What's the easiest way to get this?
Is there a way to manimulate datetime %Y %m %d to yesterdays date?
I suck at templates -- Does this look right?
- platform: template
sensors:
boys_room_white_noise_playing:
friendly_name: "Boys room white noise machine playing"
value_template: >-
{% if ( states('sensor.boys_room_white_noise_energy_power')|int > 0) %}
true
{% else %}
false
{% endif %}
Want binary sensor to be on if the power draw is over 0w
value_template: >-
{{ states('sensor.boys_room_white_noise_energy_power')|int > 0 }}
So much better, thank you!
Is there a way to manimulate datetime %Y %m %d to yesterdays date?
@main steppe
Got it, I fixed it by going back 86400 seconds in time (one day).
yesterday_date:
value_template: >
{{ (as_timestamp(now())
- 86400)
|timestamp_custom('%Y:%m:%d', false) }}
I have 3 input_booleans named timer_30min, timer_60min, and timer_90min. I'm trying to come up with a way in my automation to toggle the state of the correct input_boolean. I started experimenting and have this non-working code:
{% if is_state('input_select.fan_time_select', '30') %}
input_boolean.timer_30min
{% elif %}
{% if is_state('input_select.fan_time_select', '60') %}
{% endif %}
Rather than doing some if/else statements I started trying to think of how to just toggle the correct input_boolean directly, something like this:
action:
service: input_boolean.toggle
entity_id: input_boolean.timer_{{ states('input_select.fan_time_select') }}min
Is doing this way OK?
That creates the correct "text version" of the entity_id but it throws an error
need to do something like this:
action:
service: input_boolean.toggle
data_template:
entity_id: "input_boolean.timer_{{ states('input_select.fan_time_select') }}min"
Tried that but I still get the error:
Invalid config for [automation]: not a valid value for dictionary value @ data['action'][1]['entity_id']. Got None. (See ?, line ?).
Whoops, missed adding the data_template
Thanks, that did pass the config test now
Following up on this action I would like to create the "inverse" of it. With the above action from @buoyant pine I'm able to toggle the correct boolean from input_select.fan_time_select but now I want to add an action that turns off the other 2 input_boolean. Something like:
action:
service: input_boolean.turn_off
data_template:
entity_id: "input_boolean.timer_{{ not is_state('input_select.fan_time_select') }}min"
Basically if 30 is selected then I want to turn off 60 and 90 so I think I might need a for loop to check each input_select option but I'm not sure
Simplest would probably be to make another automation with each of the booleans turning on as a trigger with an action that turns the others off based on which one was the trigger
OK, I kind of have something like that already that I guess I could make work. I was just wondering if there was a "simpler" way.
Yes, there is.
@queen meteor Well I'd be curious to see what your idea is. I've been playing around for a bit and haven't stumbled across the right combination of logic yet
Whatβs the trigger?
- alias: Update Fan Timer
trigger:
# Trigger whenever the input_select state changes.
platform: state
entity_id: input_select.fan_time_select
condition:
condition: template
#entity_id: input_select.fan_time_select
# Ignore state changes to '0', or 'OFF', or whatever we want to set the off state.
value_template: "{{ not is_state('input_select.fan_time_select', 'OFF') }}"
you can use exclude filter to filter out the entities
...searching for examples....
give me one sec...
thanks you, np
something like this... ```yaml
action:
- service_template: "input_boolean.turn_off"
data_template:
entity_id: >-
{% set entities = ["input_boolean.timer_30min", "input_boolean.timer_60min", "input_boolean.timer_90min"] %}
{{ entities |reject("equalto", "input_boolean.timer" + states('input_select.fan_time_select') + "min")|list }}
I always forget about that
Ugh, I wasn't even close to something like that but I was trying to find a way to create that "array" automatically.
make sure your conditions are correct, otherwise it will turn off everything π
Debugging it now as I got an error
there is a missing " there... let me fix the code above.
try that code now - hopefully that wont break!
you added " after min?
yup
Yeah, that passes now. The logic certainly seems correct staring at it so many thanks for helping. I'll do some testing and see what happens!
something like this... ```yaml
action:
- service_template: "input_boolean.turn_off"
data_template:
entity_id: >-
{% set entities = ["input_boolean.timer_30min", "input_boolean.timer_60min", "input_boolean.timer_90min"] %}
{{ entities |reject("equalto", "input_boolean.timer_" + states('input_select.fan_time_select') + "min")|list }}
@queen meteor
Minor edit to add a "_" after "input_boolean.timer
it's your entities... that's why I said something like this..." π
@void steeple posted a code wall, it is moved here --> https://paste.ubuntu.com/p/MgsqSgDDWY/
can someone help me clean the macro up I have been trying to get this to work for a couple hours.. I need to break out but I know the jinja doesnt break like python. https://paste.ubuntu.com/p/MgsqSgDDWY/
the sample input is K:992323;Upstairs; I would like to to return just 992323
Continuiing my debugging from last night as the input_boolean.turn_off action isn't working. When I enter:
{% set entities = ["input_boolean.timer_30min", "input_boolean.timer_60min", "input_boolean.timer_90min"] %}
{{ entities |reject("equalto", "input_boolean.timer_" + states('input_select.fan_time_select') + "min")|list }}
in the template editor I get what looks to be correct: ['input_boolean.timer_30min', 'input_boolean.timer_90min']
When I go to the service tab and enter: entity_id: ['input_boolean.timer_30min', 'input_boolean.timer_60min'] in the YAML section that correctly works but if I paste what the template editor returns into the entity field the YAML field gets changed to:
entity_id: 'entity_id: [''input_boolean.timer_30min'', ''input_boolean.timer_60min'']'
So I'm getting extra quotes for some reason
I think I need a tuple rather than a list but replacing list with tuple returned an error so as a hack for now I just added |replace("'", "")|replace("[", "")|replace("]", "") after |list
@grave ruin if you don't want a list, and want to get a comma separated string, you could simply replace | list with | join(',')
Let me try that and see if it works
Thanks again @queen meteor I'm sure it's no surprise to you but that did the trick. Just for completeness here's how it looks in case someone else crazy enough to want to do something similar:
- service_template: "input_boolean.turn_off"
data_template:
entity_id: >
{% set entities = ["input_boolean.timer_30min", "input_boolean.timer_60min", "input_boolean.timer_90min"] %}
{{ entities |reject("equalto", "input_boolean.timer_" + states('input_select.fan_time_select') + "min")|join(',') }}
I'll probably be back because I should expand on this because currently I just use a input_boolen.toggle and don't act if it's switching from on to off. If it does switch to off then I should be canceling the timer
So this template works in the editor but it doesn't work in my automation. Do I have to use a condition: or and split these up to make it work?
- alias: Fan Timer Expired
trigger:
platform: template
value_template: "{{ (is_state('timer.garage_afs', "finished")) or (is_state('timer.garage_afs', "canceled")) }}"
"doesn't work" meaning throws an error, expected <block end>, but found '<scalar>'
change your inside double quotes to singles?
I'll try that but I just tried this and got a different error:
- alias: Fan Timer Expired
trigger:
platform: state
condition:
condition: or
conditions:
- condition: state
entity_id: 'timer.garage_afs'
state: 'finished'
- condition: state
entity_id: 'timer.garage_afs'
state: 'canceled'
Invalid config for [automation]: required key not provided @ data['trigger'][0]['entity_id']. Got None. (See ?, line ?). is the error for the above change
Thanks @long basalt that was it. Staring at it too long I guess
for a state trigger you need at the minimum:
platform: state
entity_id: domain.your_entity
``` that's what "required key not provided..." means
is there anyway to get the domain of your trigger as part of an automation template?
Sure. trigger.to_state.domain
i just saw that actually. Thanks mate. I think the docs need some better linking for idiots like me...
Lmao no prob
Does anyone know why this template doesn't work? https://pastebin.com/B3JRrbSP
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/automations.yaml", line 646, column 5
expected <block end>, but found '<scalar>'
in "/config/automations.yaml", line 647, column 38
value_template: '{{ (state_attr('media_player
^
Change the first and last of those to "
You can't use the same quotes outside the template as inside the template
hey all, having an issue with a data template using automation editor
trying to use a single automation to configure pico remote
@wraith cliff posted a code wall, it is moved here --> https://paste.ubuntu.com/p/sW2S4NwTS4/
@wraith cliff posted a code wall, it is moved here --> https://paste.ubuntu.com/p/rh3Kb74FmT/
hmmph
{% if trigger.to_state.state == '2' %}
entity_id: cover.dining_windows
position: 50
{% else %}
entity_id:cover.dining_windows
{% endif %}```
i have a corresponding service template to go along with it
but the editor does not like my data template
{% if trigger.to_state.state == '1' %}
cover.open_cover
{% elif trigger.to_state.state == '8' %}
cover.open_cover
{% elif trigger.to_state.state == '4' %}
cover.close_cover
{% elif trigger.to_state.state == '16' %}
cover.close_cover
{% elif trigger.to_state.state == '2' %}
cover.set_cover_position
{% endif %}```
@arctic sorrel I've had 5 years of programming classes in all sorts of languages and I still manage to mess that up... Thank you very much
No worries
@wraith cliff Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, codewalls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
please watch the line limit
ah, sorry
And if the bot moves - don't re-post FFS
also that's not how you use data_templates
i can't conditionally set data values?
should be:
data_template:
entity_id: (template here)
position: (template here)
you can, just not in the way you're trying to
if i set a position on open_cover, it fails
so you're saying I cant handle in a single automation?
position is not allowed on open_cover
meh, that sort of defeats the purpose
not really
but it does. so instead of 2 automations, now i have 1 automation and 1 or 2 scripts
just moves the code elsewhere
i'm not seeing the problem 
yeah i can make either solution work, i was hoping to have it in a single automation
without calling another script
might i ask why? i'm just curious since i do this all the time
i'm trying to reduce the number of entities
and managing things in the UI becomes problematic when i have a shitload of scripts and automations
especially when i have like 20 odd Pico remotes
have you taken control of lovelace?
then you can include only what you want to see in the overview
what a weirdly phrased question
inthe automation and scripts UI
id ont want to see 100s of line items
its a management nightmare
ah gotcha. i don't use the UI editors
i selectively put items on my lovelace UI
i use both the yaml directly and the UI for simple stuff
and since you can template in there...it's making it much easier to ditch editing the automations.yaml directly
i have my config, automations, scripts, etc. split out into smaller pieces to make it easier to manage for that reason. but yeah that's not helpful if you're using the UI editors
it seems to be the direction home assistant is going, so i'm trying to get on board
and making quick changes in the UI is a bit easier
well you're not gonna lose the ability to write the YAML for automations and stuff directly
there would be a riot
especially since i'm running Home Assistant Core, i dont have the nice VS Code add-on
i'm also running HA core. i use a cloud9 IDE container for editing
it's a pretty nice interface
i can access it locally or remotely via nginx set up on my server
my docker points to a shared config on my synology, so yeah i can remotely edit
also you might be able to find a vscode docker container
since the addon is just that, a docker container
right
yeah, still not the solution i was hoping for
will be eagerly waiting grouping function in automations editor.
organization becoming a bit of a bitch in the UI
resource: "http://192.168.1.187/api/v1/powergas/day?limit=1&sort=asc&json=object&round=off&starttime={{ states.gisteren_datum }} 23:59:59"
I use this code for my API in a template, but it isn't working. Is there a way that I can see what's going on?
Or how can I echo this line?
you can test it at developer tools > template to make sure it's returning what you want
ah yeah that too
Hey everyone,
Please use imgur or other image sharing web sites, and share the link here.
I'm still new to Home assistant
yeah, you can click edit on your messages and copy them
I was experimenting last night and trying to change an automation so it triggered from a timer finishing or if the timer was cancelled. Here's what I tried:
- alias: Fan Timer Expired
trigger:
# Turns off the fan only when timer expires normally.
platform: template
value_template: "{{ (is_state('timer.garage_afs', 'finished')) or (is_state('timer.garage_afs', 'cancelled')) }}"
That "decodes" correctly but it isn't being triggered when the timer finishes
I think the automation engine has to decode which entity states to track
no need to use a template there tbh. this should work:
trigger:
- platform: state
entity_id: timer.garage_afs
to:
- finished
- cancelled
that'll trigger when the state of that timer goes to finished or cancelled @grave ruin
though that template trigger looks fine, as long as those are actual possible states for the timer
(also, using a list in to: or from: is currently undocumented, but it works)
Hi,
Could a template wizard help me. I need the entity Id from a list that has the highest sensor value. Iβve seen minmax but i want the sensor id. Not itβs value. I figure I need to make a list, find the index of the max and output the entity at that location. But Iβm new to temp laying and Iβm a bit lost. Iβm playing with the monitor script on a bunch of pi zeros to try and get room level locations.
Thanks @buoyant pine I think my problem might have been that the timer doesn't "hold" those states? I've changed to your style as once again that makes sense so I'll test that. I've been off breaking other stuff so I'll follow up with that adventure in a bit
well your template should still work as long as those are valid states and as long as the sensor changes from any other state to one of those states
i don't user timers so i don't know what's valid
so i'll just have to trust you π
If anyone wants their stuff broken just let me know, I can help!
I'm in mode: yaml so I don't have to reload changes do I? I have been reloading but not restarting with a bunch of these changes I'm trying
developer tools > states is where you want to check for the actual state btw (not sure if you know that or have been told that already)
Yes, thanks, I'm heavily on that page and the template page, as well as checking the log book to see what happened
you can reload everything you see at configuration > server controls without restarting home assistant (plus any input_* integration using the input_*.reload services)
mode: yaml sounds like a frontend thing which wouldn't affect what you can reload without a restart
I do that for good measure, didn't know about the input_*
OK, thanks. Here comes the latest breaking change....
So here's a service that's part of an action of an automation (that's a mouthful):
- service_template: >
{% if is_state('group.garage_afs', 'on') %}
timer.start
#{% else %}
#timer.cancel
{% endif %}
data_template:
entity_id: timer.garage_afs
duration: "00:{{ states('input_select.fan_time_select') }}:00"
can't have comments (like that) in a template
OK, I'll remove. I just want to start the timer of one entity of the group is on
{# this is a jinja2 comment #}
my brain can only absorb and retain so much!
MOAR knowledge
you can use conditions in the action: part of the automation btw
probably better than a service template with one if and no else
so something like
action:
...
- condition: state
entity_id: group.garage_afs
state: 'on'
- service: timer.start
data_template:
...
if the condition isn't met, the action stops there
I started with that but I have a service after this that needs to run so my understanding is if a condition "fails" then that immediately stops the entire automation. Or did I get that wrong?
nope, you got it right. note what i said about using it in the action: section though
Well if you want to make you r brain hurt you can take a look at what I'm struggling with, https://paste.ubuntu.com/p/nKkNbKMq2f/. This is the main automation for fan package
goodness
Yeah, you can see some of the testing I've been trying, I KNOW it's a mess!
lol it's all good
30,000 foot view:
- 3 boolean buttons on the screen that allow you to set the length of time before it will turn off the fan
- If you set a time you can go back and click the same time and the timer should be cancelled
- You can pick a new fan time whenever and it just changes the timer
- the fan is actually a bank of 3 independent switches so I've got scripts/automations to handle that
i've gotcha
if you want to make your brain hurt, take a look at my favorite automation that i've ever written: https://github.com/Tediore/My-HASS-config/blob/master/config/automations/speaker_volume.yaml (first one in that file)
To really spin your head, here's the complete fan package in case you're a glutten for punishment, https://paste.ubuntu.com/p/PkfhJC7RTg/
sees 320 lines
nope.png
ouch, it has grown. Once I get this working I'll have to go back and trim the fat because I'm sure there's leftover stuff that can go away
normal part of the process 
the automation that i shared above used to be 10 separate automations until i learned more about templating
now it's 1 automation
Well I'm a hardware guy (hence the million questions and trial and error) so if you need board design I can help with that
i'm an analyst
i know all about asking lots of questions
because i do the same lol
I changed back to this because I realized that I need to cancel the timer if it is running:
- service_template: >
{% if is_state('group.garage_afs', 'on') %}
timer.start
{% else %}
timer.cancel
{% endif %}
data_template:
entity_id: timer.garage_afs
duration: "00:{{ states('input_select.fan_time_select') }}:00"
But if I select the 30min timer and then go back and select it again, the timer is not canceled nor is the last service run input_select.fan_time_select to OFF but the button does changes state so the automation is triggered and runs the first action
I had a feeling passing duration when I was trying to cancel the timer might be an issue and I forgot to check the logs, which showed:
Error while executing automation automation.update_fan_timer. Invalid data for call_service at pos 3: extra keys not allowed @ data['duration']
So I changed to this:
- service_template: >
{% if is_state('group.garage_afs', 'on') %}
timer.start
{% endif %}
data_template:
entity_id: timer.garage_afs
duration: "00:{{ states('input_select.fan_time_select') }}:00"
- service_template: >
{% if is_state('group.garage_afs', 'off') %}
timer.cancel
{% endif %}
entity_id: timer.garage_afs
and I get this error:
Error while executing automation automation.update_fan_timer. Invalid data for call_service at pos 4: Service does not match format <domain>.<name>
pos 4 is the last one I listed
Hi, need help.
How can I configure scan_interval to make the request every hour.
That is, every hour, taking as reference the current time.
I don't want to use 3600s, since I would start counting from 2:37 p.m.
I need to make the call at 14,15,16,17,18 ... etc
mi sensor:
- platform: rest
resource: https://api
name: PVPC
value_template: '{{ value_json["PVPC"][now().hour].NOC }}'
scan_interval: 36000
Set the scan interval very, very long (years) and then use an automation triggered on the hour to call the update entity service.
mmm
understand....
i try, thanks
Set the scan interval very, very long (years) and then use an automation triggered on the hour to call the update entity service.
@fossil venture how configure every hour? in automatization?
ahh ooki perfect, thanks!
@fossil venture how trigger resquet api for update sensor created?
hi again
why result is 0.0
- platform: rest
resource: https://api.esios.ree.es/archives/70/download_json?locale=es
name: PVPC
value_template: "{{ (value_json['PVPC'][now().hour].NOC|float/10)|round(2) }}"
scan_interval: 36000
?? template worng? i dont understand
@opaque thorn the value {{ (value_json['PVPC'][now().hour].NOC) }} doesn't return a single value - it returns something like 108,24. When you convert to float, that becomes 0.0
try ```
"{{ (value_json['PVPC'][now().hour].NOC.split(',')[0]|float/10)|round(2) }}"
@opaque thorn ```
service: homeassistant.update_entity
entity: sensor.mi_sensor
try ```
"{{ (value_json['PVPC'][now().hour].NOC.split(',')[0]|float/10)|round(2) }}"
@queen meteor thanks so much
@grave ruin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/nDkxyGXcgh/
Sorry about that, I thought 20 lines was OK but it looks like it's >=20 lines
hi guys, i need some help with a litlle code can someone help me?
https://pastebin.com/BHaYztdA
give me the the error--->Falha ao chamar o serviΓ§o script/remote_ac_power. not a valid value for dictionary value @ data['entity_id']
i think the limit is like 12 now
ignore my earlier comment. I think you should check whether the entities script.remote_quente_basculante16 & 16 are existing. Also try giving single quote in you if statements
Confused by the Code Wall bot, I only posted 5 lines of code? Sorry, Iβm new round here.
@pastel bronze please dont keep posting ....you total post is 19 lines and thats why its moving it
Hi, trying to create a template to find the sensor that is showing the strongest signal. So far, I have.....
βββ
{% for rssi in states.sensor | sort(attribute="state") %}
{%- if 'Sarah' in rssi.attributes.friendly_name and rssi.attributes.unit_of_measurement == 'db' and rssi.state != 'unknown'%}
{{ rssi.attributes.friendly_name }}: {{rssi.state}} {{- rssi.attributes.unit_of_measurement}}
{% endif -%}
{%- endfor -%}
βββ
But it is sorting alpha, not numeric. How would I make it sort numeric? Also, I really only want to know the highest value, so there is probably a simpler way. Sorry for all the CodeWall posts, just trying to find my feet. Thanks !
{% for rssi in states.sensor | sort(attribute="state") %}
{%- if 'Sarah' in rssi.attributes.friendly_name and rssi.attributes.unit_of_measurement == 'db' and rssi.state != 'unknown'%}
{{ rssi.attributes.friendly_name }}: {{rssi.state}} {{- rssi.attributes.unit_of_measurement}}
{% endif -%}
{%- endfor -%}
wrong ticks on qwerty keyboard its above caps lock
Like this
Testing
Thanks and sorry for being a muppet.
no worries
Is it possible to use the trigger data in an automation to decide which service to use in an action?
E.g.: multiple device_tracker as trigger, and decide which notify.mobile_app to use in action based on that.
Yup. trigger.to_state.entity_id to reference the entity ID that triggered the automation would be one option
And then map the entity_id to service? Can I just template the service? π
I just read the docs:
You must use service_template in place of service when using templates in the service section of a service call.
Sure, you can template the service. I've done something similar here to template an entity ID used in a service call based on the trigger: https://github.com/Tediore/My-HASS-config/blob/master/config/automations/speaker_volume.yaml
First automation in that file
Thanks! Got it working π
message: >
StΓΈve har gΓ₯tt {{ states.counter.vacuum_run_counter.state }} ganger
{{- '\n' -}}
Friendly name: {{ trigger.to_state.attributes.friendly_name }}
service_template: >
{% if trigger.to_state.attributes.friendly_name == 'Petter' %}
notify.mobile_app_petters_iphone
{% elif trigger.to_state.attributes.friendly_name == 'Vacuum Dust Bin Today' %}
notify.mobile_app_petters_iphone
{% else %}
notify.mobile_app_so_iphone
{% endif %}```
Had to use a boolean to test a bit, but this does the trick π
Nice! Btw using the states() and state_attr() methods are better than the states. method. Helps prevent errors when the entity isn't available such as on startup
@buoyant pine So these two should be the same?
{% elif state_attr('trigger.to_state', 'friendly_name') == 'Vacuum Dust Bin Today' %}
{% elif trigger.to_state.attributes.friendly_name == 'Vacuum Dust Bin Today' %}
It is not working unfortunately.
This works when testing under Dev tools - Templates:
true
{% endif %}```
So maybe I am getting the attributes for trigger.to_state-object wrong.
Ah sorry, I was referring to the vacuum run counter. Though I think it'll work for the trigger state object if you remove the quotes around trigger.to_state
hi, is there a way to change the state name for binary sensors?
The state displayed in the frontend or the actual state?
i'm looking https://www.home-assistant.io/docs/configuration/customizing-devices/ here but can't really make heads or tails of it.
displayed. I'd like to be able to pass through a state to node-red so I dont have to define the notification 'state'
But you can change the device class to change what's displayed in the frontend
right now it notifies a door is on or off
i was thinking maybe a cover is the answer?
No clue unfortunately, I don't use node red
ah, well the displayed state would be the same in HA?
from 'on' and 'off' to 'open' or 'closed'
hope that helps clarify.
Are you just trying to pass the state through so that it's human-readable? If so I just type out in my automations 'open' or 'closed' instead of passing the actual state through. You can use an if template, so that if the state is on it passes open
In node red I believe you can use a switch node for that
Yeah that sounds about right. Basically trying to find a way to convert on / off messages to open / close in node red
I suppose a workaround would be creating a template sensor
But that seems...not nice
I'd ask if there's a way to do that directly in #node-red-archived
You can use a function node for that.
msg.payload = "open"
}
if (msg.payload=="off"){
msg.payload = "closed"
}```
Ah there ya go
Or alternatively just a switch node to do two different branches depending on on or off and then just hard code the text you want it to say
very cool, thank you @white ruin
@buoyant pine
Ah sorry, I was referring to the vacuum run counter. Though I think it'll work for the trigger state object if you remove the quotes around trigger.to_state
Did not work. I utilized states() in the other spots, thanks for the tip π
No prob, sorry for the confusion with that
Try reading my mind better next time π
@white ruin when i send on through the inject node nothing is outputted from teh function node.
I would suggest asking in #node-red-archived. I know it's possible to do it that way but I'm not well versed in node-red and the people in that channel will be better able to help
thanks, i will.
@flat hatch posted a code wall, it is moved here --> https://paste.ubuntu.com/p/HxQ3X4F8Hx/
@flat hatch posted a code wall, it is moved here --> https://paste.ubuntu.com/p/VVtv25z4Kz/
hi i have a problem with creating a template how to solve it ??
@flat hatch posted a code wall, it is moved here --> https://paste.ubuntu.com/p/383k2hmzwq/
~rule6 @flat hatch
@flat hatch Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, codewalls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
can I still get a list of all turned on lights?
oh yea - Thanks petro!
{% set domain = 'light' %}
{% set state = 'on' %}
{{ states[domain] | selectattr('state','eq', state) | map(attribute='entity_id') | list | join(', ') }}```
lets see if this works out π€
data_template:
entity_id: >
{% set domain = 'light' %}
{% set state = 'on' %}
{{ states[domain] | selectattr('state','eq', state) | map(attribute='entity_id') | list | join(', ') }}
brightness: >
xxxxxxxx would be nice for exery light on xxxxxxx
{{ (brightness / 100 * 85) | int if (brightness / 100 * 85) >= 11 else 0 | int }}
transition: 5
deam... that makes the lights brighter...
aaahhh.. fuuu
that will take any light and pushes the state to all other...
@flat hatch change plugs_kwh_Today to plugs_kwh_today and similar for the other one with a capital letter in the slug
As the error message suggests
hello
can someone help me please?
error--> Falha ao chamar o serviΓ§o script/remote_ac_power. not a valid value for dictionary value @ data['entity_id']
What do you see when you paste the template at dev tools > template?
@buoyant pine i didnt understand your question sorry
Paste everything under entity_id: > in the text field at developer tools > template
And look at what the output is
remote_ac_power:
sequence:
- service: script.turn_on
data_template:
entity_id: >
############################
PEAR THAT
sorry caps, apear that
Everything under entity_id: >
This:
{% if is_state("input_select.ac_operation_mode", "AQUECER") and is_state("input_select.ac_swing_mode", "BASCULANTE") and is_state("input_select.ac_target_temp", "16") %} script.remote_quente_basculante16 {% elif is_state("input_select.ac_operation_mode", "AQUECER") and is_state("input_select.ac_swing_mode", "BASCULANTE") and is_state("input_select.ac_target_temp", "17") %} script.remote_quente_basculante17 {% endif %}
in dev tools dont apear nothing bellou entities
I'm saying copy what you have under entity_id: >, go to developer tools > template, and paste it in the text field there and see what appears on the right side
Clear out the text field at developer tools > template before pasting in your data
if i put only what i have under entity, in right side dont apear nothing
you want to see a print?
in first view i think that its forbidden multiple condicions on a service
Nah it's probably because you have no {% else %}
And the target temp is neither 16 nor 17
i have a error but i rewrite
in "imput_select" temperature was "imput_number"
i add the {% else %} and kind a work, but now i didnt now why the other condicions are false, because 1 are true
if i put that
remote_ac_power:
sequence:
- service: script.turn_on
data_template:
entity_id: >
{% if is_state("input_select.ac_operation_mode", "AQUECER") and is_state("input_select.ac_swing_mode", "BASCULANTE") and is_state("input_number.ac_target_temp", "16") %} script.remote_quente_basculante16
{% elif is_state("input_select.ac_operation_mode", "AQUECER") and is_state("input_select.ac_swing_mode", "BASCULANTE") and is_state("input_number.ac_target_temp", "17") %} script.remote_quente_basculante17
{% else %} xxx
{% endif %}
give me that
remote_ac_power:
sequence:
- service: script.turn_on
data_template:
entity_id: >
xxx
and in input states are Aquecer Basculante 17
yes
17.0
i will put 17.0
i think that will work...
man you are the best
now it work
withou the else to π
but i think that is a bug off home assistant because i have the next config
ac_target_temp:
name: Escolha temperatura
min: 16
max: 30
step: 1
if the step are 1 the number in logic should be 16, 17, etc
please appolagice me but, if the step are 1 tha variavel are int(9 for example), if the step are 0.5 (9.5 for example) the variavel are float, i'm wrong or comunicate a bug to home?
anyone have a template for dimmers?
Context: I have an Ikea tradfri dimmer (new one) and an tradfri bulb. Both connected to HA. Want the dimming function to actually work
what is wrong in this template, i want to return TRUE if temperature range is between 28 to 42 else return the temprature value
currently the temprature is 30.9
but still i dont get TRUE as reply
{% if is_state('sensor.bme680_temprature', '>=28' and '<=42') %} {{ 'True' }} {% else %} {{ states('sensor.bme680_temprature') }}. {% endif %}
@edgy dirge i'm not sure you can do a test like that with is_state() (though if you've seen a working example, please direct me to it because i'd be interested to see it). try this:
{% if 28 <= states('sensor.bme680_temprature') | float <= 42 %}
'True'
{% else %}
{{ states('sensor.bme680_temprature') }}
{% endif %}
i tested the above with a sensor of my own and it works
i will give it a try. above is just a test code/templlate
what am trying to achieve is to arrive at AQI from BME680 Sensor
am trying to create template sensor for this code to arrive at AQI using Temp & gas resistance from the code @buoyant pine
want to convert this into Template sensor
if (current_humidity >= 38 && current_humidity <= 42) humidity_score = 0.25 * 100; else { if (current_humidity < 38) humidity_score = 0.25 / 40 * current_humidity * 100; else { humidity_score = ((-0.25 / (100 - 40) * current_humidity) + 0.416666) * 100; } } return humidity_score; }
Someone could help me to integrate this on my home assistant? https://github.com/lukevink/hass-config-lajv
@edgy dirge ok, so apply that to what i posted above:
{% if 38 <= states('sensor.your_humidity_sensor') | float <= 42 %}
25
{% elif states('sensor.your_humidity_sensor') | float < 38 %}
{{ 0.25 / 40 * states('sensor.your_humidity_sensor') | float * 100 }}
{% else %}
{{ ((-0.25 / 60 * states('sensor.your_humidity_sensor') | float) + 0.416666) * 100
{% endif %}
great thanks
@buoyant pine is there a way to create the entire code in single template sensor?
that's what you would put in the template sensor
@edgy dirge ok, so apply that to what i posted above:
{% if 38 <= states('sensor.your_humidity_sensor') | float <= 42 %} 25 {% elif states('sensor.your_humidity_sensor') | float < 38 %} {{ 0.25 / 40 * states('sensor.your_humidity_sensor') | float * 100 }} {% else %} {{ ((-0.25 / 60 * states('sensor.your_humidity_sensor') | float) + 0.416666) * 100 {% endif %}
@buoyant pine This gives only Humidity score
similarly i want to calculate gas score
then total score
well, you can figure that out based on what i posted for the gas score π
then eveluate AQI
well, you can figure that out based on what i posted for the gas score π
@buoyant pine Which meas each score is a seperate template sensor? Is my understanding right
probably the most practical, otherwise you'll have a very long template
alternatively, you could see if someone's made a custom component that does all this. one exists for calculating dew point so who knows
Someone could help me to integrate this on my home assistant? https://github.com/lukevink/hass-config-lajv
@tranquil dome When i try to copy his settings to start over it, the control light lovelace page is totally blank
@tranquil dome that is someone elses configuration, you will need to adapt the code to fit your own entities when you copy it over...it wont just work by copying it and calling it a day.
@charred haven I know this. Iβm trying to adapt it. And I canβt understand why I have white page on first two tab
what part are you trying to copy over? might be helpful if you show the specfic section
what part are you trying to copy over? might be helpful if you show the specfic section
@charred haven I'm trying to copy the light part
@tranquil dome there is way to much in that link to decipher what you mean by the light part....can you share the code you used so we can look at just that portion?
~share @tranquil dome
@tranquil dome Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
@tranquil dome there is way to much in that link to decipher what you mean by the light part....can you share the code you used so we can look at just that portion?
@charred haven https://hastebin.com/sinarelibu.bash
i have a blank lovelace tab
@tranquil dome ok you should be in #frontend-archived to get help on this as its only UI related....share teh link you sent here with them but keep in mind you have a lot going on here so it may be difficult to get help
In the docs (https://www.home-assistant.io/docs/configuration/templating/#priority-of-operators) it notes that {{ states('sensor.temperature') | float / 10 | round(2) }}
Would round 10 to 2 decimal places, then divide states('sensor.temperature') by that.
... but what if I want it divided by 10 and then rounded to 2 decimal places... how would I do that?
BODMAS, or whatever they call it these days
Aka, use brackets
{{ (states('sensor.temperature') | float / 10) | round(2) }}
Ahh... I had tried
{{ states('sensor.temperature') | ( float / 10) | round(2) }}
But that did not work...
Thank you @arctic sorrel !
PEMDAS
Hey everyone! I have an occupancy sensor (sensor.test_occ) that reports true for occupied, and false for not occupied. I would like to show Occupied or Unoccupied in the card on Lovelace, but I cannot for the life of me figure out how to get it to work. I've seen in here things about a "Template Sensor" but I am not sure how to create one of those.
I've tried putting this into the lovelace card, but I just get Entity Not Available
type: sensor
entity: sensor.test_occ
{% if is_state('sensor.test_occ', 'true') %}
Occupied
{% else %}
Unoccupied
{% endif %}
@open belfry unless you are using custom lovelace component, that code above wonβt work. Jinja is backend, and lovelace is front end.
Ah. Ok. So how do I do this then?
You have two choices. 1. Create a custom sensor and use it as-is in Lovelace. 2. Use Lovelace custom component.
Where would I find documentation on either of those? I'm assuming if I create a custom sensor, I would use that instead of the current actual sensor, right?
That seems like the easiest way to go.
Although, I do also have the Lovelace Card Templater plugin installed through HACS.
Hell Yeah! I figured out Option #1. Now on to figure out Option #2 anyways. Thanks for the push in the right direction @queen meteor !
So with this, I get Entity not available: sensor.test_occ
type: 'custom:card-templater'
card:
type: entities
show_header_toggle: false
title: Sensors
entities:
- entity: sensor.test_occ
name_template: 'if is_state("sensor.test_occ", "true") "Occupied" else "Unoccupied"'
I'm sure it's a syntax error, but there aren't any examples that match what I'm doing, so I'm just grasping at straws.
Ok. I was wrong. There is an example, but it gives me the same result.
type: 'custom:card-templater'
card:
type: entities
show_header_toggle: false
title: Sensors
entities:
- entity: sensor.test_occ
state_template: >
{{ "Occupied" if states.sensor.test_occ.state == "true" else
"Unoccupied" }}
try:
state_template: >
{% if is_state('sensor.test_occ.state', 'true') %}
"Occupied"
{% else %}
"Unoccupied"
{% endif %}
I'm not an expert but maybe that will work. You can also test it in the Developer Tools -> Template page
Hi folks. I have a statistics sensor based on a counter sensor that I am using to track the average change from one report to the next. Is there a way to make the "Average Change" attribute the default, so I can see graphs, etc? Or should I simply make a template referencing it?
can I just add a static mdi icon to a template sensor without using icon_template?
Yes, you can!
I'm trying to trouble shoot a template from what it appears isn't getting executed for state_value_template. Anyone able to double check my sanity on how constants are used to map to the MQTT light object state template variable?
hi guys, someone have a group with a multiple enteties?
@pliant night show us your code. What are you trying to do?
@lethal basin groups are no longer used.
@queen meteor and what is the surregate for it?
groups for gui are gone, but else groups are still there
{
"name": "Master Bed Light Switch",
"command_topic": "homie/dimmer-3f91181/dimmer/dimmer/set",
"brightness_command_topic": "homie/dimmer-3f91181/dimmer/dimmer/set",
"brightness_state_topic": "homie/dimmer-3f91181/dimmer/dimmer",
"state_topic": "homie/dimmer-3f91181/dimmer/dimmer",
"state_value_template": "{{ 0 if (value | int) == 0 else 100 }}", #tried 0 or '0', 'false' to trigger off state
"brightness_scale": 100,
"on_command_type": "brightness",
"brightness_value_template": "{{ value | int }}",
"payload_on": 100,
"payload_off": 0
}
@lethal basin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/PjHP6prf8H/
so what are your intentions with this group?
and apear like that
its a pop up to show all enteties in group, because its a alarm clock and i need to pull very information for make a triger with that
are you sure the card is supposed to take a group and not a list of entities?
yes, its work arround 3 weeks but in one update didnt work anymore π¦
i was very happy with that group apear like in android
this... is not related to templates
@buoyant pine can be no?
you will say frontend, but in frontend no one can helps me i'm there for 2 days without a answer, can be a problem off hassio in general?
well #frontend-archived is probably the right spot for it. post it on the forum too if you want
share the card config in #frontend-archived too
because if i increase the windows view, i can view more item, basacally the hassio dont ajuste anymore the card to window
ok sorry @buoyant pine
Does anyone know if you can use a schema besides basic/default with MQTT Discovery? That would also solve my problem with state_value_template instead
The template code above works when I run it in template editor in the dev tools. I think i'm running into issues with state_value_template and matching to payload_on or payload_off
You shared links to@source code. Have you read the docs page for mqtt light?
for about a month π¦
lol
Are you sure it is not value_json? I see you use value.
2020-02-20 21:05:57 DEBUG (MainThread) [homeassistant.components.mqtt] Received message on homie/dimmer-273de91/dimmer/dimmer: b'0'
I thought I had the issue fixed after casting it to an INT
Ok.
so the issue appears the light state is always on
the dimmer aka brightness functions perfectly after using the brightness_value_template and casting that to INT
the payloads work as 0 and 100
and the part for state should work π "state_value_template": "{{ 0 if (value | int) == 0 else 100 }}"
i used the brightness scale to 100 option?
Are you testing In code or using services tab?
What do you have in home assistant config?
mqtt:
broker: "X.X.X.X"
discovery: true
discovery_prefix: homeassistant
homeassistant/light/dimmer-3f91181/config
i've noticed i'm one of very few using JSON dic loading from MQTT
but to help validate someone elses questions if I manually setup the config in the YAML file I can get it to work only using schema: template
light:
- platform: mqtt
name: Master Bed Light Switch
schema: template
state_topic: "homie/dimmer-3f91181/dimmer/dimmer"
command_topic: "homie/dimmer-3f91181/dimmer/dimmer/set"
state_template: "{{ 'off' if value == '0' else 'on' }}"
command_on_template: "{{ ((value | int / 255 * 100) | round(0)) if value is defined else 255 }}"
command_off_template: "0"
brightness_template: "{{ ((value | int) / 100 * 255) | round(0) }}"
retain: true
that config works since i'm able to use the command on and off and the state_template works
Whatβs not working then? Iβm confused. Code looks correct
so i'm using a bridge for my home automation and it automaticly removes and adds devices and publishes them to MQTT server
so I can't use YAML configs unless i write some "interesting" config editor and restart HASS on device changes π
what I fear is this discovery is using the basic schema parser and doesn't allow for schema: template
so long story recap, if I can get MQTT discovery to work with schema: template OR get the state_value_template to work like state_template
oh.... its possible thats a document bug and state_value_template is the same as state_template....?
does have both of them but for different schemas i'm not sure why π¦
sorry about mess of details!
i'm convinced something is off since testing the state_value_template: "0" or the false and off and the state still stays set to true even when brightness is 0
but I didn't want bug the devs if is just a weird behavior
Sorry. Best I can suggest is try sending different values and see if that makes any difference. I havenβt used it. The template code looks correct.
you might want to check the messages on the MQTT via separate MQTT client and the see whether the values are published first. Unless of course you have already done that π
@rare panther ya the messages look good @queen meteor I'm gonna create a dummy object that doesn't really exist and just push some test values without a dimmer. I fear this isn't template related Thanks for the help
Can someone help me fix this?
- platform: template sensors: dmi_pond_smart_socket_load: friendly_name: "Pond Smart Socket Load Power" unit_of_measurement: 'kWh' value_template: > {% if is_state("switch.smart_socket_pond", "on") %} state_attr("switch.smart_socket_pond", "load_power" | float / 1000 {% else %} 0.0 {% endif %}
I get a string as a result of first statement evaluation, how can i properly write it to get the attribute value of another entity and return a float there? Probably second part will need to be rewritten to.
ouch, seems like there was a missing bracket after 'load_power'
nnvm π
@upbeat basin just about to say that lol
π
Can anyone help me with the rest sensor? Looks like .106 broke the one I had earlier.
here's the response that I get from my CURL command <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfoResponse xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"><SerialNumber>5C-AA-AA-31-EA-80:1</SerialNumber><SoftwareVersion>54.2-72160</SoftwareVersion><DisplaySoftwareVersion>10.6.1</DisplaySoftwareVersion><HardwareVersion>1.14.1.11-1</HardwareVersion><IPAddress>192.168.2.253</IPAddress><MACAddress>5C:AA:AA:31:EA:80</MACAddress><CopyrightInfo>Β© 2003-2019, Sonos, Inc. All rights reserved.</CopyrightInfo><ExtraInfo></ExtraInfo><HTAudioIn>21</HTAudioIn><Flags>0</Flags></u:GetZoneInfoResponse></s:Body></s:Envelope>
I want to extract the value between the tags <HTAudioIn>21</HTAudioIn>, i.e., 21
https://github.com/arsaboo/homeassistant-config/blob/master/sensor.yaml#L273 used to work until .105
@fast vigil what is it doing?
extracting the value in HTAudioIn, which corresponds to the audio codec that is currently beingplayed
{'0': 'No SPDIF input connected', '2': 'Stereo', '7': 'Dolby 2.0', '18': 'Dolby 5.1', '20': 'Pause Burst', '21': 'Paused', '22': 'Silence'}
Isnt this because of the Sonos being changed?
with admin
@fast vigil is the other one working at 282?
What does it return? that line with SPDIF?
no, that is the mapping
so 21 corresponds to Paused
right now nothing is playing on Sonos
so the status is paused
1 sec, i'll try this on my sonos
here's the curl command that you can try curl --header 'SOAPACTION: "urn:schemas-upnp-org:service:DeviceProperties:1#GetZoneInfo"' --data '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfo xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"></u:GetZoneInfo></s:Body></s:Envelope>' --request POST --header 'Content-Type: text/xml; charset="utf-8"' 'http://192.168.2.253:1400/DeviceProperties/Control' if you want to try it outside HA
Doesnt work on my sonos
But what is the response you get on that?
thats the big one there
yes, just use the curl command
and you should see <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfoResponse xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"><SerialNumber>5C-AA-AA-31-EA-80:1</SerialNumber><SoftwareVersion>54.2-72160</SoftwareVersion><DisplaySoftwareVersion>10.6.1</DisplaySoftwareVersion><HardwareVersion>1.14.1.11-1</HardwareVersion><IPAddress>192.168.2.253</IPAddress><MACAddress>5C:AA:AA:31:EA:80</MACAddress><CopyrightInfo>:copyright: 2003-2019, Sonos, Inc. All rights reserved.</CopyrightInfo><ExtraInfo></ExtraInfo><HTAudioIn>21</HTAudioIn><Flags>0</Flags></u:GetZoneInfoResponse></s:Body></s:Envelope>
as the output
I cant, my sonos doesnt have that feature for some reason
So i am figuring out in Janja2, if we can make a list on a qualifier
and then just pick the list item
i have neither
yeah, I thought so
I see
but, its kinda stupid because it returns XML
and it doesnt get to be placed in json properly
well, it is structured well
and can be converted to json
that is what I thought the PR was supposed to do
Thats what i read from it
So the thing is, if we just think its a string instead of structured thing
we filter on that
but it isnt json atm
earlier it would just return the string and then we could parse
Yes
not sure what changed in the last PR
I cannot even see what is the value that is being returned
as the value is more than 255 chars
And if you change your payload?
to what?
To request less info
But i guess thats no option
I think we just found out why its called beta
Cant help you D: Sorry buddy
Let me know if you figured it out
sure thing
@fast vigil that regex seem to be working okay
yeah, the problem is not with the regex
the problem is with the updated rest sensor
I don't think it is returning the string that it was returning earlier
I see... what is it returning now?
sorry - just checking messages, lazy to scroll back
hmm...
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfoResponse xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"><SerialNumber>5C-AA-AA-31-EA-80:1</SerialNumber><SoftwareVersion>54.2-72160</SoftwareVersion><DisplaySoftwareVersion>10.6.1</DisplaySoftwareVersion><HardwareVersion>1.14.1.11-1</HardwareVersion><IPAddress>192.168.2.253</IPAddress><MACAddress>5C:AA:AA:31:EA:80</MACAddress><CopyrightInfo>:copyright: 2003-2019, Sonos, Inc. All rights reserved.</CopyrightInfo><ExtraInfo></ExtraInfo><HTAudioIn>21</HTAudioIn><Flags>0</Flags></u:GetZoneInfoResponse></s:Body></s:Envelope>
that is the same output
that has not changed
hmm...
but I in the last PR, it automatically converted xml to json or something like that
If I just use ```yaml
- platform: rest
method: POST
resource: http://192.168.2.253:1400/DeviceProperties/Control
name: Sonos Stereo
headers:
SOAPACTION: "urn:schemas-upnp-org:service:DeviceProperties:1#GetZoneInfo"
Content-Type: text/xml; charset="utf-8"
payload: '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfo xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"></u:GetZoneInfo></s:Body></s:Envelope>'
value_template: '{{ value }}'```
I get bash Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 434, in _async_add_entity await entity.async_update_ha_state() File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 284, in async_update_ha_state self._async_write_ha_state() File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 417, in _async_write_ha_state self.entity_id, state, attr, self.force_update, self._context File "/usr/src/homeassistant/homeassistant/core.py", line 981, in async_set state = State(entity_id, new_state, attributes, last_changed, None, context) File "/usr/src/homeassistant/homeassistant/core.py", line 725, in __init__ f"Invalid state encountered for entity id: {entity_id}. " homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity id: sensor.sonos_stereo. State max length is 255 characters.
ah! I see...
then instead of using rest sensor, you might just use command line sensor
I mean using curl command as a shell command
I know, it is crazy. hopefully - you can redirect output to a file or mqtt
now I wonder why that PR was merged....
I am sure I am missing something
if not, there will be some unhappy users soon
What if you put those attributes in json_attributes?
yeah, I tried that too
- platform: rest
method: POST
resource: http://192.168.2.253:1400/DeviceProperties/Control
name: Sonos Stereo
headers:
SOAPACTION: "urn:schemas-upnp-org:service:DeviceProperties:1#GetZoneInfo"
Content-Type: text/xml; charset="utf-8"
payload: '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfo xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"></u:GetZoneInfo></s:Body></s:Envelope>'
json_attributes:
- "HTAudioIn"
json_attributes_path: '$.["Body"]["GetZoneInfoResponse"]'
value_template: '{{ value_json["Body"] }}'```
doesn't work either
I am sure some of the values there are not right
but cannot figure out
it won't work as it is failing to get the value itself as it breaks as soon as it hits 255 character limit
no, that should work. The 255 chars limit has been there for a long time, but it only applies to the state value
intermediate outcomes can be any length
that 255 char limit is done outside - it is not in the PR itself.... the mock unit test doesn't really testwith output with more than 255 chars. that's why the PR went through
yeah, but that is only for the state. Also, it was working before and nothing in the PR is about 255 chars
that's what I am saying.... earlier it was just xml, now they use xml2dict library, which creates a dictionary that is more than 255 - that's where it is breaking
the xml may be well within 255 earlier. the new PR added xml2dict, which bloats the string length to more than 255
I see
the test cases passed as the test data is small
I believe you mean two schfifty-five
- platform: rest
method: POST
resource: http://192.168.2.253:1400/DeviceProperties/Control
name: Sonos Stereo
headers:
SOAPACTION: "urn:schemas-upnp-org:service:DeviceProperties:1#GetZoneInfo"
Content-Type: text/xml; charset="utf-8"
payload: '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetZoneInfo xmlns:u="urn:schemas-upnp-org:service:DeviceProperties:1"></u:GetZoneInfo></s:Body></s:Envelope>'
json_attributes:
- "HTAudioIn"
json_attributes_path: '$.["Body"]["GetZoneInfoResponse"]'
value_template: '{{ OK }}'
does not give the 255 chars error.
I get JSON result was not a dictionary or list with 0th element a dictionary, so the issue is how it is parsed
I think adding json_attributes_path narrows down the attribute set - which probably reduces the size down to below 255 - but in this case, that filter is causing the json dictionary to be empty - that means no matching json with that attribute found.
maybe change from HTAudioIn to lower case json attribute? when it converts to dictionary, may be json is converting them to lower case keys
something like htaudioin?
ok...let me do that
I feel the issue is also somewhere in the other two fields
json_attributes:
- "htaudioin"
json_attributes_path: '$.response["Body"]["GetZoneInfoResponse"]'
value_template: '{{ value_json.response["Body"]["GetZoneInfoResponse"] }}'```
everything gives JSON result was not a dictionary or list with 0th element a dictionary
let me try lower case everywhere
not sure the lowercase thing works, but worth a try. If you see the actual json, it would make it easy to set the path and access attributes
I know...it does not give the json even with logger set to debug
how is someone supposed to debug this
if you copy the sensor code to local custom_components, you can add additional debug statements
I added it
but even that is not given the value....may be I did not add it in teh right place
right after line #208, add print (value)
you want to do it after it converted to json
ok added there as well
otherwise woul'd see plan xml
but it did not debug even the plain xml
your logger level set to debug?
yes homeassistant.components.rest.sensor: debug
no - this would become a custom sensor - you need to add one for custom sensor