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
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):
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')
accept(websocket)
send_message(device_address, message)
"""
+import collections
import messages
import json
import logging
# 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
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):
: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):
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(
last_friend_refresh=login.current_user.twitter_oauth.last_friend_refresh,
signed_up_friends=signed_up_friends,
friends=friends,
+ friends_printers=friends_printers,
)
+import datetime
import flask
from flask.ext import login
import flask_wtf
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(
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(
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(
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>