2019-02-26 03:27:02 +01:00
|
|
|
import json
|
2019-07-14 15:31:21 +02:00
|
|
|
import cv2
|
2019-02-26 03:27:02 +01:00
|
|
|
import threading
|
|
|
|
|
|
|
|
class MqttObjectPublisher(threading.Thread):
|
2019-07-14 15:31:21 +02:00
|
|
|
def __init__(self, client, topic_prefix, objects_parsed, detected_objects, best_person_frame):
|
2019-02-26 03:27:02 +01:00
|
|
|
threading.Thread.__init__(self)
|
|
|
|
self.client = client
|
|
|
|
self.topic_prefix = topic_prefix
|
|
|
|
self.objects_parsed = objects_parsed
|
|
|
|
self._detected_objects = detected_objects
|
2019-07-14 15:31:21 +02:00
|
|
|
self.best_person_frame = best_person_frame
|
2019-02-26 03:27:02 +01:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
last_sent_payload = ""
|
|
|
|
while True:
|
|
|
|
|
|
|
|
# initialize the payload
|
|
|
|
payload = {}
|
|
|
|
|
|
|
|
# wait until objects have been parsed
|
|
|
|
with self.objects_parsed:
|
|
|
|
self.objects_parsed.wait()
|
|
|
|
|
2019-03-13 02:54:43 +01:00
|
|
|
# add all the person scores in detected objects
|
2019-02-26 03:27:02 +01:00
|
|
|
detected_objects = self._detected_objects.copy()
|
2019-03-13 02:54:43 +01:00
|
|
|
person_score = sum([obj['score'] for obj in detected_objects if obj['name'] == 'person'])
|
|
|
|
# if the person score is more than 100, set person to ON
|
|
|
|
payload['person'] = 'ON' if int(person_score*100) > 100 else 'OFF'
|
2019-02-26 03:27:02 +01:00
|
|
|
|
|
|
|
# send message for objects if different
|
|
|
|
new_payload = json.dumps(payload, sort_keys=True)
|
|
|
|
if new_payload != last_sent_payload:
|
|
|
|
last_sent_payload = new_payload
|
2019-07-14 15:31:21 +02:00
|
|
|
self.client.publish(self.topic_prefix+'/objects', new_payload, retain=False)
|
|
|
|
# send the snapshot over mqtt as well
|
|
|
|
if not self.best_person_frame.best_frame is None:
|
|
|
|
ret, jpg = cv2.imencode('.jpg', self.best_person_frame.best_frame)
|
|
|
|
if ret:
|
|
|
|
jpg_bytes = jpg.tobytes()
|
|
|
|
self.client.publish(self.topic_prefix+'/snapshot', jpg_bytes, retain=True)
|