From 2498519232a7215039ecfcd15a37c699137fa27c Mon Sep 17 00:00:00 2001 From: Tom Hunger Date: Thu, 15 Jan 2015 16:44:05 +0000 Subject: [PATCH] Remove previous version of sirius. It's been a good guide, so long. --- app/__init__.py | 69 -------------- app/admin/__init__.py | 7 -- app/core/__init__.py | 32 ------- app/core/claiming.py | 160 ------------------------------- app/core/commands.py | 129 ------------------------- app/core/crc16.py | 39 -------- app/core/events.py | 131 ------------------------- app/core/payload.py | 201 --------------------------------------- app/image_encoding.py | 142 --------------------------- app/main/__init__.py | 37 ------- app/models/__init__.py | 3 - app/models/core.py | 115 ---------------------- app/queues.py | 136 -------------------------- app/templates/admin.html | 7 -- app/templates/base.html | 37 ------- app/templates/dump.html | 15 --- app/templates/index.html | 14 --- 17 files changed, 1274 deletions(-) delete mode 100755 app/__init__.py delete mode 100644 app/admin/__init__.py delete mode 100644 app/core/__init__.py delete mode 100755 app/core/claiming.py delete mode 100644 app/core/commands.py delete mode 100644 app/core/crc16.py delete mode 100644 app/core/events.py delete mode 100644 app/core/payload.py delete mode 100644 app/image_encoding.py delete mode 100644 app/main/__init__.py delete mode 100644 app/models/__init__.py delete mode 100755 app/models/core.py delete mode 100644 app/queues.py delete mode 100644 app/templates/admin.html delete mode 100644 app/templates/base.html delete mode 100644 app/templates/dump.html delete mode 100644 app/templates/index.html diff --git a/app/__init__.py b/app/__init__.py deleted file mode 100755 index edcf95c..0000000 --- a/app/__init__.py +++ /dev/null @@ -1,69 +0,0 @@ -from flask import Flask, render_template -from flask.ext.bootstrap import Bootstrap -from flask.ext.sqlalchemy import SQLAlchemy -from flask_sockets import Sockets -from config import config - -from pprint import pprint -import json -import gevent -import sys - -bootstrap = Bootstrap() -db = SQLAlchemy() -sockets = Sockets() - -# @TODO -# for this to work, I have to put the following line at line 38 of -# flask_sockets, to inject it into the environment -# environment.environ['HTTP_SEC_WEBSOCKET_PROTOCOL'] = 'bergcloud-bridge-v1' -#def protocol_name(): -# print "asked for protocol" - # return 'bergcloud-bridge-v1' - -def create_app(config_name): - app = Flask(__name__) - app.config.from_object(config[config_name]) - config[config_name].init_app(app) - - bootstrap.init_app(app) - db.init_app(app) - sockets.init_app(app) - - # maybe this sets the HTTP_SEC_WEBSOCKET_PROTOCOL ? - #app.protocol_name = protocol_name - - # attach routes and custom error pages - from .main import main as main_blueprint - app.register_blueprint(main_blueprint) - - from .admin import admin as admin_blueprint - app.register_blueprint(admin_blueprint, url_prefix='/admin') - - #from .core import coresocket - from .core.events import process_event - #from .core.command_sender import CommandSender - - from queues import CommandSender - sender = CommandSender() - sender.run() - app.sender = sender - - @sockets.route('/api/v1/connection') - def coresocket(ws): - print "here" - sys.stdout.flush() - while True: - gevent.sleep() - message = ws.receive() - #pprint(message) - if message: - app.logger.info(u'Got message: {}'.format(message)) - #try: - event = json.loads(message) - with app.request_context(ws.environ): - process_event(ws, event, sender) - #except Exception, e: - # print "Exception: %r" % e - print "app created" - return app diff --git a/app/admin/__init__.py b/app/admin/__init__.py deleted file mode 100644 index b44a890..0000000 --- a/app/admin/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -from flask import Blueprint, render_template - -admin = Blueprint('admin', __name__) - -@admin.route('/') -def index(): - return render_template('admin.html') diff --git a/app/core/__init__.py b/app/core/__init__.py deleted file mode 100644 index c3872c6..0000000 --- a/app/core/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -from app import sockets - -from .events import process_event -#from .command_sender import CommandSender - -import json - -#sender = CommandSender() -#sender.run() - -# 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 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 \ No newline at end of file diff --git a/app/core/claiming.py b/app/core/claiming.py deleted file mode 100755 index fa3b305..0000000 --- a/app/core/claiming.py +++ /dev/null @@ -1,160 +0,0 @@ -from .crc16 import crc16 -from Crypto.Cipher import AES, XOR - -import struct -import base64 - -ZBEE_SEC_CONST_BLOCKSIZE = 16 - -CLAIM_CODE_SALT = [ 0x38, 0x96, 0x10, 0xd9, - 0xb6, 0xb1, 0x0d, 0x16, - 0x9e, 0xe9, 0xbf, 0x87, - 0x95, 0x32, 0x62, 0x5b ] - -# This dictionary maps base32 digits to five-bit values. -# -# Letter 'A' is omitted and not valid in a claim code. -# Letter 'I' is mapped to number '1' (i.e. claim code is '1', user enters 'I' by mistake). -# Letter 'L' is mapped to number '1' (i.e. claim code is '1', user enters 'L' by mistake). -# Letter 'U' is mapped to letter 'v' (i.e. claim code is 'V', user enters 'U' by mistake). -CLAIMCODE_BASE32_DICT = { - '0': 0x00, - '1': 0x01, - '2': 0x02, - '3': 0x03, - '4': 0x04, - '5': 0x05, - '6': 0x06, - '7': 0x07, - '8': 0x08, - '9': 0x09, -# 'A': omitted - 'B': 0x0A, - 'C': 0x0B, - 'D': 0x0C, - 'E': 0x0D, - 'F': 0x0E, - 'G': 0x0F, - 'H': 0x10, - 'I': 0x01, # mapped to '1' - 'J': 0x11, - 'K': 0x12, - 'L': 0x01, # mapped to '1' - 'M': 0x13, - 'N': 0x14, - 'O': 0x15, - 'P': 0x16, - 'Q': 0x17, - 'R': 0x18, - 'S': 0x19, - 'T': 0x1A, - 'U': 0x1B, # mapped to 'V' - 'V': 0x1B, - 'W': 0x1C, - 'X': 0x1D, - 'Y': 0x1E, - 'Z': 0x1F -} - -class InvalidClaimCode(Exception): - pass - -def unpack_claim_code(claim_code): - clean = claim_code.replace("-", "").upper() - - if len(clean) != 16: - raise InvalidClaimCode("claim codes should be 16 characters") - - value = 0 - - for i, c in enumerate(clean): - if c in CLAIMCODE_BASE32_DICT.keys(): - value += CLAIMCODE_BASE32_DICT[c] * (32 ** (15 - i)) - else: - raise InvalidClaimCode("%s is not a valid character" % c) - - device = value & 0xffffff # 24 bit hardware address xor - secret = (value >> 24) & 0xffffffffff # 40 bit secret - crc = value >> 64 # 16 bit crc - - # Return the components, and the raw 80 bit value - return (device, secret, crc, value) - -# This method is inspired by dissectors/packet-zbee-security.c from Wireshark -# input should be a binary string of 5 bytes in length -def generate_link_key(input): - input_length = len(input) + len(CLAIM_CODE_SALT) - - if len(input) <= 5: - # Padding begins with 1000000 - # Then pad with zeroes until we're at 14 bytes - input = input + b'\x80' + b'\x00' * (ZBEE_SEC_CONST_BLOCKSIZE - 2 - len(input) - 1) - - # Pad with the original length encoded as a 16bit int - # Python3 - #input = input + bytes( [((input_length * 8) >> 8 & 0xff)] ) - #input = input + bytes( [((input_length * 8) >> 0 & 0xff)] ) - # Python2 - input = input + chr((input_length * 8) >> 8 & 0xff) - input = input + chr((input_length * 8) >> 0 & 0xff) - - elif input_length != ZBEE_SEC_CONST_BLOCKSIZE: - raise InvalidClaimCode("cannot handle input size %d" % input_length) - - # We encrypt the salt and the input bytes - # blocks = [bytes(CLAIM_CODE_SALT), input] # Python3 - blocks = [str(bytearray(CLAIM_CODE_SALT)), input] # Python2 - - #output = bytes(16) # Works in Python3 - output = bytearray(16) # Works in Python2 - - for block in blocks: - # aes_encoder = AES.new(output, AES.MODE_ECB) # Python3 - aes_encoder = AES.new(str(output), AES.MODE_ECB) # Python2 - h = aes_encoder.encrypt(block) - output = bytearray(16) - for i in range(len(output)): - # output[i] = h[i] ^ block[i] # Python3 - output[i] = ord(h[i]) ^ ord(block[i]) # Python2 - output = bytes(output) - - return output - - -# Codes go through the following process: -# -# 1. Cleaning -# 2. Convert from 5-bit to 8-bit (16 chars down to 10 chars) -# 3. Checksum is checked -# 4. XOR EUI64 + Base64 security hash + CRC are returned -# -# Return the link key in Base64, and the XORed hardware_address -def process_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("cxHLL - # - payload header - # - length >L - # - payload - # - len(header plus image) + 1 >L - # - pad x - # - encode_header_region - # - pad x - # - length of following >L - # - append_printer_control_header (a bunch o bytes) - # - UC05 controls >8) ^ b]) & 0xffff - return crc - -CCITT_16 = [ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, - 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, - 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, - 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, - 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, - 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, - 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, - 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, - 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, - 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, - 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, - 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, - 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, - 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, - 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, - 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, - 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, - 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, - 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, - 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, - 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, - 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, - 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 - ] diff --git a/app/core/events.py b/app/core/events.py deleted file mode 100644 index b8bcd97..0000000 --- a/app/core/events.py +++ /dev/null @@ -1,131 +0,0 @@ -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 -# - 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 PendingClaims(object): - - def __init__(self): - self.encryption_keys = {} # hardware_xor: encryption_key - - def add_claim_code(self, claim_code): - hardware_xor, encryption_key = claiming.process_claim_code(claim_code) - #@TODO handle exception - - self.encryption_keys[hardware_xor] = encryption_key - - def key_for_address(self, device_address): - hardware_xor = claiming.make_hardware_xor(device_address) - return self.encryption_keys.get(hardware_xor, None) - -pending_claims = PendingClaims() - - -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, 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']) - timestamp = datetime.fromtimestamp(event['timestamp']) - print "DeviceEvent: %r at %s" % (payload['name'], timestamp.isoformat()) - if payload['name'] == 'heartbeat': - if sender.did_send_image is False: - print "Sending set_delivery_and_print" - 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': - device = Device.get_or_create(event['json_payload']['device_address']) - sender.device_connect(bridge, device) - elif event_name == 'device_disconnect': - device = Device.get_or_create(event['json_payload']['device_address']) - sender.device_disconnect(bridge, device) - elif event_name == 'power_on': - sender.register(ws, bridge) - elif event_name == 'encryption_key_required': - print "Sending add_device_encryption_key" - device = Device.get_or_create(event['json_payload']['device_address']) - bc = commands.add_device_encryption_key(bridge, device) - sender.for_bridge(bridge).queue_bridge_command(bc) - else: - raise EventProcessingException("Unknown BridgeEvent command name: %r" % command_name) - pass - elif event['type'] == 'BridgeLog': - 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) - 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?) - 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/core/payload.py b/app/core/payload.py deleted file mode 100644 index 0316c8d..0000000 --- a/app/core/payload.py +++ /dev/null @@ -1,201 +0,0 @@ -import base64 -import struct - -class BERGCloudConst(object): - BC_EVENT_PRODUCT_ANNOUNCE = 0xA000 - BC_COMMAND_SET_BERGCLOUD_ID = 0xB000 - - BC_COMMAND_START_BINARY = 0xC000 - BC_COMMAND_START_PACKED = 0xC100 - BC_COMMAND_ID_MASK = 0x00FF - BC_COMMAND_FORMAT_MASK = 0xFF00 - - BC_COMMAND_DISPLAY_IMAGE = 0xD000 - BC_COMMAND_DISPLAY_TEXT = 0xD001 - - BC_EVENT_START_BINARY = 0xE000 - BC_EVENT_START_PACKED = 0xE100 - BC_EVENT_ID_MASK = 0x00FF - BC_EVENT_FORMAT_MASK = 0xFF00 - - BC_COMMAND_FIRMWARE_ARDUINO = 0xF010 - BC_COMMAND_FIRMWARE_MBED = 0xF020 - - -class DeviceCommandPayload(object): - COMMANDS = { - 'set_delivery_and_print': 0x0001, - 'set_delivery': 0x0002, - 'set_delivery_and_print_no_face': 0x0011, - 'set_delivery_no_face': 0x0012, - 'set_personality': 0x0102, - 'set_personality_with_message': 0x0101, - 'set_quip': 0x0202, - 'firmware_update': 0xf000 - } - - @classmethod - def from_base64(cls, base64_payload): - data = base64.b64decode(base64_payload) - - # encode_command_header and add_length_header_to_payload - # iare used for all Barringer commands, - # in lib/berg_cloud/barringer/commands.rb - offset = 0 - device_type, reserved_byte, command_name_id, file_id, reserved_long, payload_length \ - = struct.unpack_from(" encode_files have a - # similar format: a list of files, each as - # - length+1 (LLLLL", data, offset) - return_hash['name'] = "product_announce" - return_hash['product_id'] = "%08x%08x%08x%08x" % (id0, id1, id2, id3) - return_hash['product_version'] = version - - elif eventCode == DeviceEventPayload.EVENT_HEARTBEAT: - if eventPayloadLength != DeviceEventPayload.EVENT_HEARTBEAT_SIZE: - return_hash['error'] = 'Invalid heartbeat payload length of %d. Should be %d' % (eventPayloadLength, DeviceEventPayload.EVENT_HEARTBEAT_SIZE) - return return_hash - - uptime = struct.unpack_from(" THRESHOLD or p[1] > THRESHOLD or p[2] > THRESHOLD: - return WHITE - else: - return BLACK - -def ilen(i): return sum(1 for _ in i) - -# so what we have is a list of runs, alternating white and black, -# starting with white. -# the scheme for our little printer RLE is: -# - runs of 0..251 inclusive are stored as a byte -# - if larger, pull off chunks of 1536, 1152, 768, 384, 251 (encoded as -# 255, 254, 253, 252, 251) until small enough -# when a large number is broken into chunks, each chunk needs -# to be suffixed by a zero so it snaps back to swap it back to the -# correct colour -def rle(lengths): - for length in lengths: - if length == 0: - yield length - elif length <= 251: - yield length - elif length > 251: - remainder = length - done_first = False - while remainder > 251: - chunk, code = [t for t in TRANSLATE if remainder >= t[0]][0] - remainder -= chunk - if done_first: - yield 0 - else: - done_first = True - yield code - else: - if remainder > 0: - yield 0 - yield remainder - -def rle_image(image_fn): - im = Image.open(image_fn) - return _rle_image(im) - -def _rle_image(im): - # get image pixels - im = im.convert('RGBA') - pixels = im.getdata() - - # convert to B&W and group each run length into lists - # each list is (result of identity function, [actual pixels]) - grouped = groupby(pixels, pixel_to_bw) - - # create list of tuples (WHITE|BLACK, run_length) - groups = [] - for k, g in grouped: - groups.append( (k, ilen(g)) ) - - # the decoder assumes that the first run is white, so if the - # first pixel is black, add a zero run of white - if groups[k][0] == BLACK: - groups.insert(0, (WHITE, 0)) - - # encode using our custom encoding - lengths = [g[1] for g in groups] - x = bytearray(rle(lengths)) - compressed_data = struct.pack("<%dB" % len(x), *x) - - # package up with length as header - # first byte is compressed type, always 1 - output = struct.pack(" - - - """ - from selenium import webdriver - driver = webdriver.PhantomJS('phantomjs') - driver.set_window_size(384, 5) - #driver.get("http://www.google.com") - - driver.get("about:blank") - html = html.replace('"', '\\"') - html = html.replace("\n", " ") - html = html.replace("\t", " ") - html = html.replace("\r", " ") - driver.execute_script("""document.write("%s")""" % html) - # @TODO good grief, I can't just go putting sleeps around the place. - # how else to tell when the document.write has finished rendering, and - # all the images have loaded? - # maybe I need to inject something like this and look for an alert? - # http://imagesloaded.desandro.com - time.sleep(2) - - #p = driver.get_screenshot_as_file("/Users/matt/Desktop/test5.png") - p = driver.get_screenshot_as_png() - im = Image.open(io.BytesIO(p)) - return _rle_image(im) - -# ~~~~ -# Test -# ~~~~ - -if __name__ == '__main__': - # just see whether the output results in the same number of - # pixels as the input - TEST_PNG_FN = '/Users/matt/Documents/dev-unversioned/sirius2/iconrethink.png' - pixel_count, rle_encoded = rle_image(TEST_PNG_FN) - - output_length = 0 - length_codes = {} - for length, code in TRANSLATE: - length_codes[code] = length - - for b in rle_encoded[3:]: # jump the header bytes - length = ord(b) - if length in length_codes.keys(): - length = length_codes[length] - output_length += length - - # Good, it matches - print "Input length: %d" % pixel_count - print "Output length: %d" % output_length - - \ No newline at end of file diff --git a/app/main/__init__.py b/app/main/__init__.py deleted file mode 100644 index 7e0b78f..0000000 --- a/app/main/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -from flask import Blueprint, render_template, flash, current_app -from flask.ext.wtf import Form -from wtforms import StringField, TextAreaField, BooleanField, SelectField,\ - SubmitField - -from app.models.core import Device -from app.core.commands import set_delivery_and_print - -import pprint -import cgi - -main = Blueprint('main', __name__) - -class SendDeliveryForm(Form): - message = TextAreaField(u'Type a message here') - submit = SubmitField('Send') - -@main.route('/') -def index(): - devices = Device.query.all() - - return render_template('index.html', devices=devices) - -@main.route('/device/', methods=['GET', 'POST']) -def device(device_address): - device = Device.query.get_or_404(device_address) - form = SendDeliveryForm() - sender = current_app.sender - - if form.validate_on_submit(): - html = """

%s

""" % form.message.data - flash('Form submitted') - q = sender.for_device(device) - if q is not None: - dc = set_delivery_and_print(device.device_address, html=html) - q.queue_device_command(dc) - return render_template('dump.html', dump=pprint.pformat(device), form=form) diff --git a/app/models/__init__.py b/app/models/__init__.py deleted file mode 100644 index c2be36f..0000000 --- a/app/models/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# the top-level models module needs to import all models so that the -# database migration tool can detect them -from .core import BridgeCommand, DeviceCommand, Bridge, Device, PendingClaim \ No newline at end of file diff --git a/app/models/core.py b/app/models/core.py deleted file mode 100755 index 1e4056d..0000000 --- a/app/models/core.py +++ /dev/null @@ -1,115 +0,0 @@ -from app import db - -import json - -# BridgeCommand has -# - timestamp (datetime in UTC) -# - bridge_address (store the hex value as a string) -# - id (primary key) -# - return_code -- init as null, integer -# - json_payload -- text -class BridgeCommand(db.Model): - __tablename__ = 'bridge_commands' - id = db.Column(db.Integer, primary_key=True) - 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.String, nullable=False) - return_code = db.Column(db.SmallInteger, nullable=True) - - def to_json(self): - try: - json_payload = json.loads(self.json_payload) - except: - json_payload = None - json_hash = { - 'type': 'BridgeCommand', - 'bridge_address': self.bridge_address, - 'command_id': self.id, - 'json_payload': json_payload, - 'timestamp': self.timestamp.isoformat() - } - return json.dumps(json_hash, encoding='utf-8') - -# DeviceCommand has -# - device_address (store the hex value as a string) -# - id (primary key) -# - binary_payload (store base64 encoded) -# - state (ready, failed, delivered, skipped) -# - deliver_at (timestamp) -class DeviceCommand(db.Model): - __tablename__ = 'device_commands' - id = db.Column(db.Integer, primary_key=True) - device_address = db.Column(db.String, nullable=False) - binary_payload = db.Column(db.Text, nullable=False) - state = db.Column(db.String, nullable=False) - deliver_at = db.Column(db.DateTime, nullable=False) - return_code = db.Column(db.SmallInteger, nullable=True) - - def to_json(self): - json_hash = { - 'command_id': self.id, - 'type': 'DeviceCommand', - 'device_address': self.device_address, - 'binary_payload': self.binary_payload - } - return json.dumps(json_hash, encoding='utf-8') - -class Bridge(db.Model): - __tablename__ = 'bridges' - bridge_address = db.Column(db.String, primary_key=True) - 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.Integer, 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=Device.make_hardware_xor(device_address)) - db.session.add(d) - db.session.commit() - return d - - @staticmethod - def make_hardware_xor(device_address): - # the hardware_xor from device_address 000d6f000273ce0b - # should match the hardware_xor from claim_code - # ps2f-gsjg-8wsq-7hc4 - # and (I think) 000d6f00015ff77f should lead to 6290192 - # and match claim code 6xwh441j8115zyrh - # and this 0011223344aabb01 leads to 10087971 - b = bytearray.fromhex(device_address) - - # little endian - b.reverse() - - claim_address = bytearray(3) - claim_address[0] = b[0] ^ b[5] - claim_address[1] = b[1] ^ b[3] ^ b[6] - claim_address[2] = b[2] ^ b[4] ^ b[7] - - result = claim_address[2] << 16 | claim_address[1] << 8 | claim_address[0] - - return result - - -class PendingClaim(db.Model): - __tablename__ = 'pending_claims' - id = db.Column(db.Integer, primary_key=True) - claim_code = db.Column(db.String, nullable=False) - hardware_xor = db.Column(db.String, nullable=False) diff --git a/app/queues.py b/app/queues.py deleted file mode 100644 index 3e33a35..0000000 --- a/app/queues.py +++ /dev/null @@ -1,136 +0,0 @@ -from app.models.core import BridgeCommand, DeviceCommand - -import gevent - -class CommandSender(object): - """ Single object per process to send bridge and device commands - down the Websocket connection. - @TODO use Reddis to pass information around between processes. - """ - - def __init__(self): - self.queues = {} # ws: _CommandQueue - self.did_send_image = False # temporary - - def register(self, ws, bridge): - # when a power_on event is received from a bridge, - # register its websocket so that bridge (and devices - # connected to that bridge) can receive commands - for k, v in self.queues.items(): - if bridge.bridge_address == v.bridge: - self.queues.pop(k) - q = _CommandQueue(bridge=bridge) - self.queues[ws] = q - # queue old bridge commands - commands = BridgeCommand.query.filter_by(state='ready', bridge_address=bridge.bridge_address).all() - for c in commands: - q.queue_bridge_command(c) - - def device_connect(self, bridge, device): - # device can be connected only to one bridge at a time - qb = self.for_bridge(bridge) - for q in [qq for qq in self.queues.values() if qq != qb]: - if q.has_device(device): - q.remove_device(device) - qb.add_device(device) - # queue old device commands - commands = DeviceCommand.query.filter_by(state='ready', device_address=device.device_address).all() - for c in commands: - qb.queue_device_command(c) - - def device_disconnect(self, bridge, device): - q = self.for_bridge(bridge) - q.remove_device(device) - - def for_bridge(self, bridge): - queues = [q for q in self.queues.values() if q.bridge == bridge.bridge_address] - if queues: - return queues[0] - else: - return None - - def for_device(self, device): - queues = [q for q in self.queues.values() if q.has_device(device)] - if queues: - return queues[0] - else: - return None - - def send_commands(self): - """ called periodically by run """ - for ws, q in self.queues.items(): - for c in q.prepare_commands_to_send(): - ws.send(c) - - def _run(self): - while True: - self.send_commands() - gevent.sleep(0.5) - - def run(self): - """ spawns and loops, calling send_commands periodically """ - gevent.spawn(self._run) - - -class _CommandQueue(object): - """ There is one _CommandQueue per websocket connection, - and it handles the command queues and pending commands. - Uses bridge_address and device_address internally. """ - - def __init__(self, bridge): - self.bridge = bridge.bridge_address - self.devices = set() - self.bridge_queue = [] - self.device_queue = {} # device_address: [DeviceCommand] - self.bridge_pending = None - self.device_pending = {} # device_address: None|DeviceCommand - - def add_device(self, device): - da = device.device_address - if da not in self.devices: - print "==> 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[0] != 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/templates/admin.html b/app/templates/admin.html deleted file mode 100644 index 98968ea..0000000 --- a/app/templates/admin.html +++ /dev/null @@ -1,7 +0,0 @@ -{% extends "base.html" %} - -{% block title %}Sirius - Admin{% endblock %} - -{% block page_content %} -

Admin!

-{% endblock %} \ No newline at end of file diff --git a/app/templates/base.html b/app/templates/base.html deleted file mode 100644 index a000d64..0000000 --- a/app/templates/base.html +++ /dev/null @@ -1,37 +0,0 @@ -{% extends "bootstrap/base.html" %} - -{% block title %}Sirius{% endblock %} - -{% block navbar %} - -{% endblock %} - -{% block content %} -
- {% for message in get_flashed_messages() %} -
- - {{ message }} -
- {% endfor %} - - {% block page_content %}{% endblock %} -
-{% endblock %} diff --git a/app/templates/dump.html b/app/templates/dump.html deleted file mode 100644 index fe7eccf..0000000 --- a/app/templates/dump.html +++ /dev/null @@ -1,15 +0,0 @@ -{% extends "base.html" %} -{% import "bootstrap/wtf.html" as wtf %} - -{% block title %}Sirius - Device{% endblock %} - -{% block page_content %} -

Send a message

- -
-{{ dump }}
-
- -{{ wtf.quick_form(form) }} - -{% endblock %} \ No newline at end of file diff --git a/app/templates/index.html b/app/templates/index.html deleted file mode 100644 index b5f7697..0000000 --- a/app/templates/index.html +++ /dev/null @@ -1,14 +0,0 @@ -{% extends "base.html" %} - -{% block title %}Sirius - Index{% endblock %} - -{% block page_content %} -

Hello, World!

- - - -{% endblock %} \ No newline at end of file -- 2.47.3