#templates-archived
1 messages · Page 111 of 1
As I recall, yes. But you’d need to consult the docs
btw whats the deal with customizer ?
am i using something old ?
can customizer do what am intending to do therE?
i think i have to add this no ?
customizer:
custom_ui: local
in configuration.yaml?
Ok
where should i put this ?
custom_ui: local
since its not mentioned in the docs.
directly in your configuration.yaml
when i do it, it doesn't work : /
what's you error?
I notice that the code of the customizer calls the add_extra_html_url method on the frontend, which was removed on this ticket https://github.com/home-assistant/core/pull/39799
Didn't saw your error above. Your error says it found a customize parameter in the configuration.yaml...
Hi, I’m putting my question in the right channel. I want to create a custom effect for my Mi Lightbulbs, to make them flicker. I want to randomize the time they stay on/off, but I can’t make the random number generator work. Here is my configuration, can someone help me?
flow_params:
count: 0
transitions:
- TemperatureTransition: [6500, 50, 50]
- SleepTransition: ['{{ (range(50, 1500)|random) }}']
- TemperatureTransition: [6500, 50, 0]
- SleepTransition: ['{{ (range(50, 1500)|random) }}']
I don't know this integration, but could you test this instead?
- SleepTransition: "{{ [range(50, 1500)|random] }}"
just a guess
are you sure templates are allowed?
well, except for this random part, all my other templates work
I’ll try that 🙂
Nope, still got the same error:
Logger: homeassistant.components.hassio
Source: components/hassio/__init__.py:407
Integration: Hass.io (documentation, issues)
First occurred: 9:23:40 AM (1 occurrences)
Last logged: 9:23:40 AM
Invalid config for [yeelight]: expected int @ data['yeelight']['custom_effects'][3]['flow_params']['transitions'][1]['SleepTransition'][0]. Got '{'. (See /config/configuration.yaml, line 59). ```
I feel like I should be able to put a random number there, but I’m using the wrong method to do it
it says it is expecting an int, and that it had a template insteadd ({), really don't think you can use a template there
Try this:
transitions:
- TemperatureTransition: [6500, 50, 50]
- "SleepTransition: ['{{ (range(50, 1500)|random) }}']"```
I've seen people do similar. I think your problem will be that you weren't quoting the template.
I haven't tested it myself. Never had any need to use a template mid-list.
Awesome that’s it!
It works, thanks a lot!
Woops nevermind, I don’t know why but it had reversed to the previous file version (no idea how) but was showing the modified version. I had to restart my browser for some reason and I saw that. Still get the same error even while quoting the line.
(The previous version had a bunch of lines where I put the result of a few random.org runs for the delay, that’s why I thought it worked)
This is the conversation I remember: #templates-archived message
See if you can spot the difference between yours and theirs. They claim to have it working.
So, I was wrong 😆
We all get it wrong sometimes
Good day everyone
I have a question, and I am unsure if a template will solve my problem or if I should do something else
I have a sonoff 4ch pro for my 2 garage doors, the issue is the relay is on, then turns off
I really have not status as to what the door is in ( besides my tilt sensors)
make a template cover
use the tilt sensor as the state for the cover. for open/close use the relay's service
if you want, you can make it a template switch instead. Doesn't matter, just make it what you want to have in your UI
I guess I'm looking for the most efficient way to set it up, I guess i just don't like that i would need to create a routine to have open or close essentially just turn on the relay, does that make sense?
I'll look into a template cover, thank you.
@ripe folio it's not a 'routine'. You're creating an item that represents your device that you can use to control your device
Yes, you can then use this 'fake device' in those and use proper voice skills, i.e. turn on or open
I feel like there is a better way..
but word to the wise... if someone knows that you have the device in your house and your house doesn't have great sound proofing. All they need to do is yell really loud and your garage door will open if they know the name of the device.
There's not a better way
do you want to say "open garage door"?
if the answer is yes, the only way is a template cover.
plus feed that status to a tty like at 9 broadcast duma$$ left the garage door open
I feel like I am looking for reasons to get into templating, but am having an issue understanding what for
that doesn't require the template cover. In order to use alexa's or googles built in "Alexa, open xyz" or "Hey google, open XYZ" you need to expose it as a cover device.
"cover"?
yes... with a template cover
a cover is an opening and closing device in home assitant
ah device class?
entity_id = domain.object_id. ex light.livingroom. light is the domain, livingroom is the object_id, together they make the entity_id light.livingroom
but it is a switch
wow, there is just so much to know
which is good
i like flexibility but it paralyzes me
So if both the relay and tilt sensor are MQTT you can just make an MQTT cover. If they are from separate platforms, i.e. one is zwave and the other is mqtt then you have to make a template cover.
The tilt is zwave binary_sensor
Ok, then you're stuck with template cover
@mighty ledge posted a code wall, it is moved here --> https://paste.ubuntu.com/p/x68qQpvvSp/
I used to define my mqtt but switched to discovery, the prefix isn't always homeassistant which is odd
I'll have to figure out how to change it to a cover instead of a switch
then maybe i won't even need the tilt sensor
no, you can't switch it to a cover. You'll need a template cover
in order for the cover to work, you'll need a state which comes from zwave
which is why I keep saying template cover.
f these messages are published with the retain flag set, the cover will receive an instant state update after subscription and Home Assistant will display the correct state on startup.
I even wrote the code, it's in that link
You just need to change your entity_ids
plop that into your config and restart
ok, I'll give that a go, Thanks, just curious why use json to get the value rather than yaml
just curious
It seems easier
uh, what are you talking about?
garage: value_template: > {{ is_state('binary_sensor.xxx', 'on') }}
that's jinja
oh
It's required if you want to access other states from HA
right templates use jinga, service calls and others use json
no...
lol
service calls use yaml
sorry man, I appreciate the help
everything is yaml
templates use jinja
so you'll only have a combination of jinja and yaml
you can write yaml as objects. It looks like JSON but it's not
my_yaml:
my_field:
something: 4
is eqivalent to
my_yaml: {'my_field':{'something': 4}}
{"entity_id":"sensor.thingy"} is json no?
that's valid JSON but yaml accepts python objects
which is not JSON
fine line were walking here 😉
I'm an infrastructure guy, trying to #learntocode haha
Do you know of an introductory course that could help with this, and truthfully there is more of this in my new job than I thought
It would be benefifical, I want to go into it without them assuming i know python or javascript etc.
ok
JSON and Yaml are formats so there's tutorials all over the place but they'll be in random languages
python will help you learn jinja
I've never formally learned jinja but I knew python and the syntax is similar
but you can use these formats in a language? Doesn't the language dictate the format?
no, the library you use in the language dictates the format
there are python libraries that read and write yaml, json, xml, html, etc
same goes for every other coding language out there
So to dumb this down, for me, you have an array controller(language) you can apply passthrough or raid firmware to it(libraries) the disks are managed a certain way(format)
Well, i'm not sure what those things are
Think of it as plugins
software does xyz. If you want to do abc, you get the abc plugin
I don't do networking stuff, so the hardware & it's functionalities escape me
That is how I feel here haha but slowly
@crystal urchin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/fcH44cBFpF/
@crystal urchin take a screenshot of sensor.op8_notification in the dev tools / states page
Sure. give me a few to mark out some of the information
Okay @mighty ledge - https://imgur.com/a/sRYY3qh
use this template:
value_template: "{{ is_state_attr('sensor.op8_notification', 'android.messagingUser', 'android.app.Person@12345') }}"
your attributes are named 'xxx.yyy' therefore you cannot use the stateobject to grab the attribute information.
also, your result is not in brackets, so I removed them
Thank you, will give that a test shortly. Looks like I copied the wrong value from the line below for the [] - thanks for noticing that too!
Tested and confirmed working. Thank you Petro!!
hi all ..i m new here i neew some help about activating themes...
Igot this error:Logger: homeassistant.components.hassio
Source: components/hassio/init.py:407
Integration: Home Assistant Supervisor (documentation, issues)
First occurred: 1:56:25 (5 occurrences)
Last logged: 3:05:52
Component error: themes - Integration 'themes' not found.
Hey quick question: I'm trying to format a datetime helper to markdown and don't know how to get it to work.
{{ (strptime(states('input_datetime.some_value'), '%Y-%m-%d %H:%M:%S').strftime('%H:%M:%S')) }}
I've tried using the value directly, passing it through strptime (as shown) and everytime I'm getting UndefinedError: 'str object' has no attribute 'strftime'. The documentation is pretty silent on datetime helpers and formatting. With now(), I don't get this error.
Does someone have a helpful hint, link or anything, that could help me?
The documentation has plenty on datetime stuff: https://www.home-assistant.io/docs/configuration/templating/
You're probably looking for something like this (from the examples): {{ as_timestamp(states.binary_sensor.garage_door.last_changed) }}
Unfortunately, a strftime is missing there. I can either print out the full date and time including milliseconds or the UNIX timestamp. But I can't seem to get a custom format to work.
are there valid values in your input_datetime.some_value ?
I tried three ways:
{{ states('input_datetime.coffee_machine_start_time') }}
{{ state_attr('input_datetime.coffee_machine_start_time', 'timestamp') | timestamp_local }}
{{ (strptime(states('input_datetime.coffee_machine_start_time'), '%Y-%m-%d %H:%M:%S').strftime('%H:%M:%S')) }}```
and they all work fine
2020-11-23 14:59:47
2020-11-23 14:59:47
14:59:47
From what I can see, the values are correct. But the output is still the same "UndefinedError".
oh wait
So when I change it manually, the template works.
So it probably has something to do with my automation, that sets the datetime
probably, yes
I have one that sets the start time of the above coffee machine that works fine:
- service: input_datetime.set_datetime
entity_id: input_datetime.coffee_machine_start_time
data:
datetime: "{{ now().strftime('%Y-%m-%d %H:%M:%S') }}"
might wanna try something like that
Oh alright. I'm currently setting it something like this:
data:
timestamp: "{{ as_timestamp(now()) + ((states('input_number.lavalampe_max_runtime') | float) * 60 * 60) }}"
The calculation is the important part here
@lunar breach hmm.. still seems something's off in your parenthesis?
include the as_timestamp in the float
{{ (as_timestamp(now()) + ((states('input_number.lavalampe_max_runtime')) | float) * 60 * 60) }}
this one work fine for me:
{{ (as_timestamp(now()) + ((states('input_number.car_heater_hour')) | float) * 60 * 60) | timestamp_local }} that adds 8 hours to now()
and input_number.car_heater_hour is 8
when?
Either when I call the set_datetime service manually or when it is called via automation
@lunar breach if strptime is returning a string that means your format is wrong
I should clarify, the erro you are getting is a result of strptime returning a string, meaning the format you are providing to strptime is wrong
I had to test a script:
test_set:
alias: 'Test'
sequence:
- service: input_datetime.set_datetime
entity_id: input_datetime.test
data:
timestamp: "{{ (as_timestamp(now()) + ((states('input_number.car_heater_hour')) | float) * 60 * 60) }}"
that one works fine
Okay, the hint from @mighty ledge got me somewhere:
Doing this ... abomination ... does yield me the right results:
{{ (strptime(states('input_datetime.unlock_lavalampe'), '%Y-%m-%d %H:%M:%S.%f').strftime('%H:%M:%S')) }}
the .%f in the format was required
Although I still don't get why I have to convert dates back and forth to get this to work. Does HA store dates and times just as strings somewhere?
I'd say you don't need to. Are you mixing up datetimeand timestamp when you set your value?
in my examples above I show both
Gotta go. Good luck!
This is the automation step I take:
service: input_datetime.set_datetime
data:
timestamp: >-
{{ (as_timestamp(now()) + ((states('input_number.lavalampe_sperrzeit')) |
float) * 60 * 60) }}
entity_id: input_datetime.unlock_lavalampe
Which works
why are you converting back and forth for this template anyways?
I want to have only the time being displayed in a Markdown widget
thats a simple split {{ states('input_datetime.unlock_lavalampe').split(' ')[-1].split('.')[0] }}
Oh... yeah I tend to think to complicated :D
only convert if you need to adjust the time
I didn't expect that I would just get a string back originally. I hoped that I could get any format I want.
are you planning on posting the date in your markdown card at somepoint?
Pardon?
are you planning on displaying the date in the markdown card too?
Oh
Not for this case but I can see that I would be using it somewhere else at which point I would go back and copy-paste the code around.
But suppose I would: What would the "right" approach be if I would need a format like dd/mmm/yyyy instead (so I also get the month name)
{% set y, m, d = states('input_datetime.unlock_lavalampe').split(' ')[0].split('-') %}
{{ d }}/{{ m }}/{{ y }}
or your conversion thing
Okay the set part I should probably remember
{{ (strptime(states('input_datetime.unlock_lavalampe'), '%Y-%m-%d %H:%M:%S.%f').strftime('%d/%m/%Y')) }}
read up on Jinja
it's the language being used
I will. Thanks for the help 👍
@lunar breach posted a code wall, it is moved here --> https://paste.ubuntu.com/p/fhnFn6ZTB2/
@leaden onyx posted a code wall, it is moved here --> https://paste.ubuntu.com/p/NVQdd44DxP/
Coming from #automations-archived, thanks to @arctic sorrel I'm this far, now. See above.
@leaden onyx Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
Sorry.
@leaden onyx it will only trigger if the value turns from false to true
I took down the smoke warner, so I can warm it up with my hands and let it cool down for testing.
Deleted the automation and created it, again. Now it works. Many thanks. I really appreciate your help.
So I have a rest_command entity like this:
method: POST
content_type: 'application/json'
payload: '{"command":"{{ command }}"}'```
Is it possible to have it evaluate a template in my command shown below somehow?
action: call-service
service: rest_command.my_service
service_data:
command: '{{input_text.my_command}}'
@misty pasture make a script and call the script from the action
i want to get an attribute (long string with shorter strings divided by comma), split it into shorter strings (like python split(',') function and then iterate through each of them
or alternatively run a proper regexp on whole long string
any tips how can i bite this ?
You can use .split() in templates 🙂
I got a problem with a template.
using this syntax, it works fine:
- service: telegram_bot.send_message
data:
target: [xxxxxxxxx,yyyyyyyyy]
but I want to template it to sth like
target: >
{% if yadiyada -%}
[xxxxxxxxx,yyyyyyyyy]
{%- else -%}
[xxxxxxxxx]
{%- endif %}
``` but I get an error saying `test: Error executing script. Invalid data for call_service at pos 2: expected int @ data['target'][0]`
Are the xxx and yyy numbers?
It's probably seeing that whole row as a string. Try returning it from a template:
{% if yadiyada -%}
{{ [xxxxxxxxx,yyyyyyyyy] }}
{%- else -%}
{{ [xxxxxxxxx] }}
{%- endif %}```
Dumb bot.
What version of HA are you on?
0.117.2, supervised, raspbian
You'll need 0.118 to get native data types out of templates.
Before that, every template returned a string.
haha really? :D what a coincidence, that one release, just in time :D
😉
It works! 👏
@glad moth posted a code wall, it is moved here --> https://paste.ubuntu.com/p/tcfM7fdqd9/
Would anyone be able to help correct my code here? I get an error that says invalid config for binary sensor, extra key not allowed. I want the sensor to be on when the living room stereo is on, and off when the living room stereo is off
See code wall above or if you can see what's wrong from this snippit that's cool too - platform: 'value_template' prob_given_true: 0 prob_given_false: 1.0 value_template: >- {{ is_state('media_player.living_room','off') }}
@glad moth It seems you are overcomplicating things. "I want the sensor to be on when the living room stereo is on, and off when the living room stereo is off"
That's basically the first example in https://www.home-assistant.io/integrations/binary_sensor.template/
Like
binary_sensor:
- platform: template
sensors:
power_on:
friendly_name: "Power is on"
value_template: >-
{{ is_state('media_player.living_room','on') }}
You’re right! It basically is. Thanks so much, I need to go to bed haha
@steep lava posted a code wall, it is moved here --> https://paste.ubuntu.com/p/j8sr6h6NzJ/
I created this script for turning on some dimmers. If the sun is up, they will be set to 100 percent. If the script is called after sunset then they will be set to 35 percent. The problem is the script takes about 10 seconds to run. The relays all turn on immediately, but the dimmers are delayed until the end of the script.
Well, automations and scripts work in order so it depends on what you want. You could adjust each lights dimmer after you turn it in or prob even with the on event
I tried placing the dimmer action at the beginning of the script and they still end up turning on 10 seconds after everything else. Then I substituted for a different set of dimmers and it still took just as long
Maybe I should ditch HA scripts and tie a scene into node red. Too bad scenes can’t handle templates because they are fast and work great
Wouldn't the scene be calling the same services as the script?
Was more curious about why they were seeing a delay in their script but not in applying a scene.
it depends on the hardware and the mode he's using for the script
in templates like this {{ trigger.entity_id == 'sensor.illuminance_1_power' }} can i use wildcards like: {{ trigger.entity_id == 'sensor.*power' }} ??
or how do i represent any sensor that ends in the name with "power"
Something like this, HellCry:
{{ 'sensor.my_power'.split('.')[1].endswith('power') }}
In your case, just test directly against trigger.entity_id, not the string I hardcoded in.
.startswith(string) also works in case you wanted to check the beginning of a name (maybe you prefix all sensors with the name of the room they're in).
Just don't use those funky quotes 😄
Hello 🙂 I'm trying to extract unnamed JSON attributes into various sensors depending on nested attributes. If at all possible, I'd love to have all the values in a single sensor with attributes, but multiple sensors would do as well. Here's an example JSON output: https://hastebin.com/esifiboyox.json
Which bit are you trying to read?
FraksjonsId is the unique identifier to which I can map named sensors (or attributes)
And then I want at least the first entry inside "Tommedatoer" for each element
That would be the sensor state
And the name would be specified according to FraksjonsId
The unnamed bits are just array items. Something like {{ value_json[0].Tommedatoer[0] }} would give you the first value.
Assigning it to sensors... that's an #integrations-archived thing.
Yeah, I feared as much. I've got a solution similar to what you suggested for two sensors right now. Except it goes like this:
value_template: >
{% for entry in value_json %}
{% if entry.FraksjonId == 3 %}
{{ entry.Tommedatoer[0] }}
{% endif %}
{% endfor %}
But the system changed and I need 5 sensors instead of 2. Feels wrong to send 5 separate requests for the same data
That looks... awful.
😦
You want them in order then?
I need to map FraksjonsId to manually specified names
But they aren't always in the same order in the response JSON
I guess if it's possible to sort the array by FraksjonsId I could use static indexes
You could probably use the built-in Jinja filter to sort: https://jinja.palletsprojects.com/en/2.10.x/templates/#sort
Maybe... I'm not that familiar with Jinja.
Interesting 🙂 I'll play around with it in the template editor
It lets you sort on an attribute, judging by the docs. Sort by 'FraksjonsId'
Once sorted, just pick an item by index (i.e. list[0] is the first item in list).
Sounds good! I'm gonna test that. How would I go about assigning all of those to attributes or separate sensors from the same rest sensor?
That's where you need to jump over to #integrations-archived
Fair enough. Thanks for your help so far!
Hmm. {{ x | sort(attribute="FraksjonsId") }} just outputs the JSON as it was, with no changes
😅
FraksjonsId or FraksonId? Your original paste had the latter...
If you put this into
> Templates, you'll see it sorts them: https://hastebin.com/uvukopetup.lua
Oh, you're right! I actually misspelled it
😉
Hi guys, i've created a template sensor to mirror the value from a temperature entity from my home weather station. I want to sync it to my google assistant ecosystem via nabu casa but it doesn't appear in the list of available entities to sync. Any idea why this would be? Something related to it being a template entity instead of a real entity?
Haha! I found the problem. I had to set the "device_class" to "temperature"
OK new question.. The problem I was attempting to fix is that my temperature sensor, when synced to google, and I ask google "whats the temp" will say "it is 80 degrees, and the weatherstation temp is off". The part about being off makes no sense because its a temperature sensor and always on and I don't want google to say that. Is there a way to extract only the temperature data and not the on/off state from the actual entity for use in my template sensor?
This is the relevant code now value_template: "{{ states('sensor.my_weather_station_temp') }}"
Either that's not all of the template or there's more config you haven't shared.
`# Weather Station Template Sensor
- platform: template
sensors:
weatherstation_temp:
friendly_name: "Weather Station Temp"
icon_template: mdi:thermometer
value_template: "{{ state_attr('sensor.my_weather_station_temp') }}"
unique_id: "weatherstation_temp"
unit_of_measurement: "temperature"
device_class: "temperature"`
But since that template looks good... it's probably your #integrations-archived that are the problem.
I changed it to state_attr just now
yeah doesnt work lol
🪨 🪨
I'm trying to get it to only pass through the temperature value, not the on/off value
So theres no way to do this using template syntax?
I'm not a programmer so this is at the limits of my abilities
Your sensor looks fine. It's nothing to do with the template you shared.
You haven't said how it talks to Google... but that's an #integrations-archived discussion at this point.
Okay... so try #voice-assistants-archived for help. Not a template.
I'm still thinking there is something I can do in template though. Because the state syntax returns each state sorted alphabetically
statesi mean
So theres two states, one for the temperature value, and anothoer for the on/off value
I just want to return the temperature value
hmmm but yet when I look at the state and attributes in the developer tools it only yields the temperature value so I dunno maybe ur right about the integration being screwed up, but I can't fix that sadly
Each entity in HA has a single state. In your case, it appears to be a temperature.
It may also have attributes... but that's got nothing to do with the template you shared.
And who knows what you can control? You haven't actually bothered to ask in the right channel yet.
yeah, I figured that out now, the state_attr would return the attribute value
Go to #voice-assistants-archived, see what they suggest.
I was just trying to solve it with template syntax if possible, I appreciate your help
More of a learning project for me
Trying to work out if any of a list of entities is on.
I worked out:
is_state("light.kitchen_2", "on") +
is_state("light.living_1", "on") +
is_state("light.living_2", "on") }}
But as expected, that sums the boolean instead of being more like OR gates.
Is there a better way without creating a new group?
Replacing the + with and or looks to be the trick. Still wondering if there is a better way 🙂
@stuck kelp why don't you want to create a group? it makes it easier.
{{ expand('group.xxx') | selectattr('state','eq','on') | list | count != 0 }}
or you can do {{[states.light.kitchen_1, states.light.kitchen_2] | selectattr('state','eq','on') | list | count > 0}}
or
{{[states("light.kitchen_1"), states("light.kitchen_2")] | select('eq','on') | list | count > 0}}
Don't want a group because I won't ever acuate it.
It's just to change another light if any one of those are on.
I do think you're right though. Logic on a group is group == 1: if any in group on
I like the list notation. Might use that for this. (BTW this is Node Red, so Im scared to think there is a better way in NR too haha)
You don't have to actuate a group for a group to be useful.
You're picking the harder way to do something that already has a simple solution.
You don't build a car from scratch every time you want to drive somewhere, right?
Thing like this is why I'm frequently visiting this channel, thanks!
Comparison of what I had, and what I could change it to: https://hastebin.com/ayoqoquvim.pl
@stuck kelp managing an if then template is harder than managing a group. And you can make a automation that manages the group for you.
True, well put. I'll throw them into a group.
Was a good education in templating though
Hi everyone, i'm using the ResRobot integration an got a sensor from it with a name that has a dynamic and static part and i wanna remove the static part. It generates a name like: "Länstrafik - Buss 123" or "Länstrafik - Buss 321" and i wanna remove the "Länstrafik - "-part. So i wrote this: {{ state_attr('sensor.avgang_b', 'name') | string|regex_replace(find='Länstrafik - ', replace='')}} which seems to work fine when i test it in the developertools but i cant seem to get it right when using it as a template
This is the complete card where i wanna change the name:
@hallow mesa posted a code wall, it is moved here --> https://paste.ubuntu.com/p/5nq25rWvVy/
timestamp_custom('%d-%m-%y') <--- outputting year in 20 how to get 2020 ? %yyyy ?
thnks man
made this template but its outputting the top one constantly ?
if dates match --> output which container
else None
the sensors. conditions are in the same date format
simplified it
but not working
if sensor reaches 0 it needs to give the name
but remains 0
remains None
i mean
1 sensor is 0
{% if is_state('sensor.gft', '0' %} should work
no it shouldnt, since i didnt type all characters...
{% if is_state('sensor.gft', '0') %}
Gft
{% elif is_state('sensor.pmd', '0') %}
Plastic
{% elif is_state('sensor.restafval', '0') %}
Restafval
{% else %}
None
{% endif %}
I bought Tuya curtains/covers windows controllers. I want to add it to HA with slider. Does anyone know how to do it?
anybody knows this type of error in my logs: ```The 'entity_id' option is deprecated, please remove it from your configuration
Home Assistant is starting, not everything will be available until it is finished.
Integration:template
I want to set for my wardobe colors based on tempereture outside
should I cast to float these conditions or to int?
and what is correct syntax for rgb_color?
instead of just string "violet"?
@sonic nimbus the error message is telling you what to do
@sonic nimbus rgb color expects a list that represents [red, green, blue] in ints that range 0 to 255
hi, I am working on a replacement/improvement of the “Alexa connect” device (https://www.pocket-lint.com/smart-home/news/amazon/142408-what-is-amazon-echo-connect-and-how-does-it-make-calls). I have developed a home assistant replacement, that will announce through Alexa, the caller's phone number, give you their number location using geocoding from Google's phonenumbers (https://github.com/google/libphonenumber), and provide the caller’s name from their phone number in your contacts. If the caller is not in your contacts, Alexa only announces what is directly provided by the callerid and the geocode information.
I got our Google voice phone working completely with all the Alexa announcements described above using an obi202 google voice adapter and the home assistant obihai integration which provides caller callerid info. I am working on extending to wifeys and my cell phone, I have the caller’s number from our cellphones forwarded to HA by tasker. I have run into one problem which escapes me, I can’t get a sensor template for the caller's phone number in the same format to use the same programing for both cellphones and google phone.
Ideally, I need phone number for input into my program in the following format +1XXXXXXXXXX which both the google geocoding program and my contacts dictionary lookup will accept.
I need to convert the obi phone adapter from format xxxxxxxxxx which requires adding a "+1" in front of the phone number.
- platform: template
sensors:
prefixed_caller_number:
value_template: "{{ '+''1' + states('sensor.all_caller_number') }}"
where sensor.all_caller_number is provided by the obihai integration and the desired formatted number is "prefixed_caller_number".
I get the proper result from the template developer tools e.g. +18004564567, but the value of sensor.prefixed_caller_number is 18004564567, that is, no "+" in the front. I have tried all varieties of quotes, {{}}}, and \ before and around the plus thinking it’s a problem with the + not being escaped.
I can get either cellphones or google voice phone to work but not both at the same time by doing the phone number formatting in my python script, but I need the above common format for both to work with the same script.
any ideas why I can add a plus to the front of my sensor value?
@zinc sable It seems like HA is converting the string to a float (?) if it can be interpreted as that. Even thought it doesn't care if you set a formatting like '{0:+6d}'.format(xx).
If I put this in template and shoot that into a persistent notification:
test_tmpl:
value_template: "{{ '+' + (state_attr('sensor.sval_humidity_2', 'lastUpdated') | string ) + }}"
I get 1606551375.
But if I put in the same thing twice, making sure it can't be number:
test_tmpl:
value_template: "{{ '+' + (state_attr('sensor.sval_humidity_2', 'lastUpdated') | string ) + '+' + (state_attr('sensor.sval_humidity_2', 'lastUpdated') | string )}}"
I get :
+1606551375+1606551375
I'm sure there is a work around for this. If you find it, please report back.
don't need a work around, just correct syntax. Change '+''1' to '+1'
er wait, lemme try in 118
Nope, the + is seen as part of the number
if you place a space between the + and the 1 it's seen as a string
If it hadn't been for them pesky native types
@waxen rune using | string does nothing btw, the new template changes do not look at the template at all. It's a function that's applied after you get the result back.
I've seen a few people with use cases that don't play well with the native type change.
Someone wanted the string 'None' back from a template. You can imagine that didn't work well 🤣
what happened? Errors?
Lol, in the template editor it returns nothing
no complaint either
in the 0.119 dev build
Yeah, returning nothing is the problem. I think it only blows up when it runs through voluptuous and doesn't see the type it's expecting.
So I'm pretty sure there is a change going through with template sensors & value_templates
where it doesn't do the typing
because a sensors value is always a string
I wrote this issue up a week or 2 ago https://github.com/home-assistant/core/issues/43397
A trade off for making it easier for most use cases is making it harder for a few edge cases I guess.
For the one question above I tested out like ten variants, while reading up on Python formats. They all worked fine showing + before the number as long as there were another template in the test box, but they all broke when I tried one by one. As you said, "It's a function that's applied after you get the result back." and it seems that also applies in the template box. Maybe by design, but not very intuitive while troubleshooting 🙂
it's applied to the entire returned response
exactly. took me a while to see that 🙂
so if you do {{ 'a' }} dklsjfldskj {{ 'b' }}. They are not separately resolved
a typical edge case where it would have made sense to test the templates in separate windows/boxes/instances
just didn't think of that then
for those, it would be convenient to have like "please resolve this natively, without making assumptions"-function
like the other example with None and I guess there are other
That might be nice but you'd need to know where native typing is not used. Currently it's used everywhere
so, turning it off would actually hurt you
for the example above, I would have added a space and then trying to trim that in the next step. is there an obvious better way?
what do you mean, trim that in the next step?
If I want the number including the leading + to be used in an automation for example, I assume I could.. no, it will still be resolved as a... forget it. not thinking all the way.,
exactly
its only applied at the end
trimming it or doing anything in the template won't work
i can't get my template sensor rounded
This is my sensor from the integrations
sensor.solaredge_current_power
I want to round without decimals.
This is what i created
value_template: '{{ states.sensor.solaredge_current_power | round(0) }}'
But this is not working, anyone has a clue?
"{{ states('sensor.solaredge_current_power') | round (0)}}"
and if i want to divide by 1000?
"{{ states('sensor.solaredge_current_power') /1000 | round (0)}}" is not working
if you want to calculate, you need to tell it to treat the string as a float (number) before the calculation and use parenthesis to make sure the calc and round is done in correct order. I'd try something like this:
{{ (states('sensor.solaredge_current_power') | float / 1000) | round (0)}}
Furthermore, the round(0) is resolved first now, so this will first round 1000 to 1000 and then use that rounded value in the calculation
Oh, I should have read the entire message of boneheadfraggle 😎
i recieve an error.
Error loading /config/configuration.yaml: invalid key: "OrderedDict([("(states('sensor.solaredge_current_power') | float / 1000) | round (0)", None)])"
in "/config/sensor.yaml", line 117, column 0
did you try it in Dev Tools?
as far as I can see, it should work. there may be something else wrong in the sensor config so please share the complete config for the sensor, using correct formatting
how can I format correctly here?
solar_panels_current:
friendly_name: "Current power"
value_template: {{ (states('sensor.solaredge_current_power') | float / 1000) | round (0)}}
unit_of_measurement: 'kW'
you forgot the "
when not using multi-row templates, you need " around
value_template: "{{ (states('sensor.solaredge_current_power') | float / 1000) | round (0)}}"
Thanks folks all for your input on my “+” templating problem, consulted with my two sons, and they came up with a solution in python which I can use the same script for both cell phones and google voice phone
My sons were not terribly excited about my project initially when it was only with google landline-like voip phone, but when I got it working with cellphones, they thought it was great idea.
@sonic nimbus Something like
value_template: "{{ ( as_timestamp(state_attr('calendar.stefan', 'start_time')) - as_timestamp(now()) ) if state_attr('calendar.stefan', 'start_time') else 123 }}"
should result in the value being 123 if the state of calendar.stefan's start_time is None, else if it isn't None, the value will be calculated as normal.
I am trying to template an inline keyboard of a telegram notification - which I don't know if it's even possible to do, but this is what I have so far , which seems to be syntactically correct. However I am getting an error when executing my automation:
https://hastebin.com/ohufuzibeg.php
the error I get is Button_data_invalid
I have also tried using | instead of > next to inline_keyboard to no avail
I've also put the inline_keyboard part in the template and it doesn't seem malformed. The output is what you'd expect to work:
Output:
inline_keyboard: >
- 'Living room - Override:/overrideone'
- 'Kitchen - Override:/overridetwo'
- 'Bedroom - Override:/overridethree'
I'm trying to play a random mp3 every whole hour, but my template doesn't work
media_content_id: >
{% set address = 'http://192.168.1.10:8123/local/kvitter/' %}
{% set birdlist = ['blames1.mp3', 'blames2.mp3', 'bofink1.mp3', 'bofink2.mp3', 'gardsmyg1.mp3', 'gardsmyg2.mp3', 'gronsiska1.mp3', 'gronsiska2.mp3', 'gulsparv1.mp3', 'gulsparv2.mp3', 'koltrast1.mp3', 'koltrast2.mp3', 'lovsangare1.mp3', 'lovsangare2.mp3', 'talgoxe1.mp3', 'talgoxe2.mp3', 'tradkrypare1.mp3', 'tradkrypare2.mp3', 'tradlarka1.mp3', 'tradlarka2.mp3'] %}
{% set rng = range(20) | random %}
{% set outputstring = address + birdlist[rng] %}
{{outputstring}}
I solved it, the problem wasn't the template
Hi I've been trying to get this to work for a while now if anyone can help I'd be appreciative! In an automation to send a notification containing the value of the input.number
service: input_number.set_value
data_template:
value: "{{ trigger.from_state.state|int - trigger.to_state.state|int }}"
entity_id: input_number_weight_difference```
@slate osprey what was it
@sly urchin , without seeing your whole automation, it is kinda hard. Either send me a dm or share you whole automation.
@sly urchin Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
thanks for replying, here is the full automation.. https://hastebin.com/vafobulasa.yaml
I now have the same "state is undefined" error from this, I will try with the actual scales though as it may have been my test counter as the trigger being the issue
Hi i'm sending a MQTT message to my HA in this format {"celcius":17.3,"co":400,"eth":18818,"h2":13510,"humid":67,"id":"Room Env Sensor","tvoc":0} i know my HA is receiving this message because when i create a sensor ```
sensor room_temp:
- platform: mqtt
name: "Room Sensor"
state_topic: "temp"
the whole string is displayed. How can i manipulate this string so i can use each value separate ? do i need a REST template or do i need to split ?
Currently making me my partner's hero:
sensors:
master_fan_conditions:
friendly_name: "Master Fan Conditions"
delay_off:
seconds: 10
value_template: >-
{{ is_state('binary_sensor.magnus_sleeping', 'on')
or is_state('binary_sensor.clare_sleeping', 'on')
or states('sensor.master_bath_humidity')|float > 75 }}```
the bedroom fan is a subject of contention and she didn't want me automating it. My challenge was improving on the simple on-off switch and have it running under any of the conditions that she's able to throw at me. This template will grow with her conditions.
Line 10 should be data: not data_template and entity_id should be spaced in under data
Hi! Could anyone point me in the right direction to create a sensor template that does the following, take 2 different automations as input, compare the last triggered values and output the date/time of the latest of the two? I should create some kind of custom sensor I'm guessing, but any good ideas how to get started?
@haughty pond not possible with a template sensor
@mighty ledge , gotcha, what would be your suggestions for getting the outcome I'm looking for?
you have to create a template sensor off the sensors in the automation
So first a custom sensor for each of the automations, getting the last_triggered values, and then building upon those 2 sensors?
or just forgo the autoomations and get straight to the information
what do the automations do
Okay, scenarario is as follows. I've spent 2 full days trying to communicate with my new robo-vacuum unsuscessfully, ended up having to resort to triggering stuff via AssistantRelay. Meaning that I can't actually pull any info from the vacuum itself. So, what I have are one automation that starts the vacuum at certain times, and then a button as well for manually triggering the vacuum. What I want to do is get the date / time of whatever was run last, the automation or the manual trigger, and output that date/time to my Lovelace.
Hope you get where I'm going, like the final output would be something like: "Last cleaning run: 2020-11-30 18:36"
But maybe I'm trying to hard, because if a make the button manually trigger the automation instead, HA ignores any conditions etc. right? And it would still update the last_triggered value 🤔
Yeah, it's Tuya based, and I spent the time getting localKey etc and trying to communicate, but the thing is, it's some special thing, because the vacuum doesn't actually function properly in any normal Tuya app (Smart Life / Tuya Smart), only in the Lenovo Cleaner T1 Pro app
Trying to communicate with it gives you a lot of encoded stuff with json decode errors
Like Smart Life and Tuya Smart can't get the vacuums battery, current state or anything, can only start/stop it. Meanwhile the Lenovo app does everything including map.
It's an Lenovo T1 Pro, which is kind of a re-branded Prosenic M7 Pro. But it's hard getting good info on those.
well it looks like there's not much
If you have mqtt, you can publish the information to a topic from the automations, then make a mqtt sensor from the topic
that's probably the easiest way
there are other ways too, but they require python scripts or using the rest api
Haven't fiddled anything with MQTT before but will keep that in mind. Though as I just realized, what I could do is as I said make the manual button just trigger the same automation as is actually automatically being triggered. Because then HA ignores the conditions and runs it anyway, and still updates the last_triggered info.
So is there an easy way to just get a sensor template running for ONE automations last_triggered value?
nope
Ok 🙂
last_trigger timestamp yes, but not the value that was recieved
I just want the time outputted from one automations last_triggered value, and be able to nicely format it
then just use state_attr() and grab the last_triggered. Use as_timestamp() around it and then format it with timestamp_custom
Okay, I think I'm on the right track, thanks
@upper fog posted a code wall, it is moved here --> https://paste.ubuntu.com/p/nWmVWffj22/
Hi everyone, hope someone can help me. I am trying to create a template to combine my garage door opener and a smartthings contact sensor. The garage door opener is sonoff and automatically acts as a push button/momentary switch.
I have used the following code to create a 'cover'.
https://paste.ubuntu.com/p/nWmVWffj22/
I can open and close the garage door using a single arrow (the other one doesn't work) but it does not seem to update the garage door icon or other arrow to show the status of the door. I don't know where I am going wrong
binary sensors do not have a state open
only on or off
You're using 'open' in quite a few places
you also don't need to make the icon_template. Just add device_class: garage
Also, change your switch service from switch.toggle to switch.turn_on for both open and close cover
Ah ok! I will try and make the changes now. Thank you 👍
Thanks Petro! Works perfectly now
hello guys , I am still fighting with this - is it even possible to template this particular thing , would be my first question , or should I give it up?
What do the Dev Tools say that template evaluates to?
Good evening, would it be possible to help me debug a expected float for dictionary value @ data['value'] error?
action:
- data_template:
value: '{{states.fan.cgs_dyson_pure_hot_cool|int}}'
entity_id: input_number.dyson_pure_hot_cool_fan_speed
service: input_number.set_value
I would need to send a simple number to a created input_number
any advice or help where and how I can troubleshoot this would be greatly appreciated
I'd always use the Developer Tools / Template. Just paste the template in there and see what it returns.
I usually start from the state value and build to the right
Looking at your exaple, I'd try {{ states.fan.cgs_dyson_pure_hot_cool.state | int }}
thanks, did that and it returns data_template:
value: 4
entity_id: input_number.dyson_pure_hot_cool_fan_speed
or perhaps better {{ states('fan.cgs_dyson_pure_hot_cool') | int }}
once I got the template "wright", I tried it to call it in a service and there it fails
I'd start with calling it with a constant number. And then replacing by template. And I think you do not have to use the data_template anymore, just use data:
Assuming input_number.dyson_pure_hot_cool_fan_speed is an existing correct entity....
test 1: with a number it seems to work
I use the developer-tools/service to test it. select service: input_number.set_value. Entitiy input_number.dyson_pure_hot_cool_fan_speed and service data entity_id: input_number.dyson_pure_hot_cool_fan_speed
value: {{ states('fan.cgs_dyson_pure_hot_cool') | int }}
somewhere, something doesn't work as soon as I choose value: {{ states('fan.cgs_dyson_pure_hot_cool') | int }}, while this gives me the correct number in the templates
Did you do value: "{{ states('fan.cgs_dyson_pure_hot_cool') | int }}"?
just copied your full statement and tested, no luck
just turned it full off and the value is off, could it be it expects a string?
I do not know what the actual states of your entities are, but I'd experiment with the developer tools and you should figure this out.
Fails how?
always same error expected float for dictionary value @ data['value']
wait a sec, we lost the speed attribute somewhere on the way
And if you use a simple template like {{ 2 + 2 }} it fails?
entity_id: input_number.dyson_pure_hot_cool_fan_speed
value: "{{states.fan.cgs_dyson_pure_hot_cool.attributes.speed|int}}"
yes that also fails the {{ 2 + 2 }}
4 hardcoded does work
now I am lost, what's the difference between {{ 2 + 2 }} and hardcoded 4?
There should be no difference. What version of HA are you on?
Home Assistant 0.118.4 on RA PI
Hi everyone, is there a way to use a template in friendly_name of generic camera? I'm using template to tweak still_image_url, but can't find a way to alter friendly name.
Then I think you should log a bug. A lot of people have had difficulty with templates since the 'native types' stuff that they added.
May I already thank you for all the help. very much appreciated.
not sure if I am the best placed to file a bug, my programming knowledge is quite limited
You don't need to know how to program to log a bug 🙂
Just explain what you've tried and what the results were.
this said, I followed two guides and all the rest worked fine
true, but could be a user problem 😀
maybe a last test: how can I influence the value of {{ 2 + 2 }}. I just tested with {{ 2 + 2 | int }} and with {{ 2 + 2 | float }}
any other that could make sense to rule out?
You can't. The template will always return a string. HA decides how to use the value.
and you can set a string to input_number?
You should be able to tell it that you want to set it to the string '4' and it should understand that you mean the number 4.
The recent change for templates has had some side effects for some people.
The more people that report issues, the better the devs can understand the problem.
ok, will do. Will recreate same in my test environment 0.118.2 and see if I have the same behavior
Thank you for the help! Having quite some fun with this new solution. Once all "smart" tings are integrated, I will start to integrate my KNX. that will be the real challenge 😀
How to format this into JSON?
data_template: entity_id: media_player.alfred language: pl cache: false message: >- Kinga jest na {{ state_attr('sensor.kinga','neighbourhood') }}, {{ state_attr('sensor.kinga', 'distance_from_home_km')}} od domu. service: tts.google_say
I'm having most problem with the message part
It doesn't read the values at all
Updated age sensor
https://community.home-assistant.io/t/age-of-a-person/225241/9
@ebon drift , you should now use data: and not data_template: . I'm not saying this is the problem though
This YAML is woring for the HA automation, but I don't know how to format the message for a JSON in NodeRED
Because all that I need to pass as JSON there is the message part
The rest is done by the node
then maybe it is more a question for #node-red-archived
I'm having trouble coming up with a json_attributes_template for this mqtt sensor : https://paste.ubuntu.com/p/stz5N5xN33/
(json payload included)
The attributes are simply not showing up in the sensor.
your json_attributes_template returns an array. I think it should return a dictionary.
Does it work if you try with "{{ value_json.channel[0] | tojson }}"
?
yup it does
well...in a separate sensor
@deft timber and your suggestion also works in the original paste
I'm beginning to think i'd better make a sensor per array item
or maybe you can try smth like json_attributes_template: "{{ {'channels': value_json.channel } | tojson }}" ?
that way your json_attributes_template does return a dictionary
lemme test that
with 1 element : channels, that itself returns an array
That looks promising enough !
@sly urchin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/gbP8F77vJt/
I'm having issue with this template:
value: >
{{ (trigger.from_state.state | float - trigger.to_state.state | float) | round(2) }}
entity_id: "{{ input_number.ashley_weight_difference }}"```
With more info above, any ideas much appreciated
Hi, does someone know if one could use state attributes in History Stats? I mean like, currently I have a history stats sensor, which check how long has the state been as playing on my PS4, but I'd like to have two different sensors, divide them with media_content_type being game and app. Or rather, to have two sensors, both state=playing + media_content_type=game and state=playing + media_content_type=app.
Let me know if I should ask this on some other channel
I think I might have got it; create a new sensor, such as:
- platform: template
sensors:
ps4_media_content_type:
friendly_name: "PS4 - Media content type"
value_template: "{{ state_attr('media_player.ps4', 'media_content_type') }}"
...and then create a History Stats sensor based on this new sensor/entity
You do look like you've got it...
yup, appears so :)
@sly urchin, strange, it says that trigger.from_state.state | float and trigger.to_state.state | float are strings. Which can not be... No idea why. Bug? Could you try with float(trigger.from_state.state) instead, for testing purpose ?
I believe I've tried this along with many other tweaks but I will check this one now, thanks
@sly urchin make a persistent_notification and output the results of trigger.from_state and trigger.to_state
the | float should always convert it to a float regardless of the results of .state
or call the service system_log.write
- service: persistent_notifiication.create
data:
title: From State
message: "{{ trigger.from_state }}"
- service: persistent_notifiication.create
data:
title: To State
message: "{{ trigger.to_state }}"
You'll get 2 notifications with the objects in question
Also, how are you firing the automation? If you're pressing the test button, that automation will not work.
No, I'm using a counter and incrementing the value, so it should return the difference of 1.
Thanks I'll try this now
that's cool. I placed a comment in the thread, too, suggesting some thought around HA having more instrumentation on the people it serves. It's a little surprising to me that for all of the fine-grained entities and attributes we have to work with on devices, there's surprisingly little to work with on the people that our systems and devices are meant to serve.
Hi there !
I'm trying to sort a list of entities by value (int).
Right now i have this, but it doesn't sort by int value but by string (100 is BEFORE 80) :
{{ "group.zigbee_batteries" | expand
| sort(attribute='state')
| map(attribute='entity_id')
| list
}}
someone told me to map(attribute=state)|int|sort but that would give me a list of values, not a list of entities.
Is there any way to do this ?
I managed to get the notifications to only contain the value necessary, but when writing them to the input_number it logs an undefined error, any ideas?
Error rendering data template: UndefinedError: 'input_number' is undefined
Be carefull, in the service call you wrote from_state.attribute.weight instead of from_state.attributes.weight (missing s at attribute)
and you miss the template parenthesis for entity_id:
entity_id: "{{state_attr('input_number.ashley_weight_difference', 'entity_id')}}"
you also miss quotes for the template of the last service call (notify.mobile_app_ashley_phone)
And you miss the "s" at the end of state, it should be states.input_number.ashley_weight_difference. Or states("states.input_number.ashley_weight_difference")
message: "lost {{ states.input_number.ashley_weight_difference }}kgs this weigh in."
@sly urchin there's a bunch of errors in that
Also, just to forewarn you, there's a chance that the automation moves too fast and the weight_difference is older than the previous calculation
Thanks but I still get the same error, automations reloaded for sure
Error rendering data template: UndefinedError: 'input_number' is undefined
input number is set at 19.3
it's not coming from this automation
input_number is not referenced in any template.
No i've manually set it incase that was what was causing undefined
you need to explain what you're doing better
data_template:
value: '{{ (trigger.from_state.attributes.weight | float - trigger.to_state.attributes.weight | float) | round(1) }}'
entity_id: input_number.ashley_weight_difference```
input_number not defined is a templating error
yet you aren't referencing an input_number in these templates
you're referencing an input_number entity
you're confusing the 2
1 is a variable name "input_number"
the other is an entity inside home assistant, which happens to be a domain of 'input_number'
Okay I get what you're saying but not sure how would I go about writing the result of that template to the input number?
how are you editing this automation?
we have to step back because you're doing something wrong somewhere else
and you're focused in this area which the error is not located
you're right I must have read the previous log when slamming down your code, apologies, i just got a notification so it seems to work. Did you just edit the formatting in your version?
Thank you @mighty ledge 👍
could someone help me translate a date format into a tts readable format, eg. 2020-11-30 00:00:00 into "The 30th of November Twenty Twenty" ?
Format it using strftime notation “The %e of %B 20 %y”. But the “th” is not possible that way
@marsh lynx
{% set t = as_timestamp('2020-11-30 00:00:00') %}
{% set d = t | timestamp_custom('%d', false) | int %}
{% set suffixes = {1:'st',2:'nd',3:'rd'} %}
{% set d = d ~ 'th' if 11 <= d <= 13 else d ~ suffixes.get(d%10, 'th') %}
The {{ d }} of {{ t | timestamp_custom('%B 20 %y') }}
OMG
I didn't expect someone to practically do it for me, thats awsome. Thanks @mighty ledge . I just assumed someone would just point me to a docs page or something, lol. Thats the typical response I'd expect in discord rooms. 😄
if the format was 2020-11-30T15:59:02.549354+00:00, what would be the best way to do the same thing, could I strip everything to the right of the "T" or would there be a better way? I'm not sure if this format is a valid "timestamp" value.
@marsh lynx just change the false to true in the 2nd line
the same template will work
the difference is, you now added a timezone to it
so we don't have to assume UTC
thats great, it works either way, but no need to change the template makes it even better.
2020-12-01 16:15:00 seems to translate to "The 0th of None" - have i made a typo?
Can anyone take a look at this automation.. it used to work great until i updated to the new template version.. now it doesnt work and I included the error. I think its a simple fix just adjusting the template to the new format.
this is basically the error: Error rendering data template: UndefinedError: 'trigger' is undefined
are you testing it by hitting "execute" or something similar?
and what is the "new template version"?
if you're manually executing the automation, there is no trigger, and you'll get that error
you should also change data_template: to data: while you're there
Hey all, how can I parse the trigger data for an automation as JSON and read a property? The following shows me a JSON object, but I can't figure out how to access it inline (I'd like to notify trigger.event.data.my_property, for example)
- service: notify.mobile_device
data:
message: 'data: {{trigger.event.data}}'
Nevermind, it seems like it's already parsed and I was reading a property that didn't exist 🤦♂️
your right that i was hitting the execute button. however the automation doesnt run on its own either
and i was just referring to the changes they made to templates in .118
@boreal fiber your first trigger never works
The one with three entities?
yeah
binary_sensors only have an on/off state
the cover would still work
but not the other 2
ah your right! i recently changed those from sensors. i will change that and keep testing. since nothing seems wrong with the syntax or templating
that seemed to have worked. thanks!
fresh pair of eyes sometimes
that's all it takes!
Can someone tell what the Home Assistant sensor is that tracks who enters a zone. I want to be able to do a template that triggers the google TTS service to welcome home the person/s that entered the zone. I am correctly picking up users entering the zone I just want to use the person attribute name in the template code.. IE Welcome home "Person"
The zone trigger can do that
If you look at the docs linked in the channel topic it tells you what the template variables are for that trigger
Thankyou for telling me exactly where to look 🙂
Where to start with a template that displays what a sensor's value was an hour ago?
I don't think you can do that 😦
Oof. See, I can see the forecast for road condition in a REST response, but not the current condition. So the previous hour's forecast would be a highly likely current condition. This data updates every five minutes.
An SQL sensor should be able to pull it from your database. https://www.home-assistant.io/integrations/sql/
Will take a look
@wary horizon Or you set up a helper like an input_text where you store the previous value with an #automations-archived
Indeed, an sql sensor is a good idea:
select state from states where entity_id = 'your_entity_id' and last_changed < addtime(current_timestamp(), "-1:00:00") order by last_changed desc limit 1;
But you will be able to get the state only, not the attributes
That's fine I can make a separate template sensor for that item only
can i use logical operators in templates?
eg: value_template: "{{ is_state('light.bedroom_ceiling', 'on || off') }}"
or would this syntax be correct?
{{ is_state('light.bedroom_ceiling', 'on') or is_state('light.bedroom_ceiling', 'off') }}
Second would be correct, but does not make any sense, since it only has those 2 states it will always be True
well, there is also unavailable
"{{state('light.bedroom_ceiling') in ['on', 'off']}}" is a shorter variat,
perfect, thank you
@rugged laurel that shorter one doesnt work for me. it makes the template switch unavailable. my longer version seems to work, however
There is a typo there state( != states(
oh, i missed that
or {{ not is_state('light.bedroom_ceiling', 'unavailable') }}
BTW, how do you create an inline code segment here?
1 ` instead of 3
Ah, thanks!
I thought I got the hang of the Jinga2 indentation nuisance but I cant figure out what I'm doing wrong
can I paste an image here?
if indentation is your issue then paste.ubuntu.com would be better
@marsh lynx 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.
Remove all of the entity_id entries. That option has been deprecated.
And the device_class error should be pretty self explanatory
@languid trellis posted a code wall, it is moved here --> https://paste.ubuntu.com/p/CPCPdq6DTq/
thats the thing, the vscode error markup claims this is an error, but the HA docs show that "problem" is valid
Hello. Can anyone tell what is wrong with this template:
https://paste.ubuntu.com/p/CPCPdq6DTq/
@hollow bramble https://www.home-assistant.io/integrations/binary_sensor/
Oh, thats binary_sensor. 😛
@languid trellis too many ( and not enough )
no, it renders a number when I paste that template
What is the problem you are having?
@fossil venture hm, it worked before I added filters:
You can't put filters directly on template sensors.
https://www.home-assistant.io/integrations/filter/ https://www.home-assistant.io/integrations/template/ they are different integrations
Oh just saw that, looks like a jinja to ESPHome mashup. 🙃
Can I use the filters" on the template's output in some way or do I have to recreate filter functionality within the template?
You can make a filter sensor entry that references the template sensor you've created
@hollow bramble how do I reference the template in the sensor? Tried to search but found only templates referencing sensors.
You reference the template sensor with its entity_id
What type of sensor template would I use to set the state for my vacuum (Charging/not charging)?
I was looking for something like this
value_template: >-
{%- if state_attr('vacuum.albertinne', 'Charging') %}
false
{% else %}
true
{%- endif %}
binary_sensor
You would just need "{{ is_state_attr('vacuum.albertinne','Charging')}}"
@hollow brambleAh! .... and then it sets on/off?
It doesn't "set" anything, but it will automatically change the state of the binary_sensor based on your vacuum's charging status
So like this:
value_template: "{{ is_state_attr('vacuum.albertinne','Charging')}}"
Are you sure the state is "Charging"? I didn't think that was a state for vacuums
The state is "Docked" iirc.
True 🙂
It's also likely docked (lower case)
for sure 🙂
It seems I still have to do a ha core restart to update the binary_sensor. Correct?
That should be your default, it's way better!
I know...
Try googling "Home Assistant utløser not working"....
What am i looking for there?
It was a joke...
😉
Why is it that
{{ states.vacuum.albertinne.attributes.status }}
{{ states.vacuum.albertinne.state }}
returns
Returning home
returning
That’s what the integration provides?
status != state
In the Norwegian translation it probably is the same
So both these values kind of has the same meaning, but I would have to be careful to use the correct value when templating, though
BTW: What would you guys use to save the state for eg. light (on/off). Use a binary_sensor for that too? I would use this to check if several lights (in several groups) are lit or not, and displaying it´s status in a button in lovelace
Why not just use the state of the light?
I have three groups of light (for now)
Groups also have states
.. and some of these groups are dimmables
They are still either on or off
which mean I canot turn them on at brightness: 5, because then all the lights don´t turn on sufficiently
@earnest cosmos posted a code wall, it is moved here --> https://paste.ubuntu.com/p/JMg9CJHc4y/
- service: homeassistant.turn_on
entity_id: group.lys_grunnbelysning_dimbare
data:
brightness: 50
- delay: 0:00:03
- service: homeassistant.turn_on
entity_id: group.lys_grunnbelysning_dimbare
data:
brightness: 5
all that information is in the link the bot posted, no need to repost
That´s why i ended up calling this script to make sure all the dimmables are lit, then dimmed down
Well your first mistake is using homeassistant.turn_on instead of light.turn_on, and your second mistake is using a group instead of a light group
This script works, though 🙂
But what is it accomplishing? You're saying setting them to brightness: 5 doesn't work?
Anyway the dimmer thing is coming to play if I use the physical dimmer on the wall at a too low level too
I am telling you this because it does not seem to work properly just turning them on using group on/off
so I have to turn these on by this script at some brightness in order to have them all lit, then dim them to desires starting brightness.
I still don't understand why that would be necessary. It sounds like a broken integration
Two things here: Get the state of the light groups, and the fact I cannot turn the dimmable spot lights on at too low brightness.
That's the part that doesn't make sense.
If I do that (even when using the dimmer on the wall) not all the light bulbs are lit.
To accomplish this I must dim up the lights
What is "too low brightness"? What do the entities report as the state/brightness?
It´s not the entities or the Fibaro dimmer.
It´s the lights itself that cannot turn on properly when the dimmer is sett at the lowest value
they need more power to make all six spots to turn on at the same time
therefore I have made a work-around to have all 6 LED spots in the cieling turn on by the script
and at a brightes that gives all six spots enough power to lit
That is (as far as I know) the reason turning on light groups will not work. I can, however check the state for the groups, and that idea, @hollow bramble might solve my initial issue
Kind of complicated to explain here, though. But i need to turn those spots on at brightness: 50 to get them all lit
@azure whale posted a code wall, it is moved here --> https://paste.ubuntu.com/p/DRGjqkwnw3/
@azure whale where did you get temperature_f from? Your json does not contain that key. Your value template should be "{{ value_json.data.val }}"
______________________value_json___________________________
/ val \
/ | \
/ V \
{"up":22255,"id":"2","data":{"type":"temp","val":67.77499,"pin":4}}
^---\___________data_____________________/
{ } make up a dictionary. To accesss items in a dictionary you use .xxx or ['xxx'].
value_json is a dictionary, it contains 3 keys, up, id, and data. data is a dictionary, it contains 3 keys type, val, and pin.
so... value_json.data.val or value_json['data']['val']
items in a dictionary are noted by "KEY":"VALUE" and separated by commas
solid ascii work there
I took a class in ascii art
seriously? ha
so... can I template templates?
I have 7 fans and I kinda don't fancy doing this by hand https://paste.ubuntu.com/p/np2P8Jgqjk/
Not really, no. Though you could clean some of that up a bit. Are you planning on having only one speed control for all of your fans?
Maybe you can look at yaml anchors
I personally use it in the following scripts, to avoid repeating the url, headers, ... : https://paste.ubuntu.com/p/MNKGqGDnW4/
would that have to be done in the same .yaml file, or a package?
definitely cannot do that with yaml anchors
only if the templates were identical
then you can use anchors
No, but kinda. You can write a template to generate your template sensors. Here's an example: https://github.com/dale3h/homeassistant-config/blob/b040f17bc66a47f3f884d8360ed225d7f3a3e8f3/packages/network_devices.j2 -- this is a template I used to use to generate Template Sensors for each of my network devices so that they'd have a state of online or offline (instead of on/off), as well as an icon to denote that state.
@royal rampart Also, I want to say that your templates are the prettiest I've seen in a while. Your formatting is 💯!!!
they could be optimized a bit
"{{ not is_state('switch.dining_fan_off', 'on') }}
and
"switch.dining_fan_{{ states('input_select.speed') | lower }}"
I agree, but you have to admit his formatting is gorgeous. 😉
He actually uses spaces and doesn't write the result at the end of the line... makes it %100 easier to read
Exaaactly. And he uses is_state instead of relying on the states collection.
And makes use of the folded block syntax.
Is there an equivalent to this template:
{{states.sensor.picnic_delivery.attributes.delivery.window_start}}
In the “other” format eg. {{state_attr('sensor.picnic_delivery','delivery','window_start')}} <— That doesn’t work as it’s too many arguments...
{{ state_attr('sensor.picnic_delivery','delivery')['window_start'] }}
Ah that’s perfect! Thank you, I was trying [0] etc. but didn’t even think to try the actual name 👍
hi guys , I am fighting with this automation for some days now and I think that my actual question in order to solve my issue is , is it possible (without using python scripts) to manipulate a YAML list into adding and removing entries dynamically based on a multi-line template with if conditions ?
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
@mighty ledge so for example if I had a telegram bot inline keyboard which in order to prin keys it uses a list
would I be able to do this dynamically ?
say print a number of buttons in some conditions and another in some other conditions ?
because in all my attempts I get either syntax error because I put the dashes inside the multi-line template which is obviously wrong
or if I put the dash outside and template below if the condition goes to false then the dash is left empty (without a button) thus resulting in an error fro mthe telegram api
With the recent typing changes, all you need to do is return a comma separated string.
The dashes Are YAML notation only
@umbral pond
@umbral pond if you share your code i can hlep...
Aw shucks, you're going to make my head swell. You can put my formatting down to a lot of Google and being a Dev as a day job. Will have to try those shortcuts tho.
I won't show you any of the config from our old house lol
@mighty ledge i am trying to re-syntax it because after so many attempts and tries it doesn't look as I describe , bear with me
@mighty ledge these are my last 2 main variations:
of course i've tried other syntaxes with | instead of > in case it made a difference
and removing whitespaces from various points by putting dashes here and there in next to the % symbols
in case that was the problem
the use case is that input_booleans will never all be on at the same time , so there may be buttons in the keyboard needing to be ommited and that's where the problem starts
for all booleans on , the 2nd link , seems to work (and pass validation tests too of course)
Yeah, so... I can help with that exact template but it won't get what you want with other templates
you'd have to edit it yourself and this will probably be above your head
i understood the second 'above my head' part , that probably it will be code difficult to understand , but what do you mean it won't get what I want with other templates?
@mighty ledge posted a code wall, it is moved here --> https://paste.ubuntu.com/p/fjvbbShGGF/
I tried to make it easy so you'd understand the code
you can change the last line to {{ ns.items }} too and it will work.
granted, this only works in 0.118+
cool , I kinda understand how it works already , one question tho. the if...else logic.
the way it's typed right now , it checks if one is 'on' at a given time , where there are cases that test1 will be on , test2 off and test3 on again , so consequently I 'd need the first button and the third on the keyboard.
yeah, but you can just remove the elif and add and enif
endif
{% if %}... {% endif %} {%if %} .. {% endif %}
ah yes of course , just making sure of the edits I have to make
and making sure I don't get anything wrong
instead of {% if %} {% elif %} {% elif %} {% endif %}
also where would I add the - dash that is required for the inline_Keyboard: list to be built ?
i think the inline_keyboard should be syntaxed:
inline_keyboard:
- 'test1: /test1'
- 'test2: /test2'
etc
ok, so it's definitely a list and not a set of keys
i.e. when you write it out non-dynamically it looks like what you posted
yes that was my main issue all along , in fact , that I couldn't put the dash anywhere "safe"
the dash is for yaml notation
the notation for objects is a list notation
inline_keyboard: ['test1: /test1', 'test2: /test2']
that is identical to what you wrote
yaml interprets both without a problem
to make it work with jinja, that's the format you should use with the new typing
I see , ok good to know! one less thing to worry about
you don't need the | join(', '), it should work without it
You'll need a condition that checks for an empty list and to not fire it off
It didn't like that
Received invalid fan is_on state: True. Expected: on, off
Received invalid fan is_on state: False. Expected: on, off
Interesting! I guess that’s a new thing since adding native template types.
I actually looked to see if there was ternary operators or bash style foo && x || y
but, time to start looking at lovelace... cos my ui is a bombsite... tracking aircons, dynalite, switches, solar, ups, printers... so much stuff lol
@royal rampart if true/false doesn't work, that's a bug and it should be reported linking the integration.
the moment when you head over to #templates-archived because you cant remember a jinja filter for ansible 🤣
Borderline abandoning that method, if I turn the fan on it goes to high, if I change the speed it turns off
the template fan or the simple template?
@mighty ledge posted a code wall, it is moved here --> https://paste.ubuntu.com/p/qpP9pn4Pgb/
System log documentation (https://www.home-assistant.io/integrations/system_log/) contain:
data: title: Something bad happened message: '{{ trigger.event.data.message }}'
It doesn't work any more, probably because trigger.event.data.message become an object.
I found a way: service" in trigger.event.data.message[0]. Is any better way convert object to string?
nope, that's the best way. The result should be that anyways
{{ trigger.event.data.message[0] }}
How to update documentation?
Well, message should always be a string regardless of it's contents. Before changing the docs, might want to create an issue.
will create issue
@mighty ledge also, I've excluded you from the code wall check
Role exclusion or just petro?
Thanks!
I did the lazy way of checking. I should really use role based check.
is there a way to changethe icon from on and off switch to a toggle in switch.yaml?
https://www.home-assistant.io/integrations/switch.template/ Have you looked through here?
yes when i follow that i have a on and off button i want it to be 1 toggle button (like the rest of the switches that work with ha)
template switch will do that
you still have to define those values
otherwise it doesn't know what to turn on or off
to be clear, it creates a second switch with a dynamic icon of your choosing. You hide the first switch in the background.
How do i make a switch to just trigger an alexa routine?
Do i need an input boolean to trigger during the on part?
Oh i just need a bool with the switch!
Im trying to use a template in a condition in which i want to check if android tv attribute 'appname' is: Netflix but im not sure if value template is right. I cant seem to find how to do this right on the template pages https://hastebin.com/fuwewiheme.yaml
Take out the if from the template and you should be fine
{{ is_state_attr('media_player.android_tv', 'app_name', 'Netflix') }}
Fan one
I have a noob question. I have a custom entity, which uses a value template. Where do I actually put it? I initially though it would go into sensors, because it is supposed to be a sensor, but IntelliSense warns i need a platform. Here's my entity battery_consumption: value_template: '{% set batter_cons = sensor.powerwall_battery_now | int %} {% if batter_cons > 0 %} {{ batter_cons | int }} {% else %} 0 {% endif %}' device_class: power unit_of_measurement: W
Did you read the template sensor docs? https://www.home-assistant.io/integrations/template/
UGH, I was reading the wrong Template docs (automation templatng)
Yeah there are quite a few pages with that heading. It can get confusing when you're starting
Lol, true. every time I venture into a new part of HA, it is a windy path
Eventually you'll get used to it
It has a steep learning cliff.
I'm a seasoned dev (15+ years professionally), I cant imagine what it is liek for someone not used to having to navigate obscure API references
If you need docs for integrations it's a pretty straight forward path. If you need docs for any other part of HA.... god speed
Indeed, the past 12 months of HA improvemnts have drastically improved the "normal" user experience.
Did you recently comment on a Reddit post about HA, Lance?
I won't say when or which post, to allow you to have some privacy 😄
nope (I'm Lancelot Software on Reddit), but I have seen a lot of buzz about Core 1.0 making the rounds on Twitter
It's interesting seeing different people's views on difficulty/complexity. It's obviously not a plug and play tool but people all pick it up at varying speeds.
Even more interesting to me is that some non-devs take to it fairly quickly while some devs struggle.
You probably saw a discussion along those lines already if you spotted the v1 chat.
That is interesting, but I'm not too surprised. Devs can sometime get stuck in a rut of a certain way of thinking.. especially devs around the 5 year mark. They'll tout a specific language/platform as the best in the world and everything needs to be done with that thing (I was guilt of that too). then as you gain more experience, it becomes less about a thing and more about the concepts/approach.. you belive in 'the right tool for the job'.... not to go off on a tangent, my point being that the single-mindedness resticts you taking on new ideas
You have me worried now though. I'm just coming up to the 5 year mark... albeit with fewer of the traits you described 🤣
Think I've figured it out, I don't need to check the state of the input select just the variable called "speed"
Yes, I posted the templates above that used the speed variable
Ah sweet, I didn't notice, sorry. This is what I got currently so I'll move to that 🙂 https://paste.ubuntu.com/p/SbPwMwKTCQ/
Yeah it got moved into that link
just trying to make it go to the last set speed when I turn it on too 😄
having mixed results
argument of type 'NoneType' is not iterable...
brb figuring out what I broke
Did you remove the input select?
If you did, just replace it with a list. [‘High’, ‘Medium’, ‘Low’]
if speed in [‘High’, ‘Medium’, ‘Low’]
Sorry on mobile
https://paste.ubuntu.com/p/hqCdm4nCZv/ is what I got
sorry, I got interrupted by actual work lol
Do you actually have the input_select.speed?
Your speed template is wrong too
Unless your switches don’t have a state
And if they don’t have a state, you need to a second service to set the selection for the input select
umm, I'm just using a default widget in lovelace if that's what you mean? the one it chose
- type: entities
entities:
- entity: fan.dining_fan
the fans are rendered as 4 switches each with on, off. if you switch fan_medium to on it turns the other 3 off
"fans by dynalite"
Ok then you don’t need the input select at all
oh then nevermind 😄
{{ ([ states.switch.master_fan_high, states.switch.master_fan_medium, states.switch.master_fan_low ] | selectattr('state', 'eq','on') | map(attribute='object_id') | first).split('_')[-1] | title }}```
wow, where's that go?
Man, that took me a while to format... coding on mobile sucks
Anyways that’s your speed template
yes, mobile sux (I use my phone almost exclusively to ssh into things, or type on slack to pretend to work)
but thanks for the help, it's not easy guessing what I've got and typing on mobile
I still screwed something up. I might wait till you're not on mobile and try again 😄
I just noticed your turn on is turning the dining fan on high though
yeh I'm working on the dining room (As I'm itting under it) don't worry I've been translating since I noticed you were working on master 😄
Error rendering data template: TypeError: argument of type 'NoneType' is not iterable
Oh, I just found you in the forums, seems you've been fighting fans for a while @mighty ledge
they aren't that bad, it's just everyones hardware is different