#templates-archived
1 messages Β· Page 123 of 1
And you are going to need to do some template magic to parse out only the hour
something like this, but you are going to need to play with it in the template editor
{{ (now().hour) == as_timestamp(states.sensor.your_sensor.attributes['your_attribute']) | timestamp_custom("%H") }}
or this may work also {{ (now().hour) == (state_attr('sensor.your_sensor', 'your_attribute')) }}
Have you checked the Jinja docs? https://jinja.palletsprojects.com/en/2.11.x/templates/#list-of-builtin-tests
not yet - searched the forums but nothing definite I could find - checking
that helped, thanks
is it possible to create a switch that toggles one script as the On and another as the Off?
Sure. That just sounds like a template switch: https://www.home-assistant.io/integrations/switch.template/
(which is an #integrations-archived )
The only bit that requires a template is the value_template so that it knows when it's on/off.
ah perfect, thanks mono
actually, how do you know a script is on/off? would it be by seeing if any of the entities that the switch turned on are in the on state?
A script isn't on/off. You'll need to track the switch state with an input boolean or something.
scripts are only 'on' if there's a delay in the script. Otherwise you'd need to create a boolean that stores your on/off state
Snap
Turn on = run script A, where script A sets a boolean to 'on'.
Turn off = run script B, where script B sets the same boolean to 'off'.
Template value of the template switch is the state of the boolean.
hmmm for some reason the switch is not calling the script.
all_ac_thermostat:
friendly_name: All AC Thermostat
value_template: "{{ is_state('input_boolean.all_ac_thermostat_script_on', 'on') }}"
turn_on:
service: switch.turn_on
target:
entity_id: script.all_ac_thermostat_on
turn_off:
service: switch.turn_off
target:
entity_id: script.all_ac_thermostat_off```
oh wait, switch.turn_on and off should be script.toggle or something
no
your services need to be script.turn_on because you're turning on a script
but you don't even need that because scripts are services
all_ac_thermostat:
friendly_name: All AC Thermostat
value_template: "{{ is_state('input_boolean.all_ac_thermostat_script_on', 'on') }}"
turn_on:
service: script.all_ac_thermostat_on
turn_off:
service: script.all_ac_thermostat_off
alright, now it works, however it won't turn off... thinking that has something to do with the script though
on script turns the ac on, and turns input_boolean to on, but doesn't shut it off when clicked again
nor does it change the state of the button in the UI to on
but calling the script manually in
works....
make sure you're using the correct input boolean then
your template is correct, so the only option is that you ahve a typo
also, turning on your input_boolean should be the first service in the turn on script. Turning off should be the last service in the script turn off
Ah Iβll give that a go
Ugh still no good. I would have thought it was my button in the UI but surely I canβt have stuffed that
are you sure you have the correct input boolean name in the template?
No... looks like when I changed the name of it, it didnβt carry over π
Something so simple, thanks for steering me to look at exactly what was wrong (again)
Hey everyone.
So how would I go about changing the state text shown when a binary sensor is on/off?
For example this binary sensor binary_sensor.octoprint_printing says On and Off, but I would like to change it to Yes when On and No when Off.
you use templates to make a custom state based on a existing entities state, yes
And how would I do that?
https://community.home-assistant.io/t/change-device-status-from-home-to-online/3740/2
you replace Online with Yes and Offline with No. and also adjust to your sensor entity
Many thanks
Did you purposely find the oldest post possible?
And on the stone tablet was written this template
I can't believe it still works
I mean, I can... just 5 years ago was ancient times
it works π and I was on mobile ποΈπ€ and lazy
How come my light.turn_on action fails with this option: brightness_pct: {{ states('input_number.wakeup_brightness')|float }}? Error message: Error while executing automation automation.wakeup: expected float for dictionary value @ data['brightness_pct']
What does it return when you enter the template in the template checker in developer tools?
25
Okay, I was wondering if it might return an error (maybe because of a littly typo or something). But in this case I also do not know why it doesn't work
What is the complete service call in which the template is used?
Because you have not put quotes around a single line template.
brightness_pct: "{{ states('input_number.wakeup_brightness')|float }}"
there you go π
quite picky this one π
would love for it to understand brightness_pct: input_number.wakeup_brightness
Ah, of course.. π Shouldn't have missed that. But it's still early morning here π
simple question here - I have a sensor and I want it to be in different units
sensor.octoprint_time_elapsed shows time in seconds, let's say I want minutes
do I need to create a derivative sensor? How do I do this?
I can do this in the template editor and it works: {{states.sensor.octoprint_time_elapsed.state |float / 60 }}
But how do I integrate it back into my charts or whatever?
You use a new sensor
I think I'm getting the concept
- platform: template
sensors:
octoprint_time_elapset_min:
friendly_name: "Octoprint Time Elapsed (min)"
value_template: >-
{{states.sensor.octoprint_time_elapsed.state |float / 60 }}
at least the config check passed lol
Looks ok to me. You may want to add a unit_of_measurement (like βmins) if you want a graph in the history.
Got it - thanks again for your help. I'm feel a little slow getting started at this.
No worries, youβre doing great
I think that pretty much answers my noob questions. The next steps are to make some control dashboards. Like you said - I'll probably need to write some scripts to do this.
It's really neat to pipe everything into the same "hub" and have it all right there. I didn't consider my house that "connected" before until I started setting all this up.
is there a way to get the last time stamp of a specific state ?
Replace domain.object_id with your entity_id and state with your required state in this
{{ if domain.object_id = 'state' as_timestamp(states.domain.object_id.last_changed) else states('domain.object_id') }}
Actually... that else case is not correct. If you wanted the timestamp of the state on it will return a timestamp or off
Hmmm. Tricky...
That else case needs to be the domain.object_id of the template sensor itself.
yeah it didnt work
It would help if you showed what you tried, the full sensor definition.
{{ if sensor.csw4 = 'single' as_timestamp(states.sensor.csw4.last_changed) else states('sensor.csw4') }}
the sensors states are Single Double and LONG its a a button
Yeah, thatβs not right
Create this template sensor https://paste.ubuntu.com/p/JrYS2VN9NR/
should it be states.sensor.csw4.state ? isntead of sensor.csw4
Yes, just fixed that: https://paste.ubuntu.com/p/Z3k4DgdXwb/
emplateSyntaxError: expected token 'end of print statement', got 'states'
i donno about this part is doesnt seem right
states('sensor.single_timestamp_sensor')```
That's the state of the template sensor itself, this will be returned if the state is not 'single' i.e. no change to the sensor. It returns itself.
so i have to create a template sensor ?
Yes, I can't think of another way to not change the state if not 'single'.
I have an Aqara Button that exposes - among many things - this: sensor.pasha_button_click
If I select sensor.pasha_button_click in
, & click the button, this will show up: https://imgur.com/a/ZlmZNXr
Otherwise it's this https://imgur.com/a/rpJ9HE8
According to the docs, I think I'm supposed to use the action attribute. https://www.zigbee2mqtt.io/devices/WXKG11LM.html#deprecated-click-event
I assumed that if I did everything right, after pressing the button, having this in my template would Result in "True"
"{{ state_attr('sensor.pasha_button_click', 'click_action') == 'single' }}"
But when I click the button it still says "false"
Should I be using a different attribute?
How are you testing it?
by clicking the button
How are you checking the template? π
oh uhh in
: template i'm putting that line in the tempalte editor
It's probably happening too quickly for you to even see it there. A button is a momentary event.
I'd suggest making a template sensor with your template, then seeing what the history for that sensor says after the button is pressed.
Honestly, though... you probably don't even need a template for that. I use the same button and just have a state trigger:
- to: 'single'
entity_id: sensor.0x00158d000401926f_click
platform: state```
are you serious?
just to be clear, for me, in
I don't get anything in the state field, when i click the button; only in attributes
Tinkerer thought maybe it was in the way that I set it up, that it does only in attributes
I don't know how your sensor was created... I'm using Z2M too π€·ββοΈ
You don't have any that end with _click?
Hey,
anyone an idea how to show the cryptocurrency value of Holo (HOT) EUR ?
in a sensor
yea i do. It's sensor.pasha_button_click https://imgur.com/a/ZlmZNXr
If go that route, how does this look?
sensor:
platform: template
value_template: "{{ state_attr('sensor.pasha_button_action', 'click_action') == 'single' }}"
Hi, how can I round all entities of sensor with type power?
- name: "EG Gast Licht Decke Leistungswert"
state_address: "1/7/7"
type: power
sync_state: false
value_template: "{{ (states('sensor.eg_gast_licht_decke_leistungswert') | float ) | round(1) }}"
This is not working and only for one entity
I donβt think you can. You have to define each one
I don't see click_action in your attributes...
To check what attributes actually exist, go to the Dev Tools > States
huh, it's the craziest thing...click _action is not there. But, when i press the button, it pops up!
If i wasn't seeing it I wouldn't believe it. Is that normal?
So in
, if i select pasha_button_click this is what I see https://imgur.com/a/rpJ9HE8
And when i click the button, the field next to click changes to "single" *and a new action attribute pops up, also with "single" https://imgur.com/a/ZlmZNXr
Ah I re-read what you wrote. I just saw assumed that click_action was the attribute I was looking for, but I am actually not confident about that anymore. If you don't see click_action in my attributes, what do you see; click_type ? Something else?
It doesn't matter what I see, only what attributes your sensors have
Don't guess. Check.
Here's what I see in
attributes
- battery: 100
- click:
- linkquality: 84
- voltage: 3075
- friendly_name: pasha_button_click
- icon: mdi:toggle-switch
And here's what I see in
(for about .01 seconds) when I click the button:
- action: single
- battery: 100
- click: single
- linkquality: 84
- voltage: 3075
- friendly_name: pasha_button_click
- icon: mdi:toggle-switch
So you're after click π
It's also going to be the state for that brief time too, which is why templates are unnecessary and you could just be copying my example from earlier.
ohhh. so instead of click_action just plain old click ?
like this?
value_template: "{{ state_attr('sensor.pasha_button_action', 'click') == 'single' }}"
No no no no no
There is zero need for a template where you're just after a simple state/attribute trigger.
Okay...I hear you, I swear to god I am listening, and I'm really sorry if this is retarded, but I thought you were saying that example would only work if I had something in
states, instead of attributes ?
It will work for an attribute too.
oh. sweet. Im an idiot
Using attributes used to need a template. It changed quite a while back.
You might still see examples that use templates but you shouldn't trust old examples - always check the docs.
Relatively recent in HA terms.
Was it WTH month?
Gotcha. I was probably checking the wrong docs, i searched attributes+automations
and was def looking at some forum posts from 2019
ahh now i think i found it https://www.home-assistant.io/docs/automation/trigger/#state-trigger
Thanks for all your help, mono!!!
@final abyss posted a code wall, it is moved here --> https://paste.ubuntu.com/p/jBPpFM9HpS/
Any suggestions on tiding up this nice template from the past βοΈ ?
Padawans posting code walls? Shame on you!
Can somebody please help π¦ I cannot figure out whats going wrong here
it simply just don't work
- platform: mqtt
name: "Nick is home"
state_topic: "ai/Default/motion/"
value_template: >
{% set ns = namespace(found = false) %}
{% for match in camera_json.predictions %}
{% if match.label == 'Nick' and match.confidence >=10 %}
{% set ns.found = true %}
true
{% endif %}
{% endfor %}
Looks pretty tidy already. You could maybe assign the state to a variable just so you're not repeating a long ugly string but the functionality looks fine, sjabby.
Its barking at me after the update:
2021-04-07 20:58:15 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'mappingproxy object' has no attribute 'game' when rendering '{% if states.sensor.steam_7
the attribute only exists when a game is actually played, otherwise the attribute is not present
Then you'll need to chain your accessors, I guess...
{% if states.sensor.steam_76x50.attributes and states.sensor.steam_76x50.attributes.game -%}
It shouldn't be going any further in your nested template if the first check fails.
Same π¦
value_template: >-
{% set consumption = states('sensor.consumer1') + states('sensor.consumer2') %}
{% set production = states('sensor.prod1') + states('sensor.prod2') %}
{{ consumption + production }}
How can i force to not concatenate the values but add them together instead?
or where do i need to add | float
Add the filter after everything that would return a string.
{{ (states('sensor.demo_battery') |float) + (states('sensor.demo_grid') |float) }}
?
In your case, that's each of the 4 state functions.
k thy
{% set game = state_attr('sensor.steam_76x50', 'game') | lower %}
{{ 'game' if game and game not in ['none','unknown'] else 'none' }}
thx!
Just upgraded to 2021.4.0 and get 3 occurances of
WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'action' when rendering '{{ value_json.action }}'
in my logs at start up and then again at random times after that. None of my yaml files have the string value_json.action in them and I've tried removed every yaml file that contains the string "template" but I'm still seeing the warnings.
any pointers on where else to look.
Are you using zigbee2mqtt?
@sly seal You are a god ... yes I am ... many thanks
what's the most straightforward way to reduce on all states for a given device class? for example, I want to check whether any device_class: moisture sensors have an on state
hmm there's gotta be a more elegant approach. especially when it comes to outputting a different string if none are on
{% for state in states.binary_sensor %}
{%- if state.attributes.device_class == 'moisture' and
state.state == 'on' %}{{ state.name }}
{%- endif -%}
{%- endfor %}
Is there a simple guide to templates as I cannot find in the documentation how to do really simple operations. My SNMP request returns a voltage as an integer as 2380. This is 238.0 volts. I tried:
value_template: '{{ (val | int /10 ) }}'
It gave an error and will not read. I tried val | float / 10 | round(0) still no luck
If I do not use value_template at all it happily returns 2380
you're rounding 10 in the last one
The first one is almost right except val should be value
Perfect! That worked, thanks
I have an MQTT-device which reports a number of json-values. What is it called if I want to create a custom sensor which has all of the json values integrated? I don't want separate sensors for each json-value from the device if you get what I mean.
How would one go about retrieving attributes from a sensor (online weather in this case) that are not "top level" attributes? They are under the attribute "forecast", and then listed per day.
Found it on the forum!
I have this code:
{{ as_timestamp(now()) | timestamp_custom('%d''-''%m''-''%Y') -}}
which gives: 08-04-2021
now i would like to have the date before today in here. so day -1
could some one tell me how i do this?
Also, you don't need the ''...
{{ as_timestamp(now()) | timestamp_custom('%d-%m-%Y') }}
and for the previous day... {{ as_timestamp(now()-timedelta(days=1)) | timestamp_custom('%d-%m-%Y') }}"
thanks for all the info
I have a hopefully easy question to answer. How do you access the first element on an array? {{ state_attr('weather.kvay_hourly', 'forecast') }} does return the full array, but {{ state_attr('weather.kvay_hourly', 'forecast[0]') }} return none just for reference I am trying to get the value for weather.kvay_hourly.forecast[0].precipitation_probability
You need to access the array element after you've retrieved it. Your second example is trying to get an attribute with the name 'forecast[0]' which doesn't exist.
Something like this should work:
state_attr('weather.kvay_hourly', 'forecast')[0] }}
Sure... but that's more a topic for #automations-archived
not automation... but scripts....
so templating an if then else
in the scripts
make one call instead of another
Read the topic in #automations-archived
Hi all, quick Q, I seem to be not grasping what I know is a simple solution here. I need to present the following string in timestamp_local, but can't get the syntax right.
{{ now().timestamp() + state_attr('sensor.travel_time_home_to_hospital', 'value') }}. I thought it would be as simple as adding | timestamp_local at the end, but that obv just throws me that float and str is unnsuported operand for +
You need to use timedeltas to manipulate dates. Scroll up a little, there was a discussion today about it.
It happens
thanks! I'll give it a try
I was able to get an LED light to work using the IR remote function provided by the Broadlink integration, and made a light_template so it could be an entity. The light has options for various colors as well as color temperatures of white. However, it's all based on buttons from the IR remote, learned by the Broadlink integration. Now I'm trying to fine tune this, since the various light_template options don't seem to fit well. Not sure if I should just set the light_template to turn on and off β and then use automations to set up the various white or RGB colors, modes, etc. All of those are individual buttons on the IR remote.
I've now done something similar for a fan_template. The remote for that has 3 buttons, one for power, one for speed, and one for a built-in timer. The fan_template doesn't seem to map well to this.
If the ir remote you are talking about is for the light, you are prob going to have to learn all the commands into the broadlink and then call each command in an automation.
@unique elm posted a code wall, it is moved here --> https://paste.ubuntu.com/p/4ynSZ4bwgh/
Can I use icon templates with snmp sensors? My code example is above (abbreviated)
I am also trying to structure the code correctly in yaml, hopefully you can see what I am trying to achieve
@unique elm posted a code wall, it is moved here --> https://paste.ubuntu.com/p/r5Q28Nwdvb/
...and I will use pastebin in the future...sorry
Howdy π
I watched the release party video on youtube and have a question about trigger based template entities - I don't fully gasp it just yet.
Is this to solve the problem of updating template sensors based on certain triggers?
What I've got in mind is to create a daily average, mean, min and max temperature template sensors, and while my template seems to be working now, updating it is actually the next step - so ideally any change in metno's hourly values would kick an update (e.g. recalculate as prediction gets closer to reality)
or I'm completely in the dark and template triggers are for something completely different? like for the opposite of that?
(which can be as trigger platform template is something that's been around for a while)
@pseudo badger posted a code wall, it is moved here --> https://paste.ubuntu.com/p/fsXVQgVC3g/
@pale python posted a code wall, it is moved here --> https://paste.ubuntu.com/p/hSbtkY7cVM/
If a template sensors history isn't displayed as a graph, does it mean it's not a number?
Is there an easy way to access historical information on weather?
How much rain has fallen today is what I'm after as a template sensor
(or snow)
sensor.openweathermap_rain has historical info on this, haven't seen anything for met.no
but over 90% relative humidity by external sensors is a positive sign
It all depends on the data provided by the integration. Anything else would just be guessing.
There's nothing stopping you using multiple weather integrations and picking the data you want from each.
that's close to what I'm trying to do, yeah: iterate through all the weather state_attr and use one or combine in case they are not "none" or "unavailable" or anything weird - survives anything lol
however, how can I access historical data?
I see the entity showing history back 8 hours or so, is that available for templates (w/o configuring a historical data/stats integration)?
Templates can only change how current data is represented. You'll need an integration for that.
guys
I have this automation
if the received MQTT message does not contain whitetemp
I see this error in logs
Error evaluating condition in 'Set HA WhiteTemp': In 'condition': In 'template' condition: UndefinedError: 'dict object' has no attribute 'payload_json'
how can I say to the automation to skip everything if the json does not contain the "whitetemp"?
my read of that is: historical data (stuff I see in the UI when I click history for a sensor) is not available for templates, unless I get an integation in place that kind of stores that and makes it avail
that sound about right?
@ivory delta Got it, thanks
Trigger based template sensors add a logical way to update a template sensor. Say you donβt need something like a birthday sensor to update every 15 minutes on a time pattern, it only needs to be updated once, you can use a trigger to update the template based sensor at say 1:00 am and then leave it alone. Itβs just a finer grain of control
Maybe history stats are what you are after π€·πΌββοΈ
https://www.home-assistant.io/integrations/history_stats/
Seeing this in the logs. What am I doing wrong??
2021-04-09 17:11:03 WARNING (MainThread) [homeassistant.components.template.trigger] Error initializing 'template' trigger for 'SYT - Two hours before': TypeError: can only concatenate str (not "datetime.timedelta") to str
2021-04-09 17:11:03 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template("{% set cl = strptime(states('sensor.jewish_calendar_upcoming_candle_lighting'), '%Y-%m-%d %H:%M:%S%z') + timedelta(hours=-2) %}
{% set now = strptime(states('sensor.jewish_calendar_now'), '%Y-%m-%d %H:%M:%S%z') %}
{{ cl == now}}")
What's the value of sensor.jewish_calendar_upcoming_candle_lighting right now?
2021-04-09 15:22:00+00:00
Seems okay to me. I just did this to fake the sensor, since I don't have it:
{% set datetime = '2021-04-09 15:22:00+00:00' %}
{% set cl = strptime(datetime, '%Y-%m-%d %H:%M:%S%z') + timedelta(hours=-2) %}
{{ cl }}```
The last line outputs a time two hours before datetime.
Do you see the problem all the time or does the template sometimes work?
so it's for the scenario when I deliberately don't want a template sensor to automatically update, but needs a trigger in order to do so. E.g. I can get my hourly weather data and force it to update only once every Tuesday, or a webhook, or a state change, or whatever else the trigger platform provides
I've tried a million things, never got this one to work
That wasn't the question
Try your template in the Dev Tools, see what it says there. It works for me π€·ββοΈ
depends on whwere the timestamp is coming from
Sometimes they have a T in the format
2021-04-09 15:22:00+00:00 vs 2021-04-09T15:22:00+00:00
gotta account for that in the format
I was using their value from their state. The reason I asked if it happens all the time is in case the state isn't always a datetime in the same format they expect.
Mono you would be so proud of me. I managed to use regex all by myself to extract a value from a text sensor π₯²
RegEx is amazing once you appreciate what it can to. It can often replace a lot of code.
I'm sure there are many similar sites but I love regex101 as a playground for testing them.
You can stick a bunch of test strings in the main panel and it'll show you which of them are matched by your pattern, as well as explain how your pattern works.
I have that bookmarked from last time we were discussing regex π
it can also be slow as fuck
Yup π RegEx DoS attacks...
Is there any easy way to display the last known state of a sensor when it becomes unavailable?
you can make an automation that triggers off it changing to unavailable and display the from state
actually, you can use the new template integration
if you want to store it in a sensor
otherwise just make a notification automation
Thank you I'll try that!
Can I use icon templates with snmp sensors? My code example is pasted at https://pastebin.com/QJKCiuum
No, the SNMP does not have an icon_template option. See the docs for available options https://www.home-assistant.io/integrations/snmp/#sensor. However for what you want to do just add device_class: battery using customize. https://www.home-assistant.io/docs/configuration/customizing-devices/
This will give you an icon that changes with battery %
Has anyone seen state_attr return null instead of the correct value with 2021.4.x?
I'm using the template {{ state_attr('trigger.event.data', 'actions') }} and it returns null despite actions being defined.
I doubt thatβs an attribute
States have attributes. You can just use trigger.event.data.actions
I've added actions to my event data. And it works if I used it directly as you suggest, but if I wan't to test if it is there i.e. {{ state_attr('trigger.event.data', 'actions') != None }} I get False.
I figured out a solution: {{ trigger.event.data.actions != null }}
I'd like some help to think straight. I have a moisture sensor that shows 0,35 when the plant is well moistured, and 0,5 when it really needs more water.
I want to create a ninverted sensor that shows 0 when the actual value is 0,5 and 1 when the actual value is 0,35. And linear values in between.
Something like the "water need" is between 0 % and 100%. I'm stuck in a mind loop I can't get out of so all help is appreciated. Suggestions?
water_need = -6.667 * sensor_value + 3.333
Thanks! I just got to the same conclusion in Excel. Needed a break to see things clearly.
hey everyone, trying to get a list of entity ids for binary sensors that have a certain attribute as true
using:
however, not all binary sensors have this attribute, so I'm getting a [homeassistant.helpers.template] Template variable warning: 'mappingproxy object' has no attribute 'attr' when rendering
any ideas how to resolve?
What is the equivalent of javascripts math.exp() in home assistants templating?
Is it possible to if-else-Template a service call in a automation action section?
Yes
e ** x is e^x in jinja.
How would one do such a thing? I tried this and it doesn't work: https://gist.github.com/PiratWeber/9a7e100f400d662fb55405525bff5130#file-zigbee-yaml-L2
It's probably just a small stupid mistake on my side
Sorry. Github is blocked where I am at the moment.
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
Here you go: https://paste.ubuntu.com/p/HMBzbZHTRd/
Stand by... it also takes ages for pages to load.
No worries! I am not running away and it's not urgent π
Indentation is a bit off (should be 2 spaces not 3) but hopefully you get the idea
Target should be inline with service.
Thanks. Gonna try it out!
If somebody reads this somehow and wonders why it does not work: Inputs in Blueprint must be exposed as variables before they can be used in templates!
Ok, I've got this in the message for a cloud TTS action in a script but it's only ever saying "unknown" even though the entity is set.
{{ states('input_select.test') }}
It is evaluating to a state but, so not sure what I've got wrong
OK, I have been informed to place this here.
OK, this is likely in the wrong place so please correct me. I have had this error since updating to 2021.4.3 Logger: homeassistant.helpers.template
Source: helpers/template.py:1335
First occurred: 14:12:13 (9 occurrences)
Last logged: 14:19:05
Template variable warning: 'dict object' has no attribute 'led_indication' when rendering '{{ value_json.led_indication }}'
Template variable warning: dict object has no element Undefined when rendering '{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}'
[2:27 PM]
Thing is I don't knowingly have a helper and I don't have a fan. Please can someone tell me the best place to look to fix the issue. Running supervised on Ubuntu 20.04 dedicated machine with supervisor. Thanks
I don't have any intentional templates co this is confusing me
If you've added no templates of your own, check Dev Tools > Templates and see what's going on in there. If there are broken templates there, it'll tell you over on the right.
It's basically a playground to experiment with templates. The style of the templates in your error messages looks pretty similar to the test ones.
I am looking at it now and I see something to do with weather, it looks like an example with 'set my_test_json' in purple for example. I'm tempted to remove it but concerned it may have something to do with my weather intigration.
If it's in the Dev Tools screens, it's safe to edit, delete or otherwise fuck up. Like I said, it's a playground.
Thanks, deleted it to see if that makes a difference
I specified a template as {{ (states("input_number.low_value") | float + 4 | float ) }} and it works in the developer tools. But when I use it as a value in an automation trigger for numeric_value I receive the message: "Message malformed: expected float for dictionary value." Anyone an idea of what I should do to fix the template?
Unfortuantely I am still getting the error "Template variable warning: 'dict object' has no attribute 'led_indication' when rendering '{{ value_json.led_indication }}'"
Then something is using a template π€·ββοΈ
You can search your config for curly braces but it's up to you to find it.
OK, thanks. just looking for curly braces as narrowed the search down
That's a climate device for the second error, not a fan. Are you using MQTT? Do you have MQTT Discovery?
Template variable warning: 'break' is undefined when rendering '{%- set activepage = namespace() -%} {%- for entity in device_entities(haspdevice) -%} {%- if entity|regex_search("^number..*_activepage(?:\d+|)$") -%} {%- set activepage.entity=entity -%} {{ break }} {%- endif -%} {%- endfor -%} {% if states(activepage.entity)|lower == "none" %}-1{% else %}{{ states(activepage.entity) | int }}{% endif %}'
when trying to stream onvif camera
yeah, break is undefined yet you are trying to output it. Also, please format the code next time or share it on a codeshare site
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
what should i do to stream my camera?
The only climate device is a zigbee radiator thermosat, which I ahve been looking at I also have a couple of zigbee xiomi temperature sensors
ok, and how did you integrate it in HA?
it is zigbee2mqtt which is why I am thinking it could be that
right, but did you use discovery or did you manually add it
for MQTT
simple question
"I don't know" is a valid answer too π
I used discovery, when I installed zigbee2mqtt there is a automation to discover new devices
Ok, then write up an issue against zigbee2mqtt unless you manually configured this device in that platform
if you manually configured the discovery settings on that system, then you just need to update your templates there
im trying to set up an automation which would be triggered every time when a state of any entity with a name ending with _overcurrent suffix changes
is that even possible?
yep, use a state_changed event trigger and write a template condition that checks the entity_id supplied in the trigger object.
Can I template the initial value for input_text in configuration.yaml ?
I'm getting errors by configuration check
No
@mighty ledge thank you! you were clear π
Hey all, Sorry for my ignorance but I'm trying to modify the output of one of my sensors.
In the RAW configuration editor for a room I have:
- entities:
- entity: sensor.balcony_temperature
- entity: sensor.balcony_humidity
title: Balcony Sensors
type: entities
However the temperature is always 1.5 degrees C too high, so I'd like to subtract that value before output if possible.
Any help appreciated π
as mentioned earlier, you'll need to create a template sensor to adjust the value
that's why he sent you here, but you'll need to do some research
To be fair, I only said to come here for help with the template itself π
Thanks.
elementary template question π
{% if trigger.event.data.parameters.userId is not none %}
User Code {{ trigger.event.data.parameters.userId }}
{% endif %}
the user code text still gets included in the message even if trigger.event.data.parameters.userId doesn't exist
Hi. This might be a generic configuration question, but I can't find a more general channel, so asking here since it's for a template.
I get a DEPRECATED (seince 2021.3) warning on the value of my value_template in VSCode for the following. I'm still looking but can't see what's wrong yet. It works. Can anyone help me understand and fix it please?
cover:
- platform: mqtt
name: "Garage Door"
command_topic: "garadget/lionhousegaragedoor/command"
state_topic: "garadget/lionhousegaragedoor/status"
payload_open: "open"
payload_close: "close"
state_open: "open"
state_closed: "closed"
value_template: "{{ 'open' if 'open' in value_json.status else 'closed' }}"
EDIT: found it in https://www.home-assistant.io/blog/2021/03/03/release-20213/#breaking-changes - replace value_template with position_template.
Invalid config for [automation]: invalid template (TemplateAssertionError: no test named 'None') for dictionary value @ data['action'][0]['data_template']. Got None. (See ?, line ?).
there's clearly more to that automation than was posted π
action:
service: notify.ios
data_template:
title: Door Lock Notification
message: >
{{ trigger.event.data.event_label }}
{% if trigger.event.data.parameters.userId is not None %}
User Code {{ trigger.event.data.parameters.userId }}
{% endif %}
trigger is zwave_js_notification event
first, data_template:->data:, but that's not the problem
I would just do {% if trigger.event.data.parameters.userId %}
Is there somewhere more basic I can go to understand the basics of this language as none of this means a thing to me. The documentation doesn't help at all, as it doesn't explain the language, what it can do or how it's done. No one has ever explained the basics of what the fek is going on. A sensible list of commands would be nice, some sort of grounding would be a good start.... π
it's called "Jinja" and there's a ton of documentation on it
including this whole page: https://www.home-assistant.io/docs/configuration/templating/
other links are in the topic
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find the docs at https://www.home-assistant.io/docs/automation/templating/ - and don't forget rule #1! Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs
Ok, I'll take a look. The 'templating' page on the HA website doesn't really explain anything I'm afraid.
the one above?
Yes. Id doesn't explain the commands, the structure, memory, variables, arithmetic or anything really it's just vague and meaningless to me I'm afraid...
Jinja Template Designer Documentation
For more examples and samples, visit see this page
Does it show how to subtract 1.5 from the value provides by a sensor? I can't find it...
excuse my typing π¦
{{ states('sensor.foobar')|float - 1.5 }}
Thanks RobC π
Still can't get anything working. I think I need to start from the beginning in a different environment to get the hang of how this language actually works.
Use the Dev Tools while you're experimenting. Don't start by trying to make a template sensor from scratch.
Jinja Dev Tools?
I see, that's a starting point. Thanks for that Tom
Yay! Got something π Thanks guys
Should that bracket after foobar be curly} or normal ) ?
All good. Thought it might have been a typo :)
Is there a way using a template I can reference the value of an entity from, say, 24 hours ago? Maybe reference a previous logged entry in the DB?
not from a template, but perhaps from this: https://www.home-assistant.io/integrations/sql/
I've been using input_number to save the data at different points and then referencing that. It's cumbersome to make some many new entities
you can try a custom button card. it might use a local timer
Hi. Using HA supervised since one month ago. Love the idea of HA, but struggling with creating a light template of my liking. Is there anyone that could help me find any tutorials including code etc for creating a simple square light button (I'm using button-card) with info on how to change icon and text positions and size?
Yes, I've read the docs and I'm trying everything out as i go)
That's a #frontend-archived question.
Ok. I thought one created templates for re-use such as light-templates, or switches etc
You were asking about a Lovelace button, that's #frontend-archived
i would like to use a filter entity-card to show a card only when the entity (which is a date) matches the current date. Is there a way to use a template in state_filter?
@grim flicker Knowing I don't actually answer your question, I have another suggestion: a template binary sensor that defines if the entity date matches today and then a conditional card https://www.home-assistant.io/lovelace/conditional/that only show the entities when the binary_sensor is on.
That is indeed a good idea! Thanks
I have taken two rest api calls and extracted one value from each and am able to refer to them from their original entities. I get one out as a state attribute and can use it in the developer tools template editor as {% x = states.sensor.collected.state | float %} (this reports a string that I can cast | to a float). And the other one is a state attribute and I retrieve it's value from another sensor {% y = state_attr('sensor.factor','multiply') | float %}. Each of these are defined within their own definition in config.yaml under the platform: rest banner.
How do I use those values to present on a card as {{ x * y }}...
I can do all of the above in the template playground, but I don't know how to pull the calculation into a card when that calculation itself isn't defined in my config file
I feel like I'm close, but I think I must have to create a platform: template and somehow merge those into a new sensor result??
You either use a card that allows templates (limiting you to a subset of custom cards) or you make a template sensor that does the work for you.
Check out the integration docs for template sensors.
ok, so I am close
Indeed, you're on the right track.
ok, I'll keep looking then, I just didn't want to go hunting up the wrong path, thanks
for this am I going to use value_template and then insert a multiline jinja piece of code? and does that need to be surrounded in quotes?
If you're using multiline, drop the surrounding quotes.
any chance you could point me to such a template for ref?
There are several examples of multi line templates in the docs: https://www.home-assistant.io/integrations/template/
AHHHHHHH >- I saw that page early in putting this togerther, long since forgot about it, thanks! (I have LOTs of tabs open here, it's a nightmare) THANKS!
I'm still drawing a blank on this. But I think it's ion the reloading, which "YAML configuration reloading" is it for templates?
I've clicked them all and none of them appear to be loading templates, unless I'm doing something else wrong (which is certainly on the cards)
lol
You need to restart HA to pick up new sensors.
this code works perfectly in the template playground, I get the expected result:
{{ (states.sensor.mined.state | float ) * (state_attr('sensor.ethaud','price') | float)}}
But in the config yaml, it never loads
The one that says βtemplate entitiesβ
Weβd need to see the rest of the sensor definition.
And of course
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
my workflow for the rest sensors has worked perfectly, I go through each tab, from file editor, to config check (under server controls), and hit reload, then jump to the dev tools , I have a tab for states and templates..
under the YAML reloading, I thought there was a templates section before, but , I'll give it a restart
There is a template entities reload option there
Also, see the bot message where it says not to trust the UI check
It possibly only exists when you already have a template entity. I think this is their first.
AHHHHH, this is my first, good point
that's a good point, doing it now, thanks. I knew I'd seen it before, I'm currently rebuilding from scratch to try and "clean" it up lol
Well I'll be, thanks very much guys πΊ
tricks to make unit of measurement appear BEFORE the value?
put it before the value in the template
Hi y'all... having some trouble getting variables into discord notifier? Am I missing something or isn't it implemented yet?
{
"message": "Test: {{payload}}" ,
"target": "666666666666666666"
}
it's implemented
Soooo, i'm missing the point somewhere... got it.... 'll dig a bit deeper
i've got the following in my template {{ trigger.event.data.new_state.attributes.friendly_name.split()[-1:] }} but displays "['plant']" string instead of "plant". I have already tried {{ trigger.event.data.new_state.attributes.friendly_name.split()[-1:] | string }} but it doesnt help
is there a way of converting a list to string in Jinga2
[0]
Just for clarity, that's not converting, that's accessing the first element of a list (which in your case happens to be a string).
"d": "{\"list\":[\"Mandag den 12-04-2021\",\"Mandag den 19-04-2021\",\"Mandag den 26-04-2021\",\"Mandag den 03-05-2021\",\"Mandag den 10-05-2021\",\"Mandag den 17-05-2021\",\"Mandag den 24-05-2021\",\"Mandag den 31-05-2021\",\"Mandag den 07-06-2021\",\"Mandag den 14-06-2021\",\"Mandag den 21-06-2021\",\"Mandag den 28-06-2021\",\"Mandag den 05-07-2021\",\"Mandag den 12-07-2021\",\"Mandag den 19-07-2021\",\"Mandag den 26-07-2021\",\"Mandag den 02-08-2021\",\"Mandag den 09-08-2021\",\"Mandag den 16-08-2021\",\"Mandag den 23-08-2021\",\"Mandag den 30-08-2021\",\"Mandag den 06-09-2021\",\"Mandag den 13-09-2021\",\"Mandag den 20-09-2021\",\"Mandag den 27-09-2021\",\"Mandag den 04-10-2021\"]}"
Anyone who could help me getting the first element from this list as a date? (Or even better, converting all the dates to a list of dates, that I can manipulate).
It's a response from a REST call. Thanks!
It seems like it's nested JSON with an outer "d" and an inner "list"
But everything in the inner part is a string
Apparently that is the way ASPNET returns data, by packing it in an outer "d"
Let's pretend the entire object is called x, getting to the first comma-separated value inside your example would be something like this:
{{ x.d.list.split(',')[0] }}
You can test that in the Dev Tools by setting that JSON to a variable and then playing around.
The problem seems to be that the inner list is actually a string, so I need to parse it as JSON
Although judging by all the escape characters, you might have to parse the inner stuff.
Aye
Googling returns nothing
Same idea, just pipe it through tojson first.
You check the pins in here yet? π
HA templates just use Jinja and I know the built-in filters are pinned.
"{\"list\":[\"Mandag den 12-04-2021\",\"Mandag den 19-04-2021\",\"Mandag den 26-04-2021\",\"Mandag den 03-05-2021\",\"Mandag den 10-05-2021\",\"Mandag den 17-05-2021\",\"Mandag den 24-05-2021\",\"Mandag den 31-05-2021\",\"Mandag den 07-06-2021\",\"Mandag den 14-06-2021\",\"Mandag den 21-06-2021\",\"Mandag den 28-06-2021\",\"Mandag den 05-07-2021\",\"Mandag den 12-07-2021\",\"Mandag den 19-07-2021\",\"Mandag den 26-07-2021\",\"Mandag den 02-08-2021\",\"Mandag den 09-08-2021\",\"Mandag den 16-08-2021\",\"Mandag den 23-08-2021\",\"Mandag den 30-08-2021\",\"Mandag den 06-09-2021\",\"Mandag den 13-09-2021\",\"Mandag den 20-09-2021\",\"Mandag den 27-09-2021\",\"Mandag den 04-10-2021\"]}"
This is the output of tojson
So it looks like the output of tojson is still a string
The output of all templates is a string π Do the rest of your processing and see what you get back.
trying to access list just returns an empty string
or maybe i just don't know how to acess the result of tojson
What do i pipe it into to access the dict elements?
It should just be something like this but I'm seeing the same thing as you:
{% set list = (x.d | tojson).list %}
{{ list }}```
Yeah it seems like it keeps the object as a string and does not want to parse it as json
I'll let someone smarter than me have a go.
This was so close to being very easy, but then of course they have to do this π
You were so close
{% set value = "{\"list\":[\"Mandag den 12-04-2021\",\"Mandag den 19-04-2021\",\"Mandag den 26-04-2021\",\"Mandag den 03-05-2021\",\"Mandag den 10-05-2021\",\"Mandag den 17-05-2021\",\"Mandag den 24-05-2021\",\"Mandag den 31-05-2021\",\"Mandag den 07-06-2021\",\"Mandag den 14-06-2021\",\"Mandag den 21-06-2021\",\"Mandag den 28-06-2021\",\"Mandag den 05-07-2021\",\"Mandag den 12-07-2021\",\"Mandag den 19-07-2021\",\"Mandag den 26-07-2021\",\"Mandag den 02-08-2021\",\"Mandag den 09-08-2021\",\"Mandag den 16-08-2021\",\"Mandag den 23-08-2021\",\"Mandag den 30-08-2021\",\"Mandag den 06-09-2021\",\"Mandag den 13-09-2021\",\"Mandag den 20-09-2021\",\"Mandag den 27-09-2021\",\"Mandag den 04-10-2021\"]}" %}
{% set value = value | from_json %}
{{ value.list }}
tojson takes a dictionary and formats it as json. from_json takes a string formatted as json and turns it into a dictionary
you just had them backwards
if this is a commandline sensor or something, you should just be able to use value_json instead of value and it'll do all the conversions for you.
{{ value_json.list }}
@mighty ledge ```json
{
"d": "{"list":["Mandag den 12-04-2021","Mandag den 19-04-2021","Mandag den 26-04-2021","Mandag den 03-05-2021","Mandag den 10-05-2021","Mandag den 17-05-2021","Mandag den 24-05-2021","Mandag den 31-05-2021","Mandag den 07-06-2021","Mandag den 14-06-2021","Mandag den 21-06-2021","Mandag den 28-06-2021","Mandag den 05-07-2021","Mandag den 12-07-2021","Mandag den 19-07-2021","Mandag den 26-07-2021","Mandag den 02-08-2021","Mandag den 09-08-2021","Mandag den 16-08-2021","Mandag den 23-08-2021","Mandag den 30-08-2021","Mandag den 06-09-2021","Mandag den 13-09-2021","Mandag den 20-09-2021","Mandag den 27-09-2021","Mandag den 04-10-2021"]}"
}
ok, so
The input is wrapped in an outer d, so value_json.d would still return a string, right?
It's a REST sensor
{% set value_json = value_json.d | from_json %}
{{ value_json.list }}
I'll try that π
This'll make it tricky:
TemplateAssertionError: no filter named 'fromjson'
Does any of you know if it's possible to take that list of dates and add it to a calendar?
My other idea for that would be to write a small python program that just presents a webserver that serves an ics file with the data
There are only a handful of calendar integrations for HA: https://www.home-assistant.io/integrations/#calendar
If you're going to write something custom, maybe go with CalDAV
Ah yeah probably a better idea, I just don't know a better way to present multiple dates that goes into the future
It all depends what you want to do with it. If you come up with a way to get that list in a format you can work with, you might be able to make do with a template sensor and have other things take care of the logic around 'next date, following date, etc'
The good news is that @mighty ledge 's solution worked, so now I at least have the "next" date in a sensor
I'm trying to get a automation to work with a template condition. I have one light and I want to check if the brightness is equal to one of the two values(input_number), but there is not possible to use XOR. Any suggestions?
So thanks guys, now I have something to build upon!
I'll let you flesh it out with the real values but I'd go with something like:
{% set b = is_state_attr('light.b', 'brightness', '100') %}
{{ [a,b] | select('true') | list | count == 1 }}```
You could make it a one-liner but I broke it out for legibility. Essentially an XOR of two things is just checking that there is only a single thing that evaluates to true.
Nice, thank you. Will try that! π
Last line could equally be this (but it wouldn't scale as well with multiple values):
{{ (a and not b) or (b and not a) }}
Not sure you actually need to emulate an XOR in your scenario either:
{{ is_state_attr('light.a', 'brightness', 'value a') or is_state_attr('light.a', 'brightness', 'value b') }}
that could also work
Anyone knows why this is not working for my custom:button-card? π
- operator: template
value: |
[[[
return
states['sensor.recycleapp_xxxx_gft'].attributes.Days-until < '2'
]]]
icon: 'mdi:delete-emtpy'
- operator: default
icon: 'mdi:delete'```
Until you say what it's supposed to do and what it's actually doing, it'll be hard for anyone to explain the difference in behaviour.
Well i'm trying to change the icon based on the attribute of the sensor. If there is a trash collection in the next 2 days set mdi:delete-empty, otherwise show mdi:delete. π
I have been working on changing the icon for my battery status, based on @fossil venture above I looked at using 'customize' which I have used in the past. However when I put my ```
sensor.ups_battery_capacity:
into customize it fails and says "Incorrect type: Expect Object". Where am I going wrong?
@edgy umbra You're quoting "2", turning it into a string.
if the attribute is an integer, you should just use 2
I can display the value of sensor.ups_battery_capacity on an entity card just fine. It comes from:
- platform: snmp
host: 192.168.1.7
baseoid: .1.3.6.1.4.1.3808.1.1.1.2.2.1.0
community: public
port: 161
name: UPS Battery Capacity
value_template: '{{ (value | float) }}'
unit_of_measurement: "%"
Thanks for the answer Rob, just tested but still seems not working.
what is the value of the attribute?
This is the sensor info from dev tools.
sensor.limburg_net_afvalophaling_gft 20-04-2021 Wastecollector: limburg.net
Hidden: false
Sort-date: 20210420
Days-until: 9
unit_of_measurement:
friendly_name: limburg.net Afvalophaling gft
icon: mdi:delete
you have a typo: icon: 'mdi:delete-emtpy'
if that doesn't work, try replacing the states[] bit with 9 and make sure that works
Sorry i fixed that allready, this don't seem to change the icon.
you may need to cast it to float()
Also tried changing it to 9
You mean changing the [] to ()?
no, I mean doing float(states[xxx].attributes..xx)
if you write return 9 < 2 and it doesn't use the default case, then you have other issues
cough parseFloat cough
Guy's sorry but i'm not so good at this, i have now this but it gives a error in the card layout.
- operator: template
value: |
[[[
float(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) return 9 < 2
]]]
icon: 'mdi:delete-empty'```
Error: ButtonCardJSTemplateError: SyntaxError: Unexpected token 'return' in 'float(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) return 9 < 2'
that's not what I meant at all π
value: |
[[[
return parseFloat(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) < 2
]]]```
that's better
my point was to simplify the case until you get a rational result, and then add stuff back
Now it gives this error. π
ButtonCardJSTemplateError: ReferenceError: sensor is not defined in 'return parseFloat(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) < 2'
π
oh, nevermind. you're based on the hook
you keep abusing that apostrophe
- operator: template
value: |
[[[
return
parseFloat(states[sensor.limburg_net_afvalophaling_gft].attributes.Days-until) < 9
]]]
icon: 'mdi:delete-empty'```
Whi'ch ap'ost'rophe?
you started with this:
states['sensor.recycleapp_xxxx_gft'].attributes.Days-until < '2'
and you then removed all the quotes.
Oh i thought i just used the code from mono. π
state:
- operator: template
value: |
[[[
return
parseFloat(states['sensor.limburg_net_afvalophaling_gft'].attributes.Days-until) < 9
]]]
icon: 'mdi:delete-empty'
anyway
Don't seems to work, still showing the mdi:delete icon
dunno
here's one of mine:
state:
- value: "[[[ return states['automation.away_timer'].state === 'on'; ]]]"
operator: 'template'
name: "[[[ return parseInt(states['input_number.away'].state) + 's'; ]]]"
icon: "mdi:timer"
color: yellow
- value: "[[[ return parseInt(states['input_number.away'].state) === 0; ]]]"
operator: 'template'
name: "Away"
icon: "mdi:home-export-outline"
color: "red"
- operator: 'default'
color: green
name: "Home"
icon: "mdi:home"
works fine
maybe it doesn't like the "-" in the attribute name π€·
you could do states['sensor.limburg_net_afvalophaling_gft'].attributes['Days-until']
Thanks tried but don't seems to work, i gues there is something not good with the name of the attribute, i have another card for my thermostat which works fine with the same template layout.
Instead using a - in the attribute name the thermostat is using _ so maybe there is the difference
you can try using that attribute as the name to see that it resolves to something useful
Think i'm giving up for now, taked way to long. π
Thanks both for the help and assist! π
sensor.ups_battery_capacity:
device_class: battery
Thanks @fossil venture . This is now working.
Woops. I take that back. The icon has now changed to a 100% full battery and not my battery charging icons
The device class uses mdi icons.
With help from another member i fixed it. Changed Days-until inside the code to daysuntil and works fine now.
weird. I guess it just ignores the "-"
No i mean in the code of the integration. π
So if I want to do this: https://pastebin.com/ZysM3Yt1
Which card are you using?
I have some different battery cards with the same you want
Entities card
type: entities
entities:
- entity: sensor.ups_model
name: Model
icon: 'mdi:power-plug'
- entity: sensor.ups_status
name: Status
icon: 'mdi:power'
- entity: sensor.ups_battery_capacity
name: Battery Capacity
Oh, just use the custom:battery-state-card
That will do it all for you without any extra code needed
Its my UPS so has lots of UPS specific information on the card
@unique elm Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
I want something like this? https://imgur.com/a/aF9yadE
@edgy umbra Do you have code you could share so it is a little clearer for me?
Will share it in a minute.
Template Sensors: https://paste.ubuntu.com/p/QYVFD5TKtf/
I installed 'battery-state-card' with HACS. Restarted HA. Tried it on an entities card and its says "Custom element doesn't exist: battery-state-card." Yet is shows under HACS frontend as installed (mind you it calls it 'battery state card/entity row"
Check my template sensors and card. It will show all mdi:battery icons, changing colors on battery %, shows charging icon if phone is charging and turns color to yellow if low power mode is on.
Trying it now
Be sure to install custom:auto-entities card....
Just to let you know, this works also if you trow a return before the states. ππ»
yes, you'd need that
that was in almost all of the quoted code
that was just a snippet
My bad, have changed the integration code back to normal and used that template because if the integration will be ever updated my template with fixed code will no longer work.
right
I have done this. First "sensor.ups_battery_capacity no longer works or shows anything. There is a new sensor, "ups_battery_capacity_2" and this shows my battery level as a value but has no icon
I added this to 'sensors" in my configuration.yaml
- platform: template
sensors:
ups_battery_capacity:
unit_of_measurement: "%"
value_template: "{{ states('sensor.ups_battery_capacity') }}"
friendly_name: "Battery Capacity"
icon_template: >
{% set level = states('sensor.ups_battery_capacity') | float | multiply(0.1) | round(0,"floor") | multiply(10)| round(0) %}
mdi:battery-charging-{{level}}
since a UPS battery is always charging I skipped all of the other options
ups_battery_capacity:
unit_of_measurement: "%"
value_template: "unknown"
friendly_name: "Battery Capacity"
icon_template: >
mdi:battery-charging-0
well, that doesn't exist
that calculation must be wrong. debug it bit by bit
didn't you say that you now have that sensor with "_2" on the end?
I have done this. First "sensor.ups_battery_capacity no longer works or shows anything. There is a new sensor, "ups_battery_capacity_2" and this shows my battery level as a value but has no icon
so...
Yep, that did it. I now have:
ups_battery_capacity:
unit_of_measurement: "%"
value_template: "{{ states('sensor.ups_battery_capacity_2') }}"
friendly_name: "Battery Capacity"
icon_template: >
{% set level = states('sensor.ups_battery_capacity_2') | float | multiply(0.1) | round(0,"floor") | multiply(10)| round(0) %}
mdi:battery-charging-{{level}}
and it correctly works in developer...template
It also works on my entity card if I display 'ups_battery_capacity' but not if I display 'ups_battery_capacity_2' I get confused as to how the naming works, is this because the template is called 'ups_battery_capacity'?
you're probably causing a name collision
Should I name the template something else?
if you want, and don't want to cause a naming collision
I never explicitly named a sensor 'ups_battery_capacity' under 'snmp' it seems to have inherited this name as I had:
host: 192.168.1.7
baseoid: .1.3.6.1.4.1.3808.1.1.1.2.2.1.0
community: public
port: 161
name: UPS Battery Capacity
which I assume used 'name' and just added the underscores?
Then when I added the template you gave me I assume HA auto renamed the snmp sensor as 'ups_battery_capacity_2"
I will leave it as it is as it is working. Thanks for your help. I might add your code that once it reaches 100% it probably isn't charging. In fact if I want to spend a few hours I could use the status and if it is 'on battery' I don't use the charging icon and if 'online' it does. That will keep me busy for a while π
I tried this in 'developer tools...templates' and it works
ups_battery_capacity:
unit_of_measurement: "%"
value_template: "{{ states('sensor.ups_battery_capacity_2') }}"
value_template: "{{ states('sensor.ups_status') }}"
friendly_name: "Battery Capacity"
icon_template: >
{% set level = states('sensor.ups_battery_capacity_2') | float | multiply(0.1) | round(0,"floor") | multiply(10)| round(0) %}
{% set status = states('sensor.ups_status')%}
{% if is_state('sensor.ups_status', 'onLine') %}
mdi:battery-charging-{{level}}
{% elif states('sensor.ups_status' != 'onLine') %}
mdi:battery-{{level}}
{% endif %}
But in configuration.yaml I pasted this back in and it says 'error duplicate key' on both lines where I have 'value_template'
I thought 'value_template' was a command but I probably don't need it right?
This will work, right?
ups_battery_capacity:
unit_of_measurement: "%"
value_template: "{{ states('sensor.ups_battery_capacity_2') }}"
friendly_name: "Battery Capacity"
icon_template: >
{% set level = states('sensor.ups_battery_capacity_2') | float | multiply(0.1) | round(0,"floor") | multiply(10)| round(0) %}
{% if is_state('sensor.ups_status', 'onLine') %}
mdi:battery-charging-{{level}}
{% else %}
mdi:battery-{{level}}
{% endif %}
your spacing in teh template is a little inconsistent, but it might work
hi all i scraped my power usage off my local provider. The data is present the data table and update it daily. So I cant find a way to scrape only single day. What i did was scraped the entire table and and format into an 2 column array [[date, value] ,[date, value],[........]x 20. I'm going to send this data array to hassio via mqtt, but have no idea how to template it on hassio side.
let say i know how to template if it a single value but the data is send over as an array so i have no idea where to start.
It's all working. Just pulled the power lead out of my UPS and the icon changed perfectly. Thanks for all the help. I am posting this on the https://community.home-assistant.io/t/monitor-cyberpower-ups-plugged-into-windows-machine-via-usb/170497/22
@small hatch A similar sounding issue was described in this channel earlier today
oh let me check the history thank. did he/she got it working?
haha thank last long as it give me some hint on how to deal with data array it should be ok.
Howdy, can someone help with a webhook trigger
service: notify.mobile_app_pixel_5
data:
title: Incoming Call
message: 'Call from {{trigger.payload}}'
For some reason, the payload is empty
Can we see the trigger please?
@night warren posted a code wall, it is moved here --> https://paste.ubuntu.com/p/wqFBTnvWH5/
It's trigger.data not trigger.payload
In your message. See https://www.home-assistant.io/docs/automation/templating/#webhook
@dull bloom posted a code wall, it is moved here --> https://paste.ubuntu.com/p/qxKzjtvFJT/
I think I tried that too.... Let me try again though
Yeah - I only get a 'Call from'
Yeah I just read my own link. trigger.data has to be in form format. The only other option for webhook triggers is trigger.json and your data does not appear to be in json format either. So I don't know what you can do π€·ββοΈ
Ah,.....I tried trigger.json but no joy - just in case
hi all im need some help with templating mqtt data. Here the data i pushing over via mqtt https://ibb.co/g7bjp62 and here my template on hassio https://ghostbin.co/paste/k57bfas
i not sure is it issue with my data array that is being push over or hassio template. Or both
Can't see the image you shared. Also, please don't share text as images - just share both in a paste tool.
Right... Node Red... you want #node-red-archived
And stop sharing images π€¦ββοΈ
ok but i just want to know if the data is format correctly
im ok on the node red side. just hassio template side im dont quite know how to handle the data
i got it working if i just send over one single data point but not sure how to get hassio read and store array of data point
i want to use the data to show a graph vs my solar production graph
Share only the data you're trying to use in the template. None of the extra surrounding information.
I'm not interested in all the other lines about dates, msgid, etc.
And seeing array[21] doesn't help if I don't know what's inside the array. If all you want to do is access the first entry in an array, you just use [0] to do that.
the array as this [[date: "date", usage: float_value],[...]]
if i send just one data point explain just [date: "4/1/2021, usage: 17] i can get it template will so what i can only get value state templated but still having issue trying to get date to be templated as attributes
but if i send the entire array over i get no value at all
or should the data array be formatted as [[date, usage],["date",float_value],["date", float_value].....]
If it's like in this example, the square bracket notation will get the first inner value.
Neither look like sensible data though.
yes just an two column array in this case is a 2 x 21 matrix. first col is date: "m/d/yyyy" and 2nd is usage: float_value
i think i'll give up on the array and make it simple and just populate the sensor daily from now on by sending the last array value point from now on. So how do i get the date template as an attributes? If let say the data is send over like [date: "4/1/2021", usage: 17]. via this template https://ghostbin.co/paste/k57bfas
Not sure this is correct channel but could someone help me parse this?
</ha-icon><span>: ${states['sensor.1_iphone'].attributes['Street Number','Street','City']} </span>`
I am trying to get it to display like:
Street Number Street
City State
better yet... a way to parse 1 attribute that has too much info...
Formatted Address: '555 lost St, broken dreams, AA 55555, USA'
555 lost St
broken dreams, AA
So in displays on two lines but no zip or country.
try doing per each attribute.. </ha-icon><span>: ${states['sensor.1_iphone'].attributes.streetnumber}, ${states['sensor.1_iphone'].attributes.street}, ${states['sensor.1_iphone'].attributes.city} </span>`
thank you! Some reason she is getting all RED at me. I think its because attributes.streetnumber needs a space but i cant finger out how to add 'street number '
check the attributes name of your sensor maybe is written as street_number
no such luck its...
Street Number: 555-500
actually it shows as undefined, undefined, undefined
do you actually have all those attributes in your sensor
yea
Street Number: 555-500
Street: Hopeless Street
City: Broken Dreams
Postal Town: null
Postal Code: 55555
State: Screwed
I swear just when I think I get things figured yaml finds another way to screw with me.
city and street doesnt have spacing and it not show up?
SMH so city and state show up when i do caps So City State instead of city state
but nothing I do with Street Number works.
ah gotta do ['Street Number"] thank you
dont under stand why the return of the attribute "Formatted Address:" shows 555 street etc... but the fracking attribute Street Number: shows a range like 555 - 500
smh
oh well... this helps alote thank you Moto!
no problem im trying to figure some of these thing out too haha.
Drives me crazy as its hard to ask Mr google when you dont know what to search ya know.
anyone know how I could get this to txt wrap?
location: |
[[[
return `<ha-icon
icon="mdi:map"
style="width: 12px; height: 12px; color: red">
</ha-icon><span>: ${states['sensor.g3_1_iphone'].attributes['Formatted Address']}<span>`
Using the template {{ states.sensor.emby_latest_tv_shows.attributes.data }} gives me what appears to be a list of json objects, and the template editor says "Result type: list", so I thought {{ states.sensor.emby_latest_tv_shows.attributes.data.1 }} would give me the 2nd json object, but it instead gives me the 2nd character. Tried a few different things from the forums/doco but no luck... Is it possible to pull the Nth list object rather than the Nth character?
try {{ state_attr('sensor.emby_latest_tv_shows', 'data')[1] }}
what are you trying to do with it? The upcoming media card knows how to parse that stuff, and that integration is designed to feed it
I wrote an integration for another media source that has the same format
here's an example of my attributes, with a format string and one show:
my template above works fine to extract the second item in the list
Yah, I've got it displaying nice enough in the upcoming media card, but I'd like to use the button-card to make individual cards for each entry that can be arranged and scrolled horizontally.
Giving that template a shot now, though
https://i.imgur.com/NL9x6ST.gif Nah same problem unfortunately
it's almost like the integration is creating a list of strings, rather than dicts
looks like they had a similar, but even worse problem last year: https://github.com/gcorgnet/sensor.emby_upcoming_media/issues/12
but if upcoming_media_card is able to parse it, it's doing its primary job and there's little incentive to "fix" it. the integration that I wrote does the right thing, but it's for Channels DVR
you should submit a PR to fix it π
why the hell is it doing this?
attributes["data"] = json.dumps(card_json)
there's your problem right there
it makes a nice dict and then turns it into a string
Interesting, maybe I could fix it since that guy puts a prospective solution in there.
go fix that
You might be able to use |from_json in the template to parse it. Itβs just silly
Basically, a json.loads
Ha, didnβt even see that π
I just looked through the code.
Indeed, that should do it
Welp, a lot of work on the styling to go, but that's got the basic gist of what I had in mind working π https://i.imgur.com/ooBxHaA.gif
Kinda bummed but there doesn't seem to be a way to slow down the transitions, I had a news ticker vibe in mind, but that's not a #templates-archived issue!
@sleek nova posted a code wall, it is moved here --> https://paste.ubuntu.com/p/f2bbCsVkGG/
Can I ask how I would pull the stats from this link into home assistant as separate entities? https://api.carbonintensity.org.uk/regional/regionid/12 I have one sensor showing all of the attributes but want to break it out? Sensor is shown in the link below
https://imgur.com/PuTkFEx
You could create several REST sensor giving a value_template to get what you want in the json
Oh cool thanks, will give that a go!
I am trying find the issue with this template.
2021-04-13 12:34:24 INFO (MainThread) [homeassistant.components.mqtt.binary_sensor] No matching payload found for entity: motion_04 with state topic: tele/zigbridge_01/zb_motion_03/SENSOR. Payload: '{"ZbInfo":{"zb_motion_03":{"Device":"0x4ED2","Name":"zb_motion_03","IEEEAddr":"0x00124B002267B6F5","ModelId":"MS01","Manufacturer":"eWeLink","Endpoints":[1],"Config":["A01.1","I01"],"ZoneType":13,"ZoneStatus":12592,"Occupancy":0,"Reachable":true,"BatteryPercentage":100,"LastSeen":1043014,"LastSeenEpoch":1617288461,"LinkQuality":21}}}', template output: 'unknown', with value template 'Template("{% if value_json is defined and value_json.ZbReceived is defined %}
{% if value_json.ZbReceived.zb_motion_03.Occupancy == 1 %}ON{% else %}OFF{% endif %}
{%- else %}
{{ states('binary_sensor.motion_04') }}
{%- endif %}")'
ZbInfo is not what I am looking for its ZbReceived, when I run this template test it works fine.
but in the sensor it returns 'unknown'
can anyone help me find out what?
@naive hatch posted a code wall, it is moved here --> https://paste.ubuntu.com/p/6znNHnWjcQ/
Basic template question: I have a template switch, but it's state usually doesn't correspond with the two switches it controls. Is there a way to set the state of the switch to the same as one of the switches? Code is above ^ (Thanks HassBot :)
*I figured it out, using value_template
Could someone help me with this script/templating? I'm not sure whether this can be done in a way I'd like to achieve, but I'm running out of ideas anyway.
The script: https://paste.ubuntu.com/p/rRMH9W5DT9/
The error: Invalid config for [script]: not a valid value for dictionary value @ data['sequence'][1]['entity_id']. Got None. (See /config/configuration.yaml, line 18).
I've tried pretty much every possible way I just could think of, to define a variable, concatenating 2 strings + 1 script variable and later in the script use the newly defined variable as an entity_id
I have 2 devices, such as fan.xiaomi_blaa_blaa_bedroom and fan.xiaomi_blaa_blaa_another and the sensors are alike (sensor.bla_bla_bedroom_bla and sensor.bla_bla_another_bla), so I would like to avoid repeating myself (DRY) and just pass bedroom or another as a script variable and within the script I'd like to "construct" the entity id's based on this variable.
I know I could just pass 2 separate variables for the script, containing the entity_id's themselves, but I'd like to avoid that, to "keep my codebase at least slightly more maintainable", if it's possible
the error is telling you where to look
I know it's telling me my entity_id: "{{ entity_id }}" is the issue
that's why I'm asking can this even be achieved or not
ok, but do you know which one?
1 is correct, the other is not
you can copy the 1 to the other and it will work for both
but the error is telling you which one is invalid
but they're both the same aren't they?
nope
you need to expand what you're looking at
what's different about the fan.set_preset_mod service call and the xiaomi_miio.fan_set_favorite_level service call?
other one has target, other one don't
Alright, so which one is correct? The error tells you which one is not
both, or are the examples/documentation incorrect?
https://www.home-assistant.io/integrations/fan/#service-fanset_preset_mode
https://www.home-assistant.io/integrations/xiaomi_miio#service-xiaomi_miiofan_set_favorite_level-air-purifiers-only
Nope, templates are not allowed in one of the versions, I'm trying to get you to read the error message so that you can decipher this in the future
well it says the sequence 1 entity_id is the problem
exactly, ok, so which one is 1? This is something you may not know
meaning the latter, if the indexes in the error starts from 0, as in programming usually
lists in python start at 0
yes
So, to recap, use the target version as that is the correct method
with templates
without templates both are correct
Also, theres a 3rd option. You can put entity_id inside data/data_template
oh
and templates will work with that as well
that'd be cleaner/cleanest
so, templates only work with target, and data/data_template.
also, you should switch data_template to data
that's no longer needed
so like this? https://paste.ubuntu.com/p/sdRRtyMyzx/
yep
nice!
but you should switch
- service: xiaomi_miio.fan_set_favorite_level
data_template:
to
- service: xiaomi_miio.fan_set_favorite_level
data:
ah
at least no more error! thanks a bunch, gonna give the script a shot soon-ish, once I'm done eating π on a side note, that's a bit confusing that there's like 3, if not even more ways to define the exact same thing (and that the documentations are not up-to-date either(?)). the script worked like a charm with hard coded entity_id's before, that's why I was puzzled that why is it not working and that am I trying to do something that shouldn't even be possible
entity_id on the root level is legacy 'code', entity_id inside data is also legacy but is the most used method, entity_id inside target is new and it will most likely be the path forward.
ah, so I should start using the target one then instead. good to know :)
all 3 will exist forever
so, it really doesn't matter which one you use
entity_id at the root level is the only limited one
Hi guys. If I want to make this - 'Home'
To this - Home
Can I use this template:
'{{ trigger.to_state.state | regex_replace(find="'", replace="") }}'
Thanks!
good to know :) I think I'll stick with the data one, as it's cleanest/easiest for the eyes in my humble opinion
yeah, target was created so that services could support areas & device_ids. It only made sense to add entity_id
that depends on the trigger, if its a state change trigger, then yes. But I don't see how a state would have the word 'Home' in quotes.
long story... I extract the state to an Input_text, and it saved with the quotes
I am trying to build a way to get updates of my devices when they change locations. because each have more than one GPS trackers, every update I get notified... even if they dont change location (Moved from Home to Home)
So, I created an automation to act as a proxy...
That all sounds like a waste of time. There are ways to avoid getting notifications when the new state is the same as the old state.
Well, I asked several times about it and got the same answers. One even built a custom component to solve it...
But it looks like my template is still not working. The quotes are still there
A custom component to do something HA can do natively? That also seems like a massive waste of time.
What device tracker is reporting locations?
Can't you just group device_trackers for whatever you want and then create a trigger such as:
trigger:
- platform: state
entity_id: group.devices_to_track
to: "not_home"
and groups as:
devices_to_track:
name: Devices to track
entities:
- device_tracker.device1
- device_tracker.device2
not sure if I even understood correctly...
or use person if you want to bind multiple devices into one person and track if that person is home/at work/at school/not in predefined location
The person entity suffer from the same problem. it changes state every time a GPS tracker updates. Tried it before... even if it in the same location....
But grouping all the GPS tracker for each device might do the same as what I am trying do and mediate between the changes and the notifications. I will try it
it changes state every time a GPS tracker updates. Tried it before... even if it in the same location....
Wrong, wrong, wrong.
It might change attributes but the state isn't changing. And if your automation is triggering because you're listening to all changes, that's a flaw in your automation.
All it takes to ignore changes that have the same before and after value for state is a simple template condition that checks the two are different.
{{ trigger.from_state.state != trigger.to_state.state }}
Job done.
can I create a sensor which will be telling me a state (on, off) based on some template?
I have a feeling you're doing something wrong, but as I don't know for a fact, I don't know. at least it works for me. I have 4 devices bind to me, 2 for my wife and 2 for our kid. for example, the "left home" gets triggered only if none of the devices is saying "im home" and vice versa: "arrived home" triggers if at least one of all the bound devices tells HA "i'm home". and the very same "Kirbo is at home" doesn't get triggered more than once, as long as at least one of all of my 4 device_trackers (gps from phone, gps from watch, unifi presence for phone and unifi presence for watch) states that they're home.
How do you do that? I tried to trigger form the change of state of a person and the zone enter/leave trigger. also tried what mono suggested... non worked.
But you and mono seems so confident to make me think about it again and take another try...
I hope it will work
The examples I wrote above
Have you used the person state trigger and all the trackers are inside it?
Awesome! Need to get my head around exactly what's happening there but that's an excellent point to start from, thank you π
- Create as many persons as you want to track: http://homeassistant.local:8123/config/person
- Add the devices you want each person be tracked with, on the page above
- Create automations, such as: https://paste.ubuntu.com/p/jqgkk3R25n/
- Add as many locations as you want to track, on: http://homeassistant.local:8123/map
so thats maybe my problem. I tried to avoid using many automations so I 'templated myself to complicated death'. I used one automation and tried to identify each event and build the notification according to it...
why this sensor returns off status
sensors:
kitchen_stove_state:
friendly_name: "Kitchen Stove Status"
device_class: Power
value_template: >-
{{ states('sensor.kitchen_stove_energy_power') | float > 90 }}```
well, my example might be one way of doing the same thing. there could be easier ways as well, idk.. at least you could add multiple triggers, something like: https://paste.ubuntu.com/p/wyFyWhFTFr/
{{ states('sensor.kitchen_stove_energy_power') | float > 90 }} is true..its not false
not completely sure about the trigger.entity_id , but you can add as many triggers for the automation as you wish
actually this works as well, and is easier for the eye/cleaner code: https://paste.ubuntu.com/p/W49Nfz9bBy/
Can someone please help me, to solve this error?
Ludeeus told me, to add mor guards to the automation. But I donβt know how and what.
It looks good. I'll try it
Hope it helps/works like you want it to. If not, Iβm out of options
@humble beacon Do you know when you see that error message? It implies that the automation is trigger for something other than an event, but I don't see how that can happen
this is the code that fires the event:
hacs.hass.bus.async_fire(
"hacs/repository",
{
"action": "registration",
"repository": repository.data.full_name,
"repository_id": repository.data.id,
},
)
it makes me think that that's not the automation that's causing that error
Can anyone help with this?
ln1: |
[[[
return `<img
src='https://developers.google.com/maps/images/maps-icon.svg'
style="width:12px;height:12px">
</ha-icon> ${states['sensor.g3_1_iphone'].attributes.Street}, ${states['sensor.g3_1_iphone'].attributes.City}<br>${states['sensor.g3_1_iphone'].attributes.State}, ${states['sensor.g3_1_iphone'].attributes['Postal Code']}`
]]]
for some reason the text after the <br> is centered
but this...
ln1:
- font-size: 11px
- align-self: start
- justify-self: start
- padding-botom: 4px
... tells it to align with start.
Thank you for your help. I will search my config, if I find the mistake.
platform: numeric_state
entity_id: light.pc_light
value_template: '{{ state.attributes.brightness }}'
above: '253'
trigger: In 'numeric_state' condition: attribute 'brightness' (of entity light.pc_light) does not exist
Can anyone help to write a template based on the brightness. Would sincerely appreciate it! THank you
Is anyone familiar with the scrape sensor? For some reason, they dont work anymore
My scrape sensors were working fine, but after a restart they read 0.0
Just disappeared on me
yes I removed it π I suggested you use the tag attribute:, this is needed for your automation to trigger when only the attribute changes
what surprise me a it is that the error mentions a condition. Could you share your whole automation?
I had the attribute and it was giving me the same error
I think the attribute only works if the light is already on. Iβll post it in 10 minutes l, just stepped away from pc Iβm sorry
indeed you are right. If the light is off -> no attribute brightness
you could then replace the value_template with smth like {{ state.attributes.brightness if 'brightness' in state.attributes else 0 }}
Iβll give it a shot. Thanks Slash
OK, gurus, I need help in making this code more compact. What I am trying to do is compare the current temp of a thermostat to the set temp and return True/False. I'm sure there are more effective ways of doing this, hopefully a single line with piping.
https://paste.ubuntu.com/p/fq4n7F2FQn/
looks like you're filtering down to a single entity already based on that name
could drop the loop completely and just use that one entity
or do you have multiple entities with the name HW?
@thorny snow A shorter and more readable version of this could be written as {{ state.attributes.brightness|default(0) }}
I think the shortest you can get it without knowing the entity ID is:
{% set hw = states|selectattr('name', '==', 'HW')|list|first %}
{{ hw.attributes.current_temperature|default(0)|float < hw.attributes.temperature|default(0)|float }}
If there is more than one entity named 'HW', it will take only the first one into consideration.
I have a cover thats stuck at opening/closing instead of change to opened/closed. I guess it is possible to create a template where it sets value based on position?
Im trying to get this to work:
url: http://192.168.178.54:16021/api/v1/token/effects
method: PUT
payload: >
{ "write" : {"command": "display", "animType": "static", "animData": "18
{% set paneel1 = {{paneel1_rood}} %}
{% if paneel1 != '' %}
36776 1 {{paneel1_rood}} {{paneel1_groen}} {{paneel1_blauw}} 0 20
{% endif %}```
but the line {% set paneel1 = {{paneel1_rood}} %} is giving errors
I want to check if the automation sends paneel1_rood data to the rest command and if it does adds the line else it ignores it
If i get this to work i can successfully control my nanoleaf hexagon tiles seperately
This is the complete restcommand without the if statements. This does work but for it to work all values need to be filled so all 3 colors for all 18 hexagon tiles. i want to make a restcommand that also makes the correct code if only 1 tile gets the RGB colors from the automation. But it has to ignore all lines it doesnt get info from or the code will give an error in the nanoleaf controller. https://pastebin.com/aeUQN19T
is giving errors
What errors...? π€
Hard to say what's wrong if you don't explain the problem.
that is expecting a : and got a }
i filled it in on the test template page
im not really sure if {% set paneel1 = {{paneel1_rood}} %} can be written this way
Well this is your problem:
{% set paneel1 = {{paneel1_rood}} %}
You can't nest templates.
ok then thats my problem
What is paneel1_rood?
i have an automation calling a rest command and in the data part i have this
data:
paneel1_rood: '255'
paneel1_rood is used for RGB colors so its a number
This is the automation that works with the code i pasted. https://pastebin.com/w4hBi2jf
but i would like to being able to just give for example only tile 3 the
data:
panel3_red: '255'
panel3_green: '255'
panel3_blue: '255'
did it in english so you can understand what i mean
is there another way to check if a value is given from an automation yes or no and if not skip a line?
hmm why do i always have questions no one knows the answer to π
well the question doesn't really make sense
it does but i cant really explain the whole situation well enough
This is working https://pastebin.com/aeUQN19T
but when using this i need to send every tile all 3 colors in every automation i use
if i leave one blank i get an 400 bad request error.
It also doesnt make sense to give a tile a command if it allready is that color
change each {{paneel1_rood}} to {{paneel1_rood|default(0)}}
and it'll be zero when not provided
yeah this will turn off all tiles if there is no value. The trick would be to being able to just change one tile and leave the rest as is
an RGB of 0,0,0 will result in the tile go off
does the device support that?
you're writing a ton out, what happens if you only write one out? Does it still work? If yes then make a script for each one
i guess there seems to be no other way then to do that
if the device requires all inputs, then that's what you'd have to send
I just looked up nanoleafs, they look pretty cool
didn't even know they existed
Your other option is to store all the values that you send to the nanoleaf in helpers, and then use the helpers as default values
an input_number for each one
it woudl be alot of work, but I think it would be worth the effort
Any idea why this tempalte is evaluating to false? value_template: "{{ states('sensor.s31_251_br_tv_power_energy_apparentpower')|float > 60 }}"
when the apparentpower in dev tools is showing > 60
no its a state
then it should be working, take a screenshot of it in developer tools
Can someone help me out with a javascript template? This is returning "One" when the entity.state is 4
if (entity.state == 0)
return 'Zero'
if (entity.state == 1)
return 'One'
if (entity.state == 2)
return 'Two'
if (entity.state == 3)
return 'Three'
if (entity.state == 4)
return 'Four'
]]]```
states are strings
Ohh
also, you need terminations
I'm new to this, what are terminations?
;
It's working without them :/
at the end of each return
I've been trying to build an automation to act on ios notification actions, and I'm having trouble getting the choose function to match to a specific event. https://community.home-assistant.io/t/alert-component-ios-actionable-notifications-this-seems-convoluted/299290/12?u=apocrathia
The template condition that I'm using is "{{ trigger.event.data.actionName == "ALERT_TEST_YES" }}", but it's not hitting the conditional correctly. Is there something I'm missing?
Wait, now it's not working again?
https://pastebin.ubuntu.com/p/wNVPFQj226/
Nevermind, my sensor is just broken
I would appreciate some help with this template
Did it work for you/the way you wanted it to?
@naive hatch That template seems to execute fine. What is the entity_id: sensor.time in the configuration for?
It's to update once a second, when sensor.time changes? I thought I needed that (this code is partially stolen from a forum thread)
I removed it, and it's still 0, even though the 4 people in the group are all home
@naive hatch Try this https://pastebin.ubuntu.com/p/qRxXNQmQx8/
Still reporting 0
And if you execute that template in the dev tools?
friendly_name: "People Home"
value_template: >
4```
???
The sensor.number_of_persons_home is still reporting 0
Have you defined group.people? https://pastebin.ubuntu.com/p/skg8FhqqfX/
That template itself executes just fine for me like this: https://imgur.com/a/TPSUVvO
And you've verified that the group.people entity is present?
Yes, it exists. All 4 states are "Home"
Petro it doesnt really need all the info but every line in the code is more then just the RGB numbers. So if the RGB numbers of a specific tile are not set by the automation, it needs to skip the id number etc. thats why i wanted to skip a line when the data for that tile wasnt sent. This way i could make one setup in the rest command and use it for every automation i use without having to put all data in every time. And yes they are pretty cool indeed. To bad the integration in home assistant isnt supporting every tile as a seperate light. That would have been freaking awsome
@naive hatch okay so the template executes, but the sensor is reporting 0. You've restarted HA? Not just reloading?
let me try restarting, I've reloaded the templates and the name changed, though
Yeah, try restarting. Honestly, the restart has gotten so quick that I don't mind anymore. The reloads don't seem to catch everything.
I just put in an SSD yesterday, they're lightning fast :)
Although I bought the wrong adapter so I have to use USB-2
It looks like it's working now :)
Thanks for the help!
So if you notice on the dev tools page, the template monitors for state change events, so we don't have to specify an entity_id anymore.
So, it'll actually watch for the states to change of any entities within group.people.
I just grabbed this code from an older forum thread, so it's good to know :)
The devs did some major cleanup on the templating engine last year I think, and it sped a lot of that up.
I honestly love templates, but I don't understand the language very well :/
For the most part, it's just Python.
Cool :)
For the most part, it's Jinja π
It really is its own thing, but it at least lines up with a lot of the basic Python expressions.
Maybe its a stupid question. But why is something like {% set paneel1 = {{paneel1_rood}} %} not possible? Is it something none of the devs havent thought about or is it doing somethign strange in the background
try {% set paneel1 = paneel1_rood %}
Which devs? The HA devs didn't create Jinja...
If the variable paneel1_rood is already set, you can refer to it directly by name. https://stackoverflow.com/questions/3727045/set-variable-in-jinja#4181605
You can use {{paneel1_rood}} in a template. why cant i use it to set a variable
There is no need to have a template inside a template. The braces around a template just tell Jinja that the thing inside is an expression of some kind. It makes zero sense to have a template inside a template.
No. You can't use {{paneel1_rood}} in a template. {{paneel1_rood}} IS the template.
It's the braces around it that make it a template. Everything inside is just an expression.
{{ everything in here is the template }}
If you don't understand templates: https://jinja.palletsprojects.com/en/2.11.x/
if i put in paneel1_rood in my template the data from the automation isnt put in there
Because you're doing something else wrong π€·ββοΈ
You can't just make stuff up.
I had to leave earlier... what is paneel1_rood?
his variable name
Well, yeah... but where does it come from?
i have a restcommand with this template:
{ "write" : {"command": "display", "animType": "static", "animData": "18
36776 1 {{paneel1_rood}} {{paneel1_groen}} {{paneel1_blauw}} 0 20
40379 1 {{paneel2_rood}} {{paneel2_groen}} {{paneel2_blauw}} 0 20
", "loop": false, "palette": [], "colorType": "HSB"}```
i shortened it
in an automation i run service: restcommand and in the data i put:
data:
paneel1_rood: '255'
paneel1_groen: '0'
paneel1_blauw: '0'
``` and so on
so these values are filled in the rest commandf
i need to use {{ }} or else the template does not see them als variables coming from the automation
No. Stop.
Anything inside { } will be interpreted as Jinja. Something inside {{ }} gets returned, something inside {% %} just gets evaluated.
{% set b = 3 %}
{{ a * b }}```
This will return 15. The first two get evaluated, the last one gets returned.
I don't wrap 3 and 5 in {{}}
Share your script in a paste bin.
Ok.. makes sense. now i want to evalute it {{paneel1_rood}} is indeed returning something and if not skip the whole line
automation: https://pastebin.com/w4hBi2jf and restcommand: https://pastebin.com/aeUQN19T
You're not giving anything any variables. You're just writing random crap in a template and hoping for the best.
this isnt random. this is how it needs te be written and it does work.
but i want to be able to let the template skip lines
the top line: { "write" : {"command": "display", "animType": "static", "animData": "18 is always the same
{% set paneel1 = {{paneel1_rood}} %} = bad
{% set paneel1 = paneel1_rood %} = good
But there's no point assigning one value to another variable. Variables are only useful when you use them more than once.
then the lines beneath are the tiles every line corresponds with a id, frame, R, G, B, 0, and a transition time
the RGB needs to be changed with the automation
but when an automation does not send the RGB of the specific tile. it needs to skip that whole line in the template
so {% set paneel1 = paneel1_rood %} will get the data out of the automation and set it to paneel1?
after that i can check if its != ''
are you still on this?
yes i cant accept that this isnt possible
But there's no point assigning one value to another variable. Variables are only useful when you use them more than once.
It's all possible. You're just doing it wrong π€·ββοΈ
can you send this:
{ "write" : {"command": "display", "animType": "static", "animData": "18
36776 1 {{paneel1_rood}} {{paneel1_groen}} {{paneel1_blauw}} 0 20
", "loop": false, "palette": [], "colorType": "HSB"}
Why do you need to skip things?
will it error?
no
then there's nothing you can do
this will work fine
period
ok but then i have to write 18 rest commands for every tile
and when i want to change 10 tiles a different color i have to call 10 restcommands in an automation
while it should be send in one message
no its the number of the tiles set in the controller of the nanoleaf. it doesnt really matter what number stands there. as long as its higher then the amount of tiles i want to control at the same time.
or equal
so when i change 2 tiles from red to green the number needs to be atleast 2 but can also be 18
so you can only send something like this? I'm getting mixed answers here
{ "write" : {"command": "display", "animType": "static", "animData": "18
36776 1 {{paneel1_rood}} {{paneel1_groen}} {{paneel1_blauw}} 0 20
", "loop": false, "palette": [], "colorType": "HSB"}