Lovelace: Cannot format template sensor entity as relative time

Hello.

As per Lovelace UI documentation, it is possible to format an entity as relative time, and I have been able to do it with a sensor generated automatically from a Smartthings’ integration:
image

Still then, I wanted to generate a template based on the above sensor and I cannot obtain the same output.

My template sensor configuration:

sensor:
  - platform: template
    sensors:
      maq_lavar_completion:
        friendly_name: "Máq Lavar Completion Time"
        entity_id: 
          - switch.washing_machine
          - sensor.washing_machine_washer_machine_state
          - sensor.washing_machine_washer_job_state
          - sensor.washing_machine_washer_completion_time
        value_template:  >-
                        {%- if states.switch.washing_machine.state|lower == "off" -%}
                          None
                        {%- elif states.switch.washing_machine.state|lower == "on" -%}
                            {%- if states.sensor.washing_machine_washer_job_state.state|lower == "stop" or states.sensor.washing_machine_washer_job_state.state|lower == "finish" -%}
                               None
                            {%- else -%}
                              {{ as_timestamp(states.sensor.washing_machine_washer_completion_time.state) | timestamp_custom }}
                            {%- endif -%}
                        {%- else -%}
                          Unavailable
                        {%- endif -%}
        icon_template: "{{ 'mdi:washing-machine' }}"

or

sensor:
  - platform: template
    sensors:
      maq_lavar_completion:
        friendly_name: "Máq Lavar Completion Time"
        entity_id: 
          - switch.washing_machine
          - sensor.washing_machine_washer_machine_state
          - sensor.washing_machine_washer_job_state
          - sensor.washing_machine_washer_completion_time
        value_template:  >-
                        {%- if states.switch.washing_machine.state|lower == "off" -%}
                          None
                        {%- elif states.switch.washing_machine.state|lower == "on" -%}
                            {%- if states.sensor.washing_machine_washer_job_state.state|lower == "stop" or states.sensor.washing_machine_washer_job_state.state|lower == "finish" -%}
                               None
                            {%- else -%}
                              {{ as_timestamp(states.sensor.washing_machine_washer_completion_time.state) }}
                            {%- endif -%}
                        {%- else -%}
                          Unavailable
                        {%- endif -%}
        icon_template: "{{ 'mdi:washing-machine' }}"

In both cases, I did the following in Lovelace config:

But it is not shown as relative, as I would expect (and as it does in the original sensor in which it is based on)…

Also thought of applying relative_time in the template, but it doesn’t seem to work in that sensor…

I will try setting device_class to ‘timestamp’ as per this sensor, this might work in Lovelace (as per what I’ve read)…

Thanks in advance.

Did you find a solution?

I’m struggling with the same problem - Samsung’s Smartthings integration has some weird entities and they’re difficult to work with. Not to mention the …_washer_mode with those pesky Table_00_Course_D0 values.

I’m in the same situation… this “integration/samsung” is very poor :confused:

Hello @michalzadkowski and @codedmind.

My washer integration is quite steady (just the cycle count is not 100% perfect), here’s what I have right now:

####################################################
#                                                  #
#                  Input Number                    #
#                                                  #
####################################################
input_number:
  maq_lavar_cycles:
    name: Number of Cycles
    min: 0
    max: 100
    step: 1
    mode: box
    icon: mdi:washing-machine
    unit_of_measurement: cycle(s)

####################################################
#                                                  #
#                 Template Sensors                 #
#                                                  #
####################################################
sensor:
  - platform: template
    sensors:
####################################################
#                                                  #
#            Samsung SmartThings Sensors           #
#                                                  #
####################################################
# https://smartthings.developer.samsung.com/docs/api-ref/capabilities.html#Washer-Operating-State #
####################################################
# Possible values for sensor                       #
# sensor.washing_machine_washer_job_state:         #
#  - airWash                                       #
#  - cooling                                       #
#  - delayWash                                     #  
#  - drying                                        #
#  - finish                                        #
#  - none                                          #
#  - preWash                                       #
#  - rinse                                         #
#  - spin                                          #
#  - wash                                          #
#  - weightSensing                                 #      
#  - wrinklePrevent                                #
####################################################
# Possible values for sensor                       #
# sensor.washing_machine_washer_machine_state:     #
#  - pause                                         #
#  - run                                           #
#  - stop                                          #
####################################################
# Below values obtained from history + live        #
# logging, not from documentation, as the above    #
####################################################
# Possible values for sensor                       #
# sensor.washing_machine_washer_mode:              #
#  - Course_D6 - Roupa de Cama                     #
#  - Course_D7 - Impermeáveis                      #
#  - Course_D8 - Lã                                #
#  - Course_D9 - Roupa Escura                      #
#  - Course_DA - Lavagem Super Eco                 #
#  - Course_DB - Super Rápido                      #
#  - Course_DC - Rápido 15'                        #
#  - Course_D0 - Algodão                           #
#  - Course_D1 - eAlgodão                          #
#  - Course_D2 - Sintéticos                        #
#  - Course_D3 - Roupa Delicada                    #
#  - Course_D4 - Enxaguamento+Centrifugação        #
#  - Course_D5 - Limpar tambor                     #
#  - Course_BA - Drenar/centrifugar                # 
####################################################
### Template sensor for Maq Lavar state, depending on SmartThings auto-generated sensors ###
      state_maq_lavar_new:
        friendly_name: "Máq Lavar"
        value_template:  >-
                        {%- if states('switch.washing_machine')|lower == "off" -%}
                          Off
                        {%- elif states('switch.washing_machine')|lower == "on" -%}
                            {%- if states('sensor.washing_machine_washer_machine_state')|lower != "run" -%}
                              {{ states('sensor.washing_machine_washer_machine_state')|capitalize }}
                            {%- else -%}
                              {{ states('sensor.washing_machine_washer_job_state')|capitalize }}
                            {%- endif -%}
                        {%- else -%}
                          Unavailable
                        {%- endif -%}
        icon_template: "{{ 'mdi:washing-machine' }}"

### Template sensor for Maq Lavar remaining cycle Time, depending on SmartThings auto-generated sensors ###
      maq_lavar_remaining:
        friendly_name: "Remaining Time"
        value_template:  >-
                        {%- if states('switch.washing_machine')|lower == "on" and states('sensor.washing_machine_washer_machine_state')|lower != "stop" -%}
                            {%- if states('sensor.washing_machine_washer_job_state')|lower != "none" and states('sensor.washing_machine_washer_job_state')|lower != "finish" -%}
                              {%- if as_timestamp(states('sensor.washing_machine_washer_completion_time')) > utcnow().timestamp() -%}
                                {%- if states('sensor.washing_machine_washer_job_state')|lower == "delaywash" -%}
                                  -{{ (( as_timestamp(states('sensor.washing_machine_washer_completion_time')) - utcnow().timestamp() ) + 60) | timestamp_custom ("%H:%M", false) }}
                                {%- else -%}
                                  {{ (( as_timestamp(states('sensor.washing_machine_washer_completion_time')) - utcnow().timestamp() ) + 60) | timestamp_custom ("%H:%M", false) }}
                                {%- endif -%}
                              {%- else -%}
                                Done
                              {%- endif -%}
                            {%- else -%}
                              Idle
                            {%- endif -%}
                        {%- elif states('switch.washing_machine')|lower == "off" -%}
                          Idle
                        {%- else -%}
                          Unavailable
                        {%- endif -%}
        icon_template: "{{ 'mdi:washing-machine' }}"

### Template sensor for Maq Lavar chosen program, depending on SmartThings auto-generated sensors ###
      maq_lavar_program:
        friendly_name: "Program"
        value_template:  >-
                        {%- if states('switch.washing_machine')|lower == "off" -%}
                          None
                        {%- elif states('switch.washing_machine')|lower == "on" -%}
                            {%- if states('sensor.washing_machine_washer_machine_state')|lower != "run" -%}
                                None
                            {%- else -%}
                                {%- if states('sensor.washer_program')[-9:] == 'Course_D6' -%}
                                    Roupa de Cama
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_D7' -%}
                                    Impermeáveis
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_D8' -%}
                                    Lã
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_D9' -%}
                                    Roupa Escura
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_DA' -%}
                                    Lavagem Super Eco
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_DB' -%}
                                    Super Rápido
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_DC' -%}
                                    Rápido 15'
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_D0' -%}
                                    Algodão
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_D1' -%}
                                    eAlgodão
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_D2' -%}
                                    Sintéticos
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_D3' -%}
                                    Roupa Delicada
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_D4' -%}
                                    Enxaguamento+Centrifugação
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_D5' -%}
                                    Limpar tambor
                                {%- elif states('sensor.washer_program')[-9:] == 'Course_BA' -%}
                                    Drenar/centrifugar
                                {%- else -%}
                                    Programa desconhecido
                                {%- endif -%}
                            {%- endif -%}
                        {%- else -%}
                          Unavailable
                        {%- endif -%}
        icon_template: "{{ 'mdi:washing-machine' }}"

### Template sensor for Maq Lavar number of cycles until drum cleaning is required ###
      maq_lavar_cycles:
        friendly_name: "Cycles until Drum Cleaning"
        value_template: "{{ ( 40 - states('input_number.maq_lavar_cycles')|int ) | int }}"
        icon_template: "{{ 'mdi:washing-machine' }}"
        unit_of_measurement: cycle(s)
    
### Template sensor for information taken directly from SmartThings API ###
      washer_program:
        friendly_name: "Washer Program"
        value_template: "{{ state_attr('sensor.smartthings_api', 'components')['main']['washerMode']['washerMode']['value'] }}"
        icon_template: "{{ 'mdi:washing-machine' }}"

### Template sensor for information taken directly from SmartThings API ###
      washer_error:
        friendly_name: "Washer Error"
        value_template: "{{ state_attr('sensor.smartthings_api', 'components')['main']['custom.error']['error']['value'] }}"
        icon_template: "{{ 'mdi:alert-circle' }}"

### Template sensor for information taken directly from SmartThings API ###
      washer_consumption:
        friendly_name: "Washer Consumption"
        value_template: "{{ state_attr('sensor.smartthings_api', 'components')['main']['powerConsumptionReport']['powerConsumption']['value']['energy']|int / 1000 }}"
        icon_template: "{{ 'mdi:flash' }}"
        unit_of_measurement: kWh

### 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

####################################################
#                                                  #
#                     Scripts                      #
#                                                  #
####################################################
script:
  increase_number_missing_cycles:
    alias: "Increase missing cycles"
    sequence:
      - service: input_number.decrement
        entity_id: input_number.maq_lavar_cycles
  decrease_number_missing_cycles:
    alias: "Decrease missing cycles"
    sequence:
      - service: input_number.increment
        entity_id: input_number.maq_lavar_cycles

####################################################
#                                                  #
#                    Automations                   #
#                                                  #
####################################################
automation:
### Notify when maquina lavar cycle is finished ###
  - alias: 'Notify when maq lavar finished'
    trigger:
      - platform: state
        entity_id: 'sensor.state_maq_lavar_new'
        to: 'Finish'
    condition:
      condition: template
      value_template: "{{ trigger.from_state.state != 'Off' and trigger.from_state.state != 'Stop' and trigger.from_state.state != 'None' }}"
    action:    
      - service: notify.ios
        data_template: 
          message: "Máquina lavar finished ({{ states('sensor.maq_lavar_program') }})"
          title: "{{ states('sensor.ha_message_info') }}"
          data:
            push:
              thread-id: "home_appliances"
            apns_headers:
              apns-collapse-id: "maq_lavar_finished"

### Notify when maquina lavar cycle is paused ###
  - alias: 'Notify when maq lavar paused'
    trigger:
      - platform: state
        entity_id: 'sensor.state_maq_lavar_new'
        to: 'Pause'
        for:
          minutes: 2
    action:    
      - service: notify.ios
        data:
          message: "⚠️ Máquina lavar paused ⚠️"
          title: "{{ states('sensor.ha_message_alert') }}"
          data:
            push:
              thread-id: "home_appliances"
            apns_headers:
              apns-collapse-id: "maq_lavar_paused"

### Notify when maquina lavar changed state ###
  - alias: 'Notify when maq lavar changed state'
    trigger:
      - platform: state
        entity_id: 
          - sensor.state_maq_lavar_new
          - sensor.maq_lavar_program
          - sensor.washer_program
          - sensor.washer_consumption
          - switch.washing_machine
          - sensor.washing_machine_washer_job_state
          - sensor.washing_machine_washer_machine_state
          - input_number.maq_lavar_cycles
    action:
      - service: notify.samsung_washing_machine_log_file
        data_template:
          message: 'Sensor: {{ trigger.entity_id }} / Value: {{ trigger.to_state.state|upper }}'

### Count cycle when maquina lavar cycle is finished ###
  - alias: 'Count cycle when maq lavar finished'
    trigger:
      - platform: state
        entity_id: 'sensor.state_maq_lavar_new'
        to: 'Finish'
    condition:
      - condition: template
        value_template: >-
           {{ states('sensor.washer_program')[-9:] != 'Course_D4' 
              and states('sensor.washer_program')[-9:] != 'Course_D5' 
              and states('sensor.washer_program')[-9:] != 'Course_BA' 
              and trigger.from_state.state != 'Off' 
              and trigger.from_state.state != 'Stop' 
              and trigger.from_state.state != 'None' }}
    action:
      - service: input_number.increment
        data:
          entity_id: input_number.maq_lavar_cycles

### Reset cycle Count when maquina lavar cycle is finished ###
  - alias: 'Reset cycle count when maq lavar finished'
    trigger:
      - platform: state
        entity_id: 'sensor.state_maq_lavar_new'
        to: 'Finish'
    condition:
      - condition: template
        value_template: "{{ states('sensor.washer_program')[-9:] == 'Course_D5' }}"
    action:
      - service: input_number.set_value
        data:
          entity_id: input_number.maq_lavar_cycles
          value: 0

### Notify when cycle Count requires drum cleaning ###
  - alias: 'Notify when drum cleaning is required'
    trigger:
      platform: state
      entity_id: input_number.maq_lavar_cycles
    condition:
      condition: numeric_state
      entity_id: input_number.maq_lavar_cycles
      above: 39
    action:
      - service: notify.ios
        data:
          message: "Washing Machine Drum Cleaning is required"
          title: "{{ states('sensor.ha_message_alert') }}"
          data:
            push:
              thread-id: "home_appliances"
            apns_headers:
              apns-collapse-id: "maq_lavar_cleaning"

### Update washer data directly from Samsung Smartthings API ###
  - alias: "Update SmartThings data via API"
    trigger:
      - platform: state
        entity_id: sensor.washing_machine_washer_machine_state
        to: 
          - 'run'
          - 'stop'
      - platform: state
        entity_id: sensor.washing_machine_washer_job_state
        to:
          - 'airWash'
          - 'cooling'
          - 'delayWash'
          - 'preWash'
          - 'rinse'
          - 'spin'
          - 'wash'
          - 'weightSensing'
          - 'wrinklePrevent'
    action:
      - service: homeassistant.update_entity
        data:
          entity_id: sensor.smartthings_api

The washer program I actually get it directly via API call rather than via HA integration, as that has never worked that well.

The remaining time, I’m actually showing it as hh:mm instead, calculated based on timestamp provided and current timetamp.

Still then, if you want it to become a valid relative time in the UI, you’ll need something like the following template sensor:

      maq_lavar_remaining_iso:
        friendly_name: "Remaining Time ISO"
        value_template:  "{{ states('sensor.washing_machine_washer_completion_time') | replace ('Z', '000+00:00') }}"
        device_class: timestamp

Hope all this can somehow help you with HA integration with Samsung Washer.

Please let me know if you need any further help.

1 Like

@pplucky Whoa! I’m speechless. I was barely hoping for an answer, especially when digging out a year-old post, but this is something completely out of this world. Detailed, well commented and useful.
Thanks a lot!

In the meantime I managed to do some things by myself and present these on the front with a nice view by MorimotoK:

2 Likes

Actually, I’d like to ask about one more thing: the sensor.ha_message_alert.
What is it? You’re using it in notification titles, but I cannot really guess what it does.

@pplucky the device id that you have in the url for the api is Device Network Id in smarthing?

best regards

Not entirely sure, but I found that the ID found in SmartThings www panel was different than the one I got via API. I used Postman to make a GET request, but you could easily use curl for that.
Something along these lines:

 curl -H "Authorization: Bearer YOURTOKENHERE" -X GET https://api.smartthings.com/v1/devices/

This should list all your devices and their IDs.

1 Like

You can actually ignore it, but this is just a template sensor to allow bringing current time in specific format to the message text, with the following configuration:

sensor:
  - platform: template
    sensors:
      ha_message_alert:
        entity_id: sensor.time
        value_template: "{{ 'HA alert - ' + now().strftime('%H:%M') }}"

@pplucky how your sensor. smartthings_api get data? Mine is always empty… if i try the curl command in terminal is working… but the sensor never gets data

Basically the sensor is set to update itself every 1 year, so that it actually only gets updated (with the whole json obtained) when this automation runs:

  - alias: "Update SmartThings data via API"
    trigger:
      - platform: state
        entity_id: sensor.washing_machine_washer_machine_state
        to: 
          - 'run'
          - 'stop'
      - platform: state
        entity_id: sensor.washing_machine_washer_job_state
        to:
          - 'airWash'
          - 'cooling'
          - 'delayWash'
          - 'preWash'
          - 'rinse'
          - 'spin'
          - 'wash'
          - 'weightSensing'
          - 'wrinklePrevent'
    action:
      - service: homeassistant.update_entity
        data:
          entity_id: sensor.smartthings_api

Which is supposed to happen when the above sensor entities get one of these values.

Check my system data here:

Please let me know how it goes.

@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?