Lovelace: Cannot format template sensor entity as relative time

Tags: #<Tag:0x00007f739680f3e8>

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.