Lovelace: Cannot format template sensor entity as relative time

Hi,

I’m struggeling to get this to work.
I have a samsung developers account and got the api.
In postman i did a GET request https://api.smartthings.com/v1/devices
under the authorization tab i select bearer token and filled this token as secret in my secret yaml file.
to test i pushed send and got as result and saved it to my collection in postman.

[partial copy and paste]
{
“items”: [
{
“deviceId”: "d5026f8e-9ba7-
“name”: “[washer] Samsung”,
“label”: “[washer] Samsung”,
“manufacturerName”: “Samsung Electronics”,
“presentationId”: “DA-WM-WM-000001”,
“deviceManufacturerCode”: “Samsung Electronics”,
“locationId”: "df136aef-c3ef-
“ownerId”: "6df67325-2414-
“roomId”: "9dec5879-ece4
“deviceTypeName”: “Samsung OCF Washer”,
“components”: [
{
“id”: “main”,
“label”: “main”,
“capabilities”: [
[ end partial copy and paste postman bearer token]

I don’t get the sensors smartthings.api as shown in you screenshot. i get:

If i take your code and copy it into Development->templates
I get the error:
UndefinedError: ‘None’ has no attribute ‘main’

So from the section:
### Template sensor for Maq Lavar number of cycles until drum cleaning is required ###
wasmachine_cycles:

until:

  ### Template sensor for information taken directly from SmartThings API ###
  washer_consumption:

in adition i checked the resouce link in platform rest: and this gives me i asume a good responce hence the fact i get all data from the waschingmachine.

I’m totaly out of clues how to proceed further
any pointers would be verry nice!

Kind regards

First, make sure your sensor is set like this:

### Sensor to directly call Samsung Smarthings API ###
  - platform: rest
    name: 'SmartThings API'
    resource: https://api.smartthings.com/v1/devices/your_device_id/status
    authentication: basic
    scan_interval: 31536000 #Update automatically once a year, as it is supposed to be updated from automation only
    value_template: "{{ 'SmartThings API data' }}"
### JSON attributes can only be extracted for JSON first level attributes ###
    json_attributes:
      - components
    headers:
      Content-Type: application/json
      Authorization: !secret samsung_token

And then make sure your secret contains the word Bearer followed by a space and then the token itself, as described below by @Jimmy_Berglund:

I would be surprised if it didn’t, because that’s caused by the fact that attributes in sensor.smartthings_api are not being filled.

Testing it successfully in postman only means that your token is OK and returning data, but it does not mean HA is being able to do it the same way.

Once you maintain the token properly in secrets (as per above) and restarted your HA instance afterwards, from Developer Tools / Services, run service homeassistant.update_entity in YAML mode like this:

service: homeassistant.update_entity
data: {}
target:
  entity_id: sensor.smartthings_api

This should fill the attributes of your sensor and allow this to work as described.

i 'm not a programmer so i followed this site:

to proceed with postman.

I guess bearer token could be the problem but i cant seem to understand how this is done.

I dit the Get request and saved it to my collection in postman. after that i went to the TAB
authorisation and selected for type: Bearer Token.
I had to fill in the token i got from samsungsdevelopers page and did a send request and got the result as partial shown in my previous post.
Also saved this (upper right corner).

Could you explain what the proper procedure is for bearer Token?

Many many thanks for your quick reply !

kind regards,

Please check my updated answer above.

In terms of template sensors, they are now a bit changed to avoid template errors:

template:
  - sensor:
### Template sensor for information taken directly from SmartThings API ###
      - unique_id: washer_program
        name: "Washer Program"
        state: >-
           {%- if state_attr('sensor.smartthings_api', 'components') and states('switch.washing_machine')|lower == 'on' -%}
              {{ state_attr('sensor.smartthings_api', 'components')['main']['samsungce.washerCycle']['washerCycle']['value'] }}
           {%- endif -%}
        icon: mdi:washing-machine
### Template sensor for information taken directly from SmartThings API ###
      - unique_id: washer_spin_level
        name: "Washer Spin Level"
        state: >-
           {%- if state_attr('sensor.smartthings_api', 'components') and states('switch.washing_machine')|lower == 'on' -%}
              {{ state_attr('sensor.smartthings_api', 'components')['main']['custom.washerSpinLevel']['washerSpinLevel']['value'] }}
           {%- else -%}
              NA
           {%- endif -%}
        icon: mdi:washing-machine
### Template sensor for information taken directly from SmartThings API ###
      - unique_id: washer_rinse_cycles
        name: "Washer Rinse Cycles"
        state: >-
           {%- if state_attr('sensor.smartthings_api', 'components') and states('switch.washing_machine')|lower == 'on' -%}
              {{ state_attr('sensor.smartthings_api', 'components')['main']['custom.washerRinseCycles']['washerRinseCycles']['value'] }}
           {%- else -%}
              NA
           {%- endif -%}
        icon: mdi:washing-machine
### Template sensor for information taken directly from SmartThings API ###
      - unique_id: washer_water_temp
        name: "Washer Water Temp"
        state: >-
           {%- if state_attr('sensor.smartthings_api', 'components') and states('switch.washing_machine')|lower == 'on' -%}
             {%- if (state_attr('sensor.smartthings_api', 'components')['main']['custom.washerWaterTemperature']['washerWaterTemperature']['value'])|int(0) > 0 -%}
                {{ (state_attr('sensor.smartthings_api', 'components')['main']['custom.washerWaterTemperature']['washerWaterTemperature']['value'])|int }} °C
             {%- else -%}
                {{ state_attr('sensor.smartthings_api', 'components')['main']['custom.washerWaterTemperature']['washerWaterTemperature']['value'] }}
             {%- endif -%}
           {%- else -%}
              NA
           {%- endif -%}
        icon: mdi:washing-machine

i guess i’m doing it wrong.

this is in my yaml file and it is exactly the same as you pointed out.

Sensor to directly call Samsung Smarthings API

  • platform: rest
    name: “SmartThings API”
    resource: https://api.smartthings.com/v1/devices/d5026f8e-etceteraxxxxxx/status
    authentication: basic
    scan_interval: 31536000 #Update automatically once a year, as it is supposed to be updated from automation only
    value_template: “{{ ‘SmartThings API data’ }}”

    JSON attributes can only be extracted for JSON first level attributes

    json_attributes:
    • components
      headers:
      Content-Type: application/json
      Authorization: !secret samsung_token

in secrets yaml i have:
samsung_token: Bearer 1234567890abcdef

i did a restart, and called the serevice update.

it wont give my the attributes,

In the core error log:
Logger: homeassistant.helpers.template_entity
Source: helpers/template_entity.py:356
First occurred: 12:18:36 (3 occurrences)
Last logged: 12:18:36

  • TemplateError(‘UndefinedError: ‘dict object’ has no attribute ‘washerMode’’) while processing template ‘Template("{{ state_attr(‘sensor.smartthings_api’, ‘components’)[‘main’][‘washerMode’][‘washerMode’][‘value’] }}")’ for attribute ‘_attr_native_value’ in entity ‘sensor.washer_program’
  • TemplateError(‘UndefinedError: ‘dict object’ has no attribute ‘custom.error’’) while processing template ‘Template("{{ state_attr(‘sensor.smartthings_api’, ‘components’)[‘main’][‘custom.error’][‘error’][‘value’] }}")’ for attribute ‘_attr_native_value’ in entity ‘sensor.washer_error’
  • TemplateError(‘ValueError: Template error: as_timestamp got invalid input ‘’ when rendering template ‘{% set rem_h = (as_timestamp(states.sensor.washer_samsung_washer_completion_time.state) - as_timestamp(now())) | timestamp_custom(’%-H’, false) %} {% set rem_m = (as_timestamp(states.sensor.washer_samsung_washer_completion_time.state) - as_timestamp(now())) | timestamp_custom(’%-M’, false) %} {% if int(rem_h) > 0.9 %} {{ rem_h }} hour(s) and {{ rem_m }} minute(s) {% else %} {{ rem_m }} minute(s) {% endif %}’ but no default was specified’) while processing template ‘Template("{% set rem_h = (as_timestamp(states.sensor.washer_samsung_washer_completion_time.state) - as_timestamp(now())) | timestamp_custom(’%-H’, false) %} {% set rem_m = (as_timestamp(states.sensor.washer_samsung_washer_completion_time.state) - as_timestamp(now())) | timestamp_custom(’%-M’, false) %} {% if int(rem_h) > 0.9 %} {{ rem_h }} hour(s) and {{ rem_m }} minute(s) {% else %} {{ rem_m }} minute(s) {% endif %}")’ for attribute ‘_attr_native_value’ in entity ‘sensor.remaining_time’

and:

Logger: homeassistant.helpers.event
Source: helpers/template.py:422
First occurred: 12:18:36 (3 occurrences)
Last logged: 12:18:36

  • Error while processing template: Template("{{ state_attr(‘sensor.smartthings_api’, ‘components’)[‘main’][‘washerMode’][‘washerMode’][‘value’] }}")
  • Error while processing template: Template("{{ state_attr(‘sensor.smartthings_api’, ‘components’)[‘main’][‘custom.error’][‘error’][‘value’] }}")
  • Error while processing template: Template("{% set rem_h = (as_timestamp(states.sensor.washer_samsung_washer_completion_time.state) - as_timestamp(now())) | timestamp_custom(’%-H’, false) %} {% set rem_m = (as_timestamp(states.sensor.washer_samsung_washer_completion_time.state) - as_timestamp(now())) | timestamp_custom(’%-M’, false) %} {% if int(rem_h) > 0.9 %} {{ rem_h }} hour(s) and {{ rem_m }} minute(s) {% else %} {{ rem_m }} minute(s) {% endif %}")

I dont get where i have to look to correct this.
Many thanks for your help!

The errors you’re getting are all template related and the first 2 actually seem to be caused by the missing attributes in the sensor.smartthings_api.

I suppose if you would change the sensors as described in here, at least these 2 errors would go away (even though the issue would not be solved).

The third error is another template error from entity sensor.remaining_time, which doesn’t seem to correspond to any in my config shared above, so unrelated.

Btw, what HA version do you have? Do you have any other working REST sensors?

Honestly, if you’re sure the resource link in the REST sensor is OK (double/triple-check it), that the token is also correct in secrets (no spaces, etc), I see no reason for this not to work (unless for some reason the structure of your json is different).

Can you maybe share the full json received from the postman API call (masking whatever values you think necessary/relevant, don’t touch any tags), just to check if it may something with the json format?

Or if you could do a curl call to obtain the json like this:

curl -H "Content-Type: application/json" \
     -H "Authorization: Bearer your_token" \
     https://api.smartthings.com/v1/devices/your_device_id/status

Don’t put the json directly here in the post, put it in PasteBin or something similar.

Not knowing what level you have in your logger, it might also help to temporarily raise it to debug and then run the service as before, to check if any REST-related relevant messages appear.

1 Like

@FritsOv Just out of curiosity, did you manage to fix your issue?

Sorry for not responding. Had a to go abroard for work and came back just an hour ago. I will check your post tomorrow and try again, and will give a reaction how it goes.

@pplucky

Editted this post because i got washer api working.
I changed the template as you showed in previous post but rinse_cycles, washer program etc. give me as status unavailable. that one i have to figure out. Thanks for your help and nice work.

1 Like

@pplucky Finaly got smartthings working again. And smartthings gives me one entity, [Washer]samsung is shown.

[edit]

the curl gives me json wich i reformatted with:

its a bit huge therefore i post a part of it. if it is necessery to post all i will do it but for now:
{
“components”: {
“main”: {
“samsungce.washerDelayEnd”: {
“remainingTime”: {
“value”: 0,
“unit”: “min”,
“timestamp”: “2022-10-09T18:54:45.854Z”
},
“minimumReservableTime”: {
“value”: 164,
“unit”: “min”,
“timestamp”: “2022-10-24T14:42:44.164Z”
}
},
“samsungce.washerWaterLevel”: {
“supportedWaterLevel”: {
“value”: null
},
“waterLevel”: {
“value”: null
}
},
“samsungce.welcomeMessage”: {
“welcomeMessage”: {
“value”: null
}
},
“custom.washerWaterTemperature”: {
“supportedWasherWaterTemperature”: {
“value”: [
“none”,
“cold”,
“20”,
“30”,
“40”,
“60”,
“90”
],
“timestamp”: “2022-10-09T18:54:46.820Z”
},
“washerWaterTemperature”: {
“value”: “none”,
“timestamp”: “2022-10-24T14:42:41.501Z”
}
},
“samsungce.autoDispenseSoftener”: {
“remainingAmount”: {
“value”: “unknown”,
“timestamp”: “2022-10-09T18:54:46.820Z”
},
“amount”: {
“value”: “standard”,
“timestamp”: “2022-10-12T14:10:28.749Z”
},
“supportedDensity”: {
“value”: [
“normal”,
“high”,
“extraHigh”
],
“timestamp”: “2022-10-09T18:54:45.811Z”
},
“density”: {
“value”: “normal”,
“timestamp”: “2022-10-09T18:54:45.811Z”
},
“supportedAmount”: {
“value”: [
“none”,
“less”,
“standard”,
“extra”
],
“timestamp”: “2022-10-09T18:54:45.811Z”
}
},
“samsungce.dongleSoftwareInstallation”: {
“status”: {
“value”: “completed”,
“timestamp”: “2022-10-09T18:54:45.176Z”
}
},
“samsungce.autoDispenseDetergent”: {
“remainingAmount”: {
“value”: “unknown”,
“timestamp”: “2022-10-09T18:54:46.820Z”
},
“amount”: {
“value”: “none”,
“timestamp”: “2022-10-09T18:54:45.811Z”
},
“supportedDensity”: {
“value”: [
“normal”,
“high”,
“extraHigh”
],
“timestamp”: “2022-10-09T18:54:45.811Z”
}

If you can obtain it again while the machine is working and can put it to Pastebin for instance, it would make it easier to understand why the templates are not working for you.