2015-06-09 17:01:20 +02:00
|
|
|
'''
|
|
|
|
Created on 09.06.2015
|
|
|
|
|
|
|
|
@author: wn
|
|
|
|
'''
|
|
|
|
|
|
|
|
import threading
|
|
|
|
import Queue
|
|
|
|
from logger import Logger
|
|
|
|
import paho.mqtt.client as mqtt
|
|
|
|
import json
|
|
|
|
import datetime
|
|
|
|
|
2015-06-09 22:09:28 +02:00
|
|
|
_queue = None
|
2015-06-09 17:01:20 +02:00
|
|
|
|
|
|
|
def on_message(client, userdata, msg):
|
|
|
|
try:
|
2015-06-09 22:09:28 +02:00
|
|
|
j = json.loads(msg.payload)
|
|
|
|
now1 = datetime.datetime.now()
|
|
|
|
now = now1.replace(now1.year, now1.month, now1.day, now1.hour, now1.minute, now1.second, 0)
|
|
|
|
midnight = now.replace(now.year, now.month, now.day, 0,0,0,0)
|
|
|
|
seconds = (now - midnight).seconds
|
|
|
|
j['metadata']['timestamp'] = now
|
|
|
|
j['metadata']['seconds'] = seconds
|
|
|
|
j['metadata']['day'] = midnight
|
|
|
|
|
|
|
|
Logger.debug("MqttReceiver queues: %s" % j)
|
|
|
|
|
|
|
|
_queue.put_nowait(j)
|
2015-06-09 17:01:20 +02:00
|
|
|
except Queue.Full:
|
|
|
|
Logger.log("Message %s dropped" % (j))
|
2015-06-09 22:09:28 +02:00
|
|
|
except ValueError, e:
|
|
|
|
Logger.log("Exception %s in MqttReceiver, on_message" % (str(e)))
|
2015-06-09 17:01:20 +02:00
|
|
|
|
|
|
|
|
|
|
|
class MqttReceiver(threading.Thread):
|
|
|
|
singleton = None
|
|
|
|
|
|
|
|
@classmethod
|
2015-06-09 22:09:28 +02:00
|
|
|
def create(cls, queue, broker, topics):
|
|
|
|
global _queue
|
2015-06-09 17:01:20 +02:00
|
|
|
if cls.singleton is None:
|
2015-06-09 22:09:28 +02:00
|
|
|
cls.singleton = MqttReceiver(queue, broker, topics)
|
|
|
|
_queue = queue
|
2015-06-09 17:01:20 +02:00
|
|
|
return cls.singleton
|
|
|
|
|
2015-06-09 22:09:28 +02:00
|
|
|
def __init__(self, queue, broker, topics):
|
2015-06-09 17:01:20 +02:00
|
|
|
threading.Thread.__init__(self)
|
|
|
|
self.queue = queue
|
2015-06-09 22:09:28 +02:00
|
|
|
self.broker = broker
|
|
|
|
self.topics = topics
|
2015-06-09 17:01:20 +02:00
|
|
|
self.setDaemon(True)
|
|
|
|
|
|
|
|
def run(self):
|
|
|
|
client = mqtt.Client()
|
|
|
|
client.on_message = on_message
|
2015-06-09 22:09:28 +02:00
|
|
|
client.connect(self.broker, 1883, 60)
|
|
|
|
for topic in self.topics:
|
|
|
|
Logger.log("Subscribing on %s" % str(topic))
|
|
|
|
client.subscribe(topic)
|
|
|
|
|
2015-06-09 17:01:20 +02:00
|
|
|
client.loop_forever()
|