]> git.aero2k.de Git - sirius.git/commitdiff
Correct global command id and send error handling.
authorTom Hunger <tehunger@gmail.com>
Mon, 26 Jan 2015 12:38:51 +0000 (12:38 +0000)
committerTom Hunger <tehunger@gmail.com>
Mon, 26 Jan 2015 14:01:48 +0000 (14:01 +0000)
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.

sirius/coding/image_encoding.py
sirius/config.py
sirius/models/user.py
sirius/protocol/protocol_loop.py
sirius/web/landing.py
sirius/web/printer_print.py
sirius/web/templates/overview.html

index cadc3bf672200128410a48e4f9e9189badd59483..b77efaeaaceb7aa0a5e01e2502834a5c4acc30c2 100644 (file)
@@ -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
index 755a2c408ac32e0b0727b4db873d3f0f91a604b7..1036c979626ebf88ab48a1d404569ca1a6b08aec 100755 (executable)
@@ -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):
index 7198e5afd8b36116c232628abf41782785015814..58415c5c0f0d9313ce3cc5b1cf67b72039048573 100644 (file)
@@ -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')
 
index dc4f1f5040270d25d27ac87b14adac44fc32a235..8c5fd6245a44e9286da2f7fb1906c1a3171dab17 100644 (file)
@@ -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):
index 9b59c5ccaffa4eec831d97cd5c91aea4167093de..dab5ba29743a4b4f7bfbaf41ef87b8e234ffdbc1 100644 (file)
@@ -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,
     )
 
 
index b7338a8d677e6b7eb81232875e369255432a3072..ee2ff7fd337d1be51d2a618eac108cca3fc6b035 100644 (file)
@@ -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(
index 60ad35da82e3f79f5a706e4c639394a3df875383..216995b46dd7c26205ec23b9d96a1c6f4f313e76 100644 (file)
                          user_id=current_user.id,
                          username=current_user.username) }}">
                Claim another printer
-       </a>.
+       </a>
 </div>
 
+<h2>Friends' printers</h2>
+<ul>
+{% for x in friends_printers %}
+<li>
+       {{ x.owner.username }} - {{ x.name }}
+
+       (<a href="{{ url_for('printer_print.printer_print',
+                 user_id=current_user.id,
+                 username=current_user.username,
+                 printer_id=x.id) }}">send message</a>)
+</li>
+{% else %}
+<li>No printers yet.</li>
+{% endfor %}
+</ul>
+
 {% endif %}
-<h1>People who can print on my printers</h1>
+<h2>People who can print on my printers</h2>
 <ul>
 {% for x in signed_up_friends %}
 <li>{{ x.username }}</li>