Lovelace: Cannot format template sensor entity as relative time

@pplucky ok is working ok. I’m missing the Bearer in the token.

Can you share your script for the log… i i think is the only thing missing for now :stuck_out_tongue:

Can you share or lovelace example?

Good, then.

If you’re referring to service: notify.samsung_washing_machine_log_file, it is only a notify entity to write events in a file:

notify:
  - name: samsung_washing_machine_log_file
    platform: file
    filename: samsung_washing_machine_log_file.txt
    timestamp: True

to show something like this:

Honestly I had to change my automations a bit, when I understood that my log was incomplete (I suppose because different sensors are changing state simultaneously and not all were being written in the file).

My only purpose is to try to write a log to understand why sometimes my drum cleaning warnings are coming earlier in HA than in SmartThings app (it is the only thing not working 100% right now).

If you’re still interested, I can share my latest set of automations.

Nothing too fancy, just an entity list.

Is this method still working?

Im pretty sure ive done it all correct but im not getting anything from the sensor smartthings api.
So wanna just make sure if this acualy still works or not.

My token and device id should be correct so just trying to make sure om not banging my head on the wall for nothing. Ill add my change that made it work for me


### 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: Bearer !secret samsung_token

Yes definitely working…

Are you using the sensors that the integration inside hassio has creaded when configured? (ive done that together with your code.)

Only part beside that is if im using the wrong device id from the developers page. How did you get your korrekt id?

Dubble checked everything with the Curl command aswell that im using the right info with token and deviceid. So its just a question about if you are using The built in Intergration in homeassistant for smarthings. Like another one above my api stays empty. Ive tried the wasers deviceid and network id. Ive allso Created a new tolken and tried against that when it has everything enabled.

For all that i can see ive done eveything by the book. As i said ive allso both logged in to developers page and checked the Device id and used the curl that other done and tilled in the token together with your code. And allso renamed the washer to fitt the sensors name…

Got any suggestions or a bone to throw my way on what might be wrong?

for anyone stuble on to this code and do not get it working

this part:
Authorization: !secret samsung_token

Make sure its not just the samsung token alone in your secret, but “Bearer yourtoken”

Hello.

The device ID I use can be found within SmartThings Device list page, click the washing machine corresponding line and then look for lines started with di or pi:. Device ID should be the long string after

I’m actually using a mix of both.

Some are coming from a rest sensor which calls the Smartthings API (like program, spin level, rinse cycles or water temperature), while others are coming from the built-in integration in HA for Smarthings.


These are the sensors I get from the UI integration (btw, my device in Smartthings is simply named ‘Washing machine’, which is the beginning of each entity_id name (after the domain).

That’s a fact, maybe I could’ve mentioned it

If you run in command line:
curl -H “Content-Type: application/json” -H “Authorization: Bearer token” https://api.smartthings.com/v1/devices/DEVICE_ID/status

do you get any kind of json as a result? I get, even if my machine is offline (although of course some data are from the last time it has been online.

Please let me know how it goes.

1 Like

Thx for your answer m8.
All that was needed for me was to out in Bearer before the token in either the secret part or in your sensor for the smart api. Id add that to the code above so others dont have to get the same problem. I saw one Other above have the same problem.

If I have the washer and the dryer, what would I need to add / change to track and control both?

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.