From: Matt Webb Date: Tue, 23 Sep 2014 17:54:22 +0000 (+0100) Subject: moving the websockets logic around to start processing events in a sane way, and... X-Git-Url: https://git.aero2k.de/?a=commitdiff_plain;h=9c55dd271b993c152eaf5b7100e00dcc889cde0a;p=sirius.git moving the websockets logic around to start processing events in a sane way, and making a start on a proper command sender --- diff --git a/app/__init__.py b/app/__init__.py index 70b996d..05ab4fb 100755 --- a/app/__init__.py +++ b/app/__init__.py @@ -13,6 +13,7 @@ db = SQLAlchemy() sockets = Sockets() from . import commands +from events import process_event # @TODO @@ -39,40 +40,85 @@ def create_app(config_name): from .main import main as main_blueprint app.register_blueprint(main_blueprint) + class CommandBackend(object): + """ Interface for registering and updating Websocket clients + to receive commands. """ + + def __init__(self): + self.clients = list() + self.bridge_commands_queue = {} # bridge_address: [bc] + self.pending_bridge_command = {} # bridge_address: bc + self.device_commands_queue = {} # device_address: [dc] + self.pending_device_command = {} # device_address: dc + + self.did_send_image = False + + def register(self, ws): + self.clients.append( WebsocketClient(ws) ) + + def add_bridge_address(self, bridge_address, ws): + for c in self.clients: + if c.ws == ws: + c.bridge_address = bridge_address + + def add_device(self, device_address, ws): + [c.add_device(device_address) for c in self.clients if c.ws == ws] + + def remove_device(self, device_address, ws): + [c.remove_device(device_address) for c in self.clients if c.ws == ws] + + def send_to_bridge(self, bridge_address, command): + matches = [c for c in self.clients if c.bridge_address == bridge_address] + if matches: + matches[0].ws.send(command.to_json()) + + def send_to_device(self, device_address, command): + matches = [c for c in self.clients if c.has_device(device_address)] + if matches: + matches[0].ws.send(command.to_json()) + + command_sender = CommandBackend() + #command_sender.run() + + class WebsocketClient(object): + + def __init__(self, ws): + self.ws = ws + self.bridge_address = None + self.connected_devices = set() # device_address + + def add_device(self, device_address): + self.connected_devices.add(device_address) + + def remove_device(self, device_address): + self.connected_devices.remove(device_address) + + def has_device(self, device_address): + return device_address in self.connected_devices + # shouldn't be here, should be attached as a blueprint + # there needs to be a single backend object per process + # that allows sockets to register themselves, and remember + # what bridge_address and device_address are present + # then messages can be sent via this object. + # at some point, the object should pass messages around itself + # using redis, so it works over multiple processes + # see https://devcenter.heroku.com/articles/python-websockets + # for a good pattern @sockets.route('/api/v1/connection') def echo_socket(ws): print "here" done_once = False counting = 0 + command_sender.register(ws) while True: message = ws.receive() - pprint(message) - print "" - - # temporary logic + #pprint(message) + try: event = json.loads(message) - if event['type'] == 'BridgeEvent' and event['json_payload']['name'] == 'encryption_key_required': - print "==> encryption_key_required" - j = commands.add_device_encryption_key().to_json() - ws.send(j) - #gevent.sleep(0.5) - #print "===> %s" % j - #j = commands.set_delivery_and_print().to_json() - #ws.send(j) - if event['type'] == 'DeviceEvent': - counting += 1 - if counting == 4: - gevent.sleep(0.5) - j = commands.set_delivery_and_print().to_json() - ws.send(j) - print "===> tried to send image" - pprint(j) - done_once = True - except: - pass - - #ws.send(message) + process_event(ws, event, command_sender) + except Exception, e: + print "Exception: %r" % e return app diff --git a/app/events.py b/app/events.py new file mode 100644 index 0000000..f29ada8 --- /dev/null +++ b/app/events.py @@ -0,0 +1,65 @@ +from . import commands +from .payload import DeviceEventPayload + +# process_event should... +# - break apart the event +# - handle internally by saving/modifying state to current_app +# - deal with claiming +# - create DeviceEvent models and propagate out if necessary +# all of this is happening within a try:except: in the event loop, +# so don't be afraid to crash out + +class EventProcessingException(Exception): pass + +# @TODO command_sender shouldn't be passed in here, and of course it +# shouldn't be horribly synchronous like it is + +def process_event(ws, event, command_sender): + print "Received event type %r" % event['type'] + if event['type'] == 'DeviceEvent': + # unwrap here, even though it breaks abstraction... three event + # types: heartbeat, did_print, did_power_on + # see device_event.py in hubcode + payload = DeviceEventPayload.from_base64(event['binary_payload']) + print "DeviceEvent: %r" % payload['name'] + if payload['name'] == 'heartbeat': + if command_sender.did_send_image is False: + print "Sending set_delivery_and_print" + dc = commands.set_delivery_and_print() + command_sender.send_to_device(event['device_address'], dc) + command_sender.did_send_image = True + elif event['type'] == 'BridgeEvent': + # unwrap here. use device_connect and device_disconnect to + # change the command delivery map. there is also power_on, + # encryption_key_required [4 events are all I can find] + event_name = event['json_payload']['name'] + print "BridgeEvent: %r" % event_name + if event_name == 'device_connect': + command_sender.add_device(event['json_payload']['device_address'], ws) + elif event_name == 'device_disconnect': + command_sender.remove_device(event['json_payload']['device_address'], ws) + elif event_name == 'power_on': + command_sender.add_bridge_address(event['bridge_address'], ws) + elif event_name == 'encryption_key_required': + print "Sending add_device_encryption_key" + bc = commands.add_device_encryption_key() + command_sender.send_to_bridge(event['bridge_address'], bc) + else: + raise EventProcessingException("Unknown BridgeEvent command name: %r" % command_name) + pass + elif event['type'] == 'BridgeLog': + # print it or something + pass + elif event['type'] == 'BridgeCommandResponse': + # if the return_code is 0 or not set, set state as delivered + # else mark it as failed + # (what happens if there is never any update? is there a timeout?) + # (30 minute time-out in the command gate) + pass + elif event['type'] == 'DeviceCommandResponse': + # if the return_code is 0, set state as delivered + # else mark it as failed + # (what happens if there is never any update? is there a timeout?) + pass + else: + raise EventProcessingException("Unknown event type: %r" % event['type']) diff --git a/app/models.py b/app/models.py index 58dce89..df3ed84 100755 --- a/app/models.py +++ b/app/models.py @@ -14,6 +14,7 @@ class BridgeCommand(db.Model): timestamp = db.Column(db.DateTime, nullable=False) bridge_address = db.Column(db.String, nullable=False) json_payload = db.Column(db.UnicodeText, nullable=False) + state = db.Column(db.Enum('ready', 'failed', 'delivered', 'skipped'), nullable=False) return_code = db.Column(db.SmallInteger, nullable=True) def to_json(self):