mqtt.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import json
  2. import threading
  3. class MqttMotionPublisher(threading.Thread):
  4. def __init__(self, client, topic_prefix, motion_changed, motion_flags):
  5. threading.Thread.__init__(self)
  6. self.client = client
  7. self.topic_prefix = topic_prefix
  8. self.motion_changed = motion_changed
  9. self.motion_flags = motion_flags
  10. def run(self):
  11. last_sent_motion = ""
  12. while True:
  13. with self.motion_changed:
  14. self.motion_changed.wait()
  15. # send message for motion
  16. motion_status = 'OFF'
  17. if any(obj.is_set() for obj in self.motion_flags):
  18. motion_status = 'ON'
  19. if last_sent_motion != motion_status:
  20. last_sent_motion = motion_status
  21. self.client.publish(self.topic_prefix+'/motion', motion_status, retain=False)
  22. class MqttObjectPublisher(threading.Thread):
  23. def __init__(self, client, topic_prefix, objects_parsed, object_classes, detected_objects):
  24. threading.Thread.__init__(self)
  25. self.client = client
  26. self.topic_prefix = topic_prefix
  27. self.objects_parsed = objects_parsed
  28. self.object_classes = object_classes
  29. self._detected_objects = detected_objects
  30. def run(self):
  31. last_sent_payload = ""
  32. while True:
  33. # initialize the payload
  34. payload = {}
  35. # wait until objects have been parsed
  36. with self.objects_parsed:
  37. self.objects_parsed.wait()
  38. # add all the person scores in detected objects and
  39. # average over past 1 seconds (5fps)
  40. detected_objects = self._detected_objects.copy()
  41. avg_person_score = sum([obj['score'] for obj in detected_objects if obj['name'] == 'person'])/5
  42. payload['person'] = int(avg_person_score*100)
  43. # send message for objects if different
  44. new_payload = json.dumps(payload, sort_keys=True)
  45. if new_payload != last_sent_payload:
  46. last_sent_payload = new_payload
  47. self.client.publish(self.topic_prefix+'/objects', new_payload, retain=False)