mqtt.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import json
  2. import cv2
  3. import threading
  4. class MqttObjectPublisher(threading.Thread):
  5. def __init__(self, client, topic_prefix, objects_parsed, detected_objects, best_person_frame):
  6. threading.Thread.__init__(self)
  7. self.client = client
  8. self.topic_prefix = topic_prefix
  9. self.objects_parsed = objects_parsed
  10. self._detected_objects = detected_objects
  11. self.best_person_frame = best_person_frame
  12. def run(self):
  13. last_sent_payload = ""
  14. while True:
  15. # initialize the payload
  16. payload = {}
  17. # wait until objects have been parsed
  18. with self.objects_parsed:
  19. self.objects_parsed.wait()
  20. # add all the person scores in detected objects
  21. detected_objects = self._detected_objects.copy()
  22. person_score = sum([obj['score'] for obj in detected_objects if obj['name'] == 'person'])
  23. # if the person score is more than 100, set person to ON
  24. payload['person'] = 'ON' if int(person_score*100) > 100 else 'OFF'
  25. # send message for objects if different
  26. new_payload = json.dumps(payload, sort_keys=True)
  27. if new_payload != last_sent_payload:
  28. last_sent_payload = new_payload
  29. self.client.publish(self.topic_prefix+'/objects', new_payload, retain=False)
  30. # send the snapshot over mqtt as well
  31. if not self.best_person_frame.best_frame is None:
  32. ret, jpg = cv2.imencode('.jpg', self.best_person_frame.best_frame)
  33. if ret:
  34. jpg_bytes = jpg.tobytes()
  35. self.client.publish(self.topic_prefix+'/snapshot', jpg_bytes, retain=True)