From: Tom Hunger Date: Mon, 26 Jan 2015 12:38:51 +0000 (+0000) Subject: Correct global command id and send error handling. X-Git-Url: https://git.aero2k.de/?a=commitdiff_plain;h=be8bb27f64cd2e322a83bc048e318a773540f206;p=sirius.git Correct global command id and send error handling. We previously had a next_command_id per bridge which works for communicating with a single bridge, but we decided to use the command id for message print_ids as well where they have to be unique. If we wrap around at 4 billion we need to add an extra filter with a date-cutoff. --- diff --git a/sirius/coding/image_encoding.py b/sirius/coding/image_encoding.py index cadc3bf..b77efae 100644 --- a/sirius/coding/image_encoding.py +++ b/sirius/coding/image_encoding.py @@ -11,7 +11,7 @@ TRANSLATE = [(1536, 255), (1152, 254), (768, 253), (384, 252), (251, 251)] def pixel_to_bw(p): - if p == (0, 0, 0, 0): + if p == (0, 0, 0, 0): # 0 alpha means white. return WHITE elif p[0] > THRESHOLD or p[1] > THRESHOLD or p[2] > THRESHOLD: return WHITE diff --git a/sirius/config.py b/sirius/config.py index 755a2c4..1036c97 100755 --- a/sirius/config.py +++ b/sirius/config.py @@ -5,6 +5,8 @@ basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or 'this is the lp2 secret' SQLALCHEMY_COMMIT_ON_TEARDOWN = True + # printer not seen for 60 seconds: Mark offline. + PRINTER_OFFLINE_CUTOFF_SECONDS = 60 @staticmethod def init_app(app): diff --git a/sirius/models/user.py b/sirius/models/user.py index 7198e5a..58415c5 100644 --- a/sirius/models/user.py +++ b/sirius/models/user.py @@ -64,6 +64,24 @@ class User(db.Model): db.session.add(printer) return printer + def signed_up_friends(self): + """ + :returns: 2-tuple of (all friends, list of people who can print on + my own printer) + """ + friends = self.twitter_oauth.friends + return friends, User.query.filter( + User.username.in_(x.screen_name for x in friends)) + + def friends_printers(self): + """ + :returns: List of printers I can print on. + """ + _, signed_up_friends = self.signed_up_friends() + owner_ids = [x.id for x in signed_up_friends] + return hardware.Printer.query.filter( + hardware.Printer.owner_id.in_(owner_ids)) + Friend = collections.namedtuple('Friend', 'screen_name name profile_image_url') diff --git a/sirius/protocol/protocol_loop.py b/sirius/protocol/protocol_loop.py index dc4f1f5..8c5fd62 100644 --- a/sirius/protocol/protocol_loop.py +++ b/sirius/protocol/protocol_loop.py @@ -6,6 +6,7 @@ The official API is two functions: accept(websocket) send_message(device_address, message) """ +import collections import messages import json import logging @@ -27,9 +28,18 @@ logger = logging.getLogger(__name__) # process can reply. bridge_by_address = dict() +# Map device address to a float timestamp: +last_seen_by_address = dict() + +PrinterDevice = collections.namedtuple( + 'PrinterDevice', 'address last_heartbeat_timestamp') + +next_command_id = None + class BridgeState(object): "Ephemeral state of a bridge. Lives as long as the websocket." + def __init__(self, websocket, address): # key -> command_id, value -> unix timestamp sent self.address = address @@ -37,9 +47,20 @@ class BridgeState(object): self.pending_commands = dict() self.connected_devices = set() + +def _get_next_command_id(): + """ + :returns: An int that can be used as the next command id. + """ + # Lazy-initialize global next_command_id + global next_command_id + if next_command_id is None: # NB 0 is an invalid command id (AKA file-id) so we start at # whatever the latest message id is to avoid collisions. - self.next_command_id = model_messages.Message.get_next_command_id() + next_command_id = model_messages.Message.get_next_command_id() + logger.info("Initialized next_command_id as %s", next_command_id) + next_command_id += 1 + return next_command_id def send_message(device_address, message): @@ -48,29 +69,31 @@ def send_message(device_address, message): :param device_address: The hex-address of the device. :param message: A message from sirius.protocol.messages. - Return False if the device isn't connected, True otherwise. + :returns: 2-tuple of (success, command id used - even if the sending failed) """ + command_id = _get_next_command_id() + + # Search for bridge. for bridge_state in bridge_by_address.values(): if device_address in bridge_state.connected_devices: break else: - return False + return (False, command_id) # Send data through the websocket. command = encoders.encode_bridge_command( bridge_state.address, message, - bridge_state.next_command_id, + command_id, '0', ) bridge_state.websocket.send(json.dumps(command)) # Remember the command we just sent and increment the command id. # TODO - implement timeout logic. - bridge_state.pending_commands[bridge_state.next_command_id] = message - bridge_by_address[bridge_state.address].next_command_id += 1 + bridge_state.pending_commands[command_id] = message - return bridge_state.next_command_id - 1 + return (True, command_id) def accept(ws): diff --git a/sirius/web/landing.py b/sirius/web/landing.py index 9b59c5c..dab5ba2 100644 --- a/sirius/web/landing.py +++ b/sirius/web/landing.py @@ -46,12 +46,11 @@ def landing(): def overview(): my_printers = login.current_user.printers.all() - friends = login.current_user.twitter_oauth.friends - signed_up_friends = user.User.query.filter( - user.User.username.in_(x.screen_name for x in friends)) - + friends, signed_up_friends = login.current_user.signed_up_friends() form = TwitterRefreshFriendsForm() + friends_printers = login.current_user.friends_printers() + # TODO - twitter friends refresh rate limiting. return flask.render_template( @@ -61,6 +60,7 @@ def overview(): last_friend_refresh=login.current_user.twitter_oauth.last_friend_refresh, signed_up_friends=signed_up_friends, friends=friends, + friends_printers=friends_printers, ) diff --git a/sirius/web/printer_print.py b/sirius/web/printer_print.py index b7338a8..ee2ff7f 100644 --- a/sirius/web/printer_print.py +++ b/sirius/web/printer_print.py @@ -1,3 +1,4 @@ +import datetime import flask from flask.ext import login import flask_wtf @@ -39,14 +40,17 @@ def printer_print(user_id, username, printer_id): form = PrintForm() # Note that the form enforces access permissions: People can't - # submit a valid printer-id that's not owned by the user: - form.target_printer.choices = [ - (x.id, x.name) for x in login.current_user.printers.all()] + # submit a valid printer-id that's not owned by the user or one of + # the user's friends. + choices = [ + (x.id, x.name) for x in login.current_user.printers + ] + [ + (x.id, x.name) for x in login.current_user.friends_printers() + ] + form.target_printer.choices = choices form.target_printer.data = printer.id if form.validate_on_submit(): - flask.flash('Sent your message to the printer!') - # TODO: move image encoding into a pthread. # TODO: use templating to avoid injection attacks pixels = image_encoding.html_to_png( @@ -56,14 +60,17 @@ def printer_print(user_id, username, printer_id): pixels=pixels, ) - # Note that we don't really handle the case of a disconnected - # printer yet. It f the printer isn't connected we'll silently - # swallow the message. - next_print_id = protocol_loop.send_message(printer.device_address, hardware_message) + # If a printer is "offline" then we won't find the printer + # connected and success will be false. + success, next_print_id = protocol_loop.send_message( + printer.device_address, hardware_message) - if next_print_id is False: - pass # TODO - note immediately that we could not print in - # failure_message. + if success: + flask.flash('Sent your message to the printer!') + else: + flask.flash(("Could not send message because the " + "printer {} is offline.").format(printer.name), + 'error') # Store the same message in the model. model_message = model_messages.Message( @@ -72,6 +79,9 @@ def printer_print(user_id, username, printer_id): sender_id=login.current_user.id, target_printer=printer, ) + if not success: + model_message.failure_message = 'Printer offline' + model_message.response_timestamp = datetime.datetime.utcnow() db.session.add(model_message) return flask.redirect(flask.url_for( diff --git a/sirius/web/templates/overview.html b/sirius/web/templates/overview.html index 60ad35d..216995b 100644 --- a/sirius/web/templates/overview.html +++ b/sirius/web/templates/overview.html @@ -31,11 +31,27 @@ user_id=current_user.id, username=current_user.username) }}"> Claim another printer - . + +

Friends' printers

+ + {% endif %} -

People who can print on my printers

+

People who can print on my printers