Mqtt2Mongo/Broker.py

56 lines
1.2 KiB
Python
Raw Permalink Normal View History

2016-03-06 22:27:06 +01:00
'''
Created on 06.03.2016
@author: wn
'''
import Queue
2016-07-03 22:27:58 +02:00
import threading
from logger import Logger
2016-03-06 22:27:06 +01:00
class BrokerException(Exception): pass
class BrokerDuplicateIdException(BrokerException): pass
class BrokerNotSubscribedException(BrokerException): pass
class BrokerOverflowException(BrokerException): pass
2016-07-03 22:27:58 +02:00
class Broker(threading.Thread):
2016-03-06 22:27:06 +01:00
def __init__(self):
2016-07-03 22:27:58 +02:00
threading.Thread.__init__(self)
self.setDaemon(True)
2016-03-06 22:27:06 +01:00
self.outQueues = {}
2016-07-03 22:27:58 +02:00
self.inQueue = Queue.Queue()
def run(self):
while True:
try:
item = self.inQueue.get(True, None)
Logger.log("got an item")
for (n, q) in self.outQueues.iteritems():
Logger.log("passed to %s" % n)
q.put_nowait(item)
except Queue.Full:
pass
def getInQueue(self):
return self.inQueue
2016-03-06 22:27:06 +01:00
def subscribe(self, name):
if self.outQueues.has_key(name):
raise BrokerDuplicateIdException()
self.outQueues[name] = Queue.Queue()
2016-07-03 22:27:58 +02:00
return self.outQueues[name]
2016-03-06 22:27:06 +01:00
def unsubscribe(self, name):
try:
del self.outQueues[name]
except KeyError:
raise BrokerNotSubscribedException