Extract and match time from mqtt payload to aid automation

I’m having some wierdness where phantom / mqtt data is screwing with my automation. I believe i can solve (or rather workaround) it by matching the time of any physical state changes/updates with the now()time template, so as to ignore the phantom data, but the process is eluding me.

my mqtt stream shows lots of these pairs - even when the button hasn’t been pressed for hours:

hue/hue_dimmer_switch_2/buttonevent 1002
hue/hue_dimmer_switch_2/lastupdated 2017-12-12T09:50:49

the lastupdated is accurate - ie the button was physically pressed at 9:50am - but i’m getting these popping up in my mqtt stream every five (or so) minutes a few times a day.

a modified automation with the buttonevent state change as the trigger, and a condition that the lastupdated time is equal to now (within say 5 seconds), would squash this bug.

mooching through the forum has got me to this template to pull and strip time from now():

{{ strptime(now().strftime("%H:%M:%S"), "%H:%M:%S") -strptime("0", "%M") }}

which would give me:
14:16:19

but i am stumped as to how to go about extracting the time from the mqtt payload.

can anyone point me in the right direction?

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