From: Matt Webb Date: Thu, 25 Sep 2014 21:11:28 +0000 (+0100) Subject: the most appalling shitshower of shoddy code that i'm only committing now because... X-Git-Url: https://git.aero2k.de/?a=commitdiff_plain;h=b72a852efe796480a777692f0b848208153a2eb5;p=sirius.git the most appalling shitshower of shoddy code that i'm only committing now because it barely works and i mean BARELY and i'd better commit it before it collapses under its own shitness. in other news, i have an async command sender - not quite redis but soon - and an event handler than works in the right app context. plus mostly things work through models. and i can print images. the core messaging system is functional, even if it is made out of tictacs and string --- diff --git a/app/__init__.py b/app/__init__.py index a2f786e..336c2c4 100755 --- a/app/__init__.py +++ b/app/__init__.py @@ -37,6 +37,25 @@ def create_app(config_name): from .main import main as main_blueprint app.register_blueprint(main_blueprint) - from .core import coresocket, command_sender - + #from .core import coresocket + from .core.command_sender import CommandSender + from .core.events import process_event + + @sockets.route('/api/v1/connection') + def coresocket(ws): + print "here" + while True: + message = ws.receive() + #pprint(message) + + #try: + event = json.loads(message) + with app.request_context(ws.environ): + process_event(ws, event, sender) + #except Exception, e: + # print "Exception: %r" % e + + sender = CommandSender() + sender.run() + return app diff --git a/app/core/__init__.py b/app/core/__init__.py index da94099..e68eee2 100644 --- a/app/core/__init__.py +++ b/app/core/__init__.py @@ -1,64 +1,12 @@ from app import sockets from .events import process_event +from .command_sender import CommandSender import json -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 +#sender = CommandSender() +#sender.run() # shouldn't be here, should be attached as a blueprint # there needs to be a single backend object per process @@ -69,16 +17,16 @@ class WebsocketClient(object): # 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') +#@sockets.route('/api/v1/connection') def coresocket(ws): print "here" - command_sender.register(ws) while True: message = ws.receive() #pprint(message) - try: - event = json.loads(message) - process_event(ws, event, command_sender) - except Exception, e: - print "Exception: %r" % e \ No newline at end of file + #try: + event = json.loads(message) + with app.request_context(ws.environ): + process_event(ws, event, sender) + #except Exception, e: + # print "Exception: %r" % e \ No newline at end of file diff --git a/app/core/claiming.py b/app/core/claiming.py index 7c0680e..dfed203 100755 --- a/app/core/claiming.py +++ b/app/core/claiming.py @@ -130,7 +130,7 @@ def generate_link_key(input): # # Return the link key in Base64, and the XORed hardware_address def process_claim_code(claim_code): - hardware_address_xor, secret, crc, raw_value = unpack_claim_code(claim_code) + hardware_xor, secret, crc, raw_value = unpack_claim_code(claim_code) # Generate our own CRC from the raw_value, and confirm it matches the extracted crc data_for_crc = struct.pack(" Adding device %s to queue for bridge %s" % (da, self.bridge) + self.devices.add(da) + self.device_queue[da] = [] + self.device_pending[da] = None + + def remove_device(self, device): + da = device.device_address + self.devices.remove(da) + self.device_queue.pop(da, None) + self.device_pending.pop(da, None) + + def has_device(self, device): + return device.device_address in self.devices + + def queue_bridge_command(self, command): + self.bridge_queue.insert(0, (command.id, command.to_json())) + + def queue_device_command(self, command): + da = command.device_address + self.device_queue[da].insert(0, (command.id, command.to_json())) + + def handle_bridge_response(self, command): + if self.bridge_pending[0] == command.id: + self.bridge_pending = None + self.bridge_queue = [c for c in self.bridge_queue if c[0] != command.id] + + def handle_device_response(self, command): + da = command.device_address + if self.device_pending[da][0] == command.id: + self.device_pending[da] = None + self.device_queue[da] = \ + [c for c in self.device_queue[da] if c.id != command.id] + + def prepare_commands_to_send(self): + commands_to_send = [] + if self.bridge_pending is None and len(self.bridge_queue) > 0: + c = self.bridge_queue.pop() + self.bridge_pending = c + commands_to_send.append(c[1]) + for da in self.devices: + if self.device_pending[da] is None and \ + len(self.device_queue[da]) > 0: + c = self.device_queue[da].pop() + self.device_pending[da] = c + commands_to_send.append(c[1]) + return commands_to_send \ No newline at end of file diff --git a/app/core/commands.py b/app/core/commands.py index f7403ce..27349f3 100644 --- a/app/core/commands.py +++ b/app/core/commands.py @@ -1,3 +1,5 @@ +from app import db + from ..models.core import BridgeCommand from ..models.core import DeviceCommand from ..image_encoding import rle_image @@ -20,7 +22,8 @@ import json TEST_FILE_ID = 1 #TEST_PNG_FN = '/Users/matt/Documents/dev-unversioned/sirius2/iconrethink.png' -TEST_PNG_FN = '/Users/matt/Documents/dev/sirius/tests/iconrethink.png' +#TEST_PNG_FN = '/Users/matt/Documents/dev/sirius/tests/iconrethink.png' +TEST_PNG_FN = '/Users/matt/Documents/dev/sirius/tests/riley.png' # some constants DEVICE_TYPE = '\x01' # rBergCloud::Barringer::DEVICE_TYPE in weminuche-server @@ -46,9 +49,13 @@ def add_device_encryption_key(): command = BridgeCommand( bridge_address='000d6f0001b397c3', json_payload=json.dumps(payload), - timestamp=datetime.utcnow() + timestamp=datetime.utcnow(), + state='ready' ) - command.id = 1 + + db.session.add(command) + db.session.commit() + return command def set_delivery_and_print_payload(file_id, png_fn): @@ -100,12 +107,13 @@ def set_delivery_and_print_payload(file_id, png_fn): return entire_payload -def set_delivery_and_print(): +def set_delivery_and_print(device_address): command = DeviceCommand( - device_address='000d6f000273ce0b', + device_address=device_address, binary_payload=base64.b64encode(set_delivery_and_print_payload(TEST_FILE_ID, TEST_PNG_FN)), state='ready', deliver_at=datetime.utcnow() ) - command.id = 1 + db.session.add(command) + db.session.commit() return command \ No newline at end of file diff --git a/app/core/events.py b/app/core/events.py index 6c39ebc..64fcfea 100644 --- a/app/core/events.py +++ b/app/core/events.py @@ -1,8 +1,12 @@ +from app.models.core import BridgeCommand, DeviceCommand, Device, Bridge +from .. import db + from . import commands from .payload import DeviceEventPayload from . import claiming from datetime import datetime +from pprint import pprint # process_event should... # - break apart the event @@ -15,17 +19,17 @@ from datetime import datetime class PendingClaims(object): def __init__(self): - self.encryption_keys = {} # hardware_address_xor: encryption_key + self.encryption_keys = {} # hardware_xor: encryption_key def add_claim_code(self, claim_code): - hardware_address_xor, encryption_key = claiming.process_claim_code(claim_code) + hardware_xor, encryption_key = claiming.process_claim_code(claim_code) #@TODO handle exception - self.encryption_keys[hardware_address_xor] = encryption_key + self.encryption_keys[hardware_xor] = encryption_key def key_for_address(self, device_address): - hardware_address_xor = claiming.make_hardware_address_xor(device_address) - return self.encryption_keys.get(hardware_address_xor, None) + hardware_xor = claiming.make_hardware_xor(device_address) + return self.encryption_keys.get(hardware_xor, None) pending_claims = PendingClaims() @@ -35,7 +39,7 @@ 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): +def process_event(ws, event, sender): print "Received event type %r" % event['type'] if event['type'] == 'DeviceEvent': # unwrap here, even though it breaks abstraction... three event @@ -45,44 +49,82 @@ def process_event(ws, event, command_sender): timestamp = datetime.fromtimestamp(event['timestamp']) print "DeviceEvent: %r at %s" % (payload['name'], timestamp.isoformat()) if payload['name'] == 'heartbeat': - if command_sender.did_send_image is False: + if 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 + device = Device.query.get(event['device_address']) + if device is not None: + q = sender.for_device(device) + if q is not None: + dc = commands.set_delivery_and_print(event['device_address']) + q.queue_device_command(dc) + 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] + bridge = Bridge.get_or_create(event['bridge_address']) event_name = event['json_payload']['name'] timestamp = datetime.fromtimestamp(event['timestamp']) print "BridgeEvent: %r at %s" % (event_name, timestamp.isoformat()) if event_name == 'device_connect': - command_sender.add_device(event['json_payload']['device_address'], ws) + device = Device.get_or_create(event['json_payload']['device_address']) + sender.device_connect(bridge, device) elif event_name == 'device_disconnect': - command_sender.remove_device(event['json_payload']['device_address'], ws) + device = Device.get_or_create(event['json_payload']['device_address']) + sender.device_disconnect(bridge, device) elif event_name == 'power_on': - command_sender.add_bridge_address(event['bridge_address'], ws) + sender.register(ws, bridge) 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) + sender.for_bridge(bridge).queue_bridge_command(bc) else: raise EventProcessingException("Unknown BridgeEvent command name: %r" % command_name) pass elif event['type'] == 'BridgeLog': - # print it or something - pass + pprint(event) 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 + r = event['return_code'] + # update the database, + c = BridgeCommand.query.get(event['command_id']) + if c is None: + raise EventProcessingException("BridgeCommandResponse for unknown command_id %r" % event['command_id']) + c.return_code = r + if r == 0: + c.state = 'delivered' + else: + c.state = 'failed' + db.session.add(c) + db.session.commit() + # let the command_sender know to remove the command from + # the queue, or to resend it + bridge = Bridge.query.get(event['bridge_address']) + if bridge is not None: + sender.for_bridge(bridge).handle_bridge_response(c) 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 + r = event['return_code'] + # update the database, + c = DeviceCommand.query.get(event['command_id']) + if c is None: + raise EventProcessingException("DeviceCommandResponse for unknown command_id %r" % event['command_id']) + c.return_code = r + if r == 0: + c.state = 'delivered' + else: + c.state = 'failed' + db.session.add(c) + db.session.commit() + # let the command_sender know to remove the command from + # the queue, or to resend it + device = Device.query.get(event['device_address']) + if device is not None: + sender.for_device(device).handle_device_response(c) else: raise EventProcessingException("Unknown event type: %r" % event['type']) diff --git a/app/models/core.py b/app/models/core.py index d90e384..d02dba0 100755 --- a/app/models/core.py +++ b/app/models/core.py @@ -1,4 +1,5 @@ -from .. import db +from app import db +from app.core import claiming import json @@ -44,6 +45,7 @@ class DeviceCommand(db.Model): binary_payload = db.Column(db.Text, nullable=False) state = db.Column(db.Enum('ready', 'failed', 'delivered', 'skipped'), nullable=False) deliver_at = db.Column(db.DateTime, nullable=False) + return_code = db.Column(db.SmallInteger, nullable=True) def to_json(self): json_hash = { @@ -57,12 +59,33 @@ class DeviceCommand(db.Model): class Bridge(db.Model): __tablename__ = 'bridges' bridge_address = db.Column(db.String, primary_key=True) - last_power_on = db.Column(db.DateTime, nullable=False) + last_power_on = db.Column(db.DateTime, nullable=True) #@TODO should be false + + @classmethod + def get_or_create(cls, bridge_address): + b = cls.query.get(bridge_address) + if b is None: + b = cls(bridge_address=bridge_address) + db.session.add(b) + db.session.commit() + return b + class Device(db.Model): __tablename__ = 'devices' device_address = db.Column(db.String, primary_key=True) hardware_xor = db.Column(db.String, nullable=False) + + @classmethod + def get_or_create(cls, device_address): + d = cls.query.get(device_address) + if d is None: + d = cls(device_address=device_address, + hardware_xor=claiming.make_hardware_xor(device_address)) + db.session.add(d) + db.session.commit() + return d + class PendingClaim(db.Model): __tablename__ = 'pending_claims' diff --git a/tests/riley.png b/tests/riley.png new file mode 100755 index 0000000..0c0a6c4 Binary files /dev/null and b/tests/riley.png differ