platypush/platypush/bus/__init__.py

75 lines
2.2 KiB
Python
Raw Normal View History

import logging
2017-12-22 02:11:56 +01:00
import threading
import time
2017-12-18 01:10:51 +01:00
from queue import Queue
2017-12-22 02:11:56 +01:00
from platypush.config import Config
2019-07-01 19:32:22 +02:00
from platypush.message.event import StopEvent
2020-09-27 01:33:38 +02:00
logger = logging.getLogger('platypush:bus')
2018-06-06 20:09:18 +02:00
2017-12-18 01:10:51 +01:00
class Bus(object):
""" Main local bus where the daemon will listen for new messages """
2019-07-01 19:32:22 +02:00
_MSG_EXPIRY_TIMEOUT = 60.0 # Consider a message on the bus as expired after one minute without being picked up
def __init__(self, on_message=None):
2017-12-18 01:10:51 +01:00
self.bus = Queue()
self.on_message = on_message
2017-12-22 02:11:56 +01:00
self.thread_id = threading.get_ident()
2017-12-18 01:10:51 +01:00
def post(self, msg):
""" Sends a message to the bus """
self.bus.put(msg)
def get(self):
""" Reads one message from the bus """
return self.bus.get()
2017-12-22 02:11:56 +01:00
def stop(self):
""" Stops the bus by sending a STOP event """
evt = StopEvent(target=Config.get('device_id'),
origin=Config.get('device_id'),
thread_id=self.thread_id)
2018-09-20 09:41:19 +02:00
self.post(evt)
2017-12-22 02:11:56 +01:00
def _msg_executor(self, msg):
def executor():
try:
self.on_message(msg)
except Exception as e:
logger.error('Error on processing message {}'.format(msg))
logger.exception(e)
return executor
def poll(self):
"""
Reads messages from the bus until either stop event message or KeyboardInterrupt
"""
if not self.on_message:
2018-06-06 20:09:18 +02:00
logger.warning('No message handlers installed, cannot poll')
return
2019-07-01 19:32:22 +02:00
stop = False
while not stop:
msg = self.get()
timestamp = msg.timestamp if hasattr(msg, 'timestamp') else msg.get('timestamp')
if timestamp and time.time() - timestamp > self._MSG_EXPIRY_TIMEOUT:
2019-07-01 19:32:22 +02:00
logger.debug('{} seconds old message on the bus expired, ignoring it: {}'.
format(int(time.time()-msg.timestamp), msg))
continue
threading.Thread(target=self._msg_executor(msg)).start()
if isinstance(msg, StopEvent) and msg.targets_me():
2018-06-06 20:09:18 +02:00
logger.info('Received STOP event on the bus')
2019-07-01 19:32:22 +02:00
stop = True
2017-12-18 01:10:51 +01:00
# vim:sw=4:ts=4:et: