Extract and match time from mqtt payload to aid automation

This is how i’ve solved the problem, for the sake of completeness.

firstly, create a time of day sensor, truncated to only show hours and minutes -

- platform: template
  sensors:
    current_day_time:
      value_template: '{{ now().strftime("%H:%M") }}'  

create a sensor to collect the payload of the ‘lastupdated’ mqtt event:

- platform: mqtt
  name: 'hue_remote1_1_last_seen'
  state_topic: 'hue/hue_dimmer_switch_1/lastupdated'  

create a second sensor to reformat that data - it came in originally like 2017-12-12T09:49:44

- platform: template
  sensors:
    hue_remote1_1_last_seen_modified:
      friendly_name: "hue_remote1_1_last_seen_modded"
      value_template: "{{ states.sensor.hue_remote1_1_last_seen.state[11:]| truncate (5, False, '', 0)}}"   

then, in my original automation (which was misfiring a-plenty due to the crazy phantom mqtt data) add a comparison of the modified sensor with the time of day sensor via a value template:

  - alias: hue_dimmer_remote1_button_1
#initial_state: True
trigger:
  platform: mqtt
  topic: hue/hue_dimmer_switch_1/buttonevent
  payload: '1002'
condition:
  - condition: template
    value_template: "{{ states('sensor.hue_remote1_1_last_seen_modified') == states('sensor.current_day_time') }}"
action:
  service: light.toggle
  entity_id: light.bedroom

job done! thanks to all the various contributers on the forum which helped me scrounge this syntax together :slight_smile:

I originally tried to do all the truncating and wotnot in a single sensor - the mqtt sensor - but it didn’t work. if anyone knows why, i’d love to know as it would reduce the amount of code in this fix.

1 Like