+++ /dev/null
-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
+++ /dev/null
-from flask import Blueprint, render_template
-
-admin = Blueprint('admin', __name__)
-
-@admin.route('/')
-def index():
- return render_template('admin.html')
+++ /dev/null
-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
+++ /dev/null
-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("<Q", raw_value & 0xffffffffffffffff)
- #server_crc = crc16(data_for_crc) # this works in Python3
- server_crc = crc16( bytearray(data_for_crc) ) # this works in Python2
-
- if server_crc != crc:
- raise InvalidClaimCode("CRC problem")
-
- # Pack the 40-bit number as a LE long long, and then truncate back to 5 bytes
- packed_secret = struct.pack("<Q", secret)[0:5]
- link_key = generate_link_key(packed_secret)
- link_key_b64 = base64.encodestring(link_key)
-
- return (hardware_xor, link_key_b64)
-
-
-# ~~~~
-# Test
-# ~~~~
-
-if __name__ == '__main__':
- claim_code = '6xwh-441j-8115-zyrh'
- expected_encryption_key = b'F7D9bmztHV32+WJScGZR0g==\n'
- _, calculated_encryption_key = process_claim_code(claim_code)
- print("Expected: %s" % expected_encryption_key)
- print("Calculated: %s" % calculated_encryption_key)
+++ /dev/null
-from app import db
-
-from app.models.core import BridgeCommand, DeviceCommand, Bridge, Device
-from ..image_encoding import rle_image, rle_html
-from .claiming import process_claim_code
-
-import struct
-from datetime import datetime
-import base64
-import json
-
-# device commands are
-# set_delivery_and_print
-# set_delivery
-# set_delivery_and_print_no_face
-# set_delivery_no_face
-# set_personality
-# set_quip
-# firmware_update
-
-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/riley.png'
-
-# some constants
-DEVICE_TYPE = '\x01' # rBergCloud::Barringer::DEVICE_TYPE in weminuche-server
-COMMAND_ID = {
- 'set_delivery_and_print': 0x0001
-}
-
-def add_device_encryption_key(bridge, device):
- # populate pending_claims. @TODO back onto database instead
- claim_codes = ['6xwh-441j-8115-zyrh', 'ps2f-gsjg-8wsq-7hc4',
- 'eocd-880w-be80-vc36']
- pending_claims = {} # hardware_xor: encryption_key
- for c in claim_codes:
- hw, key = process_claim_code(c)
- pending_claims[hw] = key
-
- if not pending_claims.has_key(device.hardware_xor):
- print "Device %r %r" % (device.device_address, device.hardware_xor)
- for hw, key in pending_claims.items():
- print "Pending claim %r %r" % (hw, key)
- raise Exception("No pending claim for device")
-
- payload = {
- 'name': 'add_device_encryption_key',
- 'params': {
- 'device_address': device.device_address,
- 'encryption_key': pending_claims[device.hardware_xor]
- }
- }
-
- command = BridgeCommand(
- bridge_address=bridge.bridge_address,
- json_payload=json.dumps(payload),
- timestamp=datetime.utcnow(),
- state=u'ready'
- )
-
- db.session.add(command)
- db.session.commit()
-
- return command
-
-def set_delivery_and_print_payload(file_id, png_fn, html=None):
- # file ID is a 32 bit ID which is returned as a did_print event
- # three parts:
- # - command header
- # - >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 <cccccccc
- # - encode_image_region
-
- # device type c, reserved byte c,
- # command_name <H (short), file_id <L (long),
- # unimplemented CRC (long is zero)
- command_header = struct.pack("<BBHII", 1, 0, 1, 123, 0)
-
- # get the encoded image now, because we'll need the data later
- if html:
- pixel_count, encoded_image = rle_html(html)
- else:
- pixel_count, encoded_image = rle_image(png_fn)
-
- # payload header region
- printer_control = struct.pack("<13B",
- 0x1d, 0x73, 0x03, 0xe8, # max printer speed
- 0x1d, 0x61, 0xd0, # printer acceleration
- 0x1d, 0x2f, 0x0f, # peak current
- 0x1d, 0x44, 0x80 # max intensity
- )
- printer_byte_count = pixel_count / 8
- n3 = printer_byte_count / 65536
- n3_remainder = printer_byte_count % 65536
- n2 = n3_remainder / 256
- n1 = n3_remainder % 256
- printer_data = struct.pack("<8B", 0x1b, 0x2a, n1, n2, n3, 0, 0, 48)
- header_region = struct.pack("<BI", 0, len(printer_control) + len(printer_data))
- header_region += printer_control + printer_data
-
- # payload including the header
- payload = struct.pack("<IB", len(header_region) + len(encoded_image) + 1, 0)
- payload += header_region + encoded_image
-
- entire_payload = command_header + struct.pack("<I", len(payload)) + payload
-
- return entire_payload
-
-
-def set_delivery_and_print(device_address, html=None):
- command = DeviceCommand(
- device_address=device_address,
- binary_payload=base64.b64encode(set_delivery_and_print_payload(TEST_FILE_ID, TEST_PNG_FN, html=html)),
- state=u'ready',
- deliver_at=datetime.utcnow()
- )
- db.session.add(command)
- db.session.commit()
- return command
+++ /dev/null
-def crc16(buf, crc = 0xffff):
- for b in buf:
- crc = ((crc<<8) ^ CCITT_16[(crc>>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
- ]
+++ /dev/null
-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'])
+++ /dev/null
-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("<BBHLLL", data, 0)
-
- # can only unwrap certain commands
- if device_type != 1:
- raise ArgumentError, "Can only unwrap Little Printer commands"
- if command_name_id not in DeviceCommandPayload.COMMANDS.values():
- raise ArgumentError, "Unknown command name ID"
- if command_name_id == DeviceCommandPayload.COMMANDS['firmware_update']:
- raise ArgumentError, "Can't handle firmware_update command"
-
- # move to payload
- offset += 1 + 1 + 2 + 4 + 4 + 4
-
- # payloads encoded by printable_command -> encode_files have a
- # similar format: a list of files, each as
- # - length+1 (<L)
- # - 0 for no encryption and no IV (<B)
- # - the file
- files = []
- while offset < len(data):
- file_length_plus_one, reserved_byte = struct.unpack_from("<LB", data, offset)
- offset += 5
- files.append( data[offset:offset+file_length_plus_one-1] )
- offset += file_length_plus_one-1
- # when finished, offset should be the data length
- assert offset == len(data)
-
- return (device_type, reserved_byte, command_name_id, file_id, reserved_long, payload_length, files)
-
-
-class DeviceEventPayload(object):
- # Barringer protocol
- EVENT_HEADER_SIZE = 10
-
- EVENT_HEARTBEAT = 1
- EVENT_DID_PRINT = 2
- EVENT_DID_POWER_ON = 3
-
- EVENT_HEARTBEAT_SIZE = 4
- EVENT_DID_PRINT_SIZE = 5
- EVENT_DID_POWER_ON_SIZE_LONG = 74 # Using fragmentation
- EVENT_DID_POWER_ON_SIZE_SHORT = 58 # No fragmentation
-
- resetDict = {
- 0x0000 : "Undeterminable cause",
- 0x0100 : "FIB bootloader",
- 0x0200 : "Ember bootloader",
- 0x0300 : "External reset",
- 0x0400 : "Power on",
- 0x0500 : "Watchdog",
- 0x0600 : "Software triggered",
- 0x0700 : "Software crash",
- 0x0800 : "Flash failure",
- 0x0900 : "Fatal error",
- 0x0a00 : "Access fault"}
-
- @classmethod
- def from_base64(cls, base64_payload):
- data = base64.b64decode(base64_payload)
-
- return_hash = {}
-
- offset = 0
- eventCode, commandInvocationId, eventPayloadLength = \
- struct.unpack_from("<HII", data, offset)
-
- return_hash['event_code'] = eventCode
- return_hash['command_invocation_id'] = commandInvocationId
- return_hash['event_payload_length'] = eventPayloadLength
-
- # Move on to the actual payload and switch
- offset += 2 + 4 + 4
-
- if len(data) != (DeviceEventPayload.EVENT_HEADER_SIZE + eventPayloadLength):
- return_hash['error'] = 'Invalid event payload length of %d. Should be %d' % (len(data), DeviceEventPayload.EVENT_HEADER_SIZE + eventPayloadLength)
- return return_hash
-
- #
- # Barringer protocol events
- #
- if eventCode & BERGCloudConst.BC_EVENT_FORMAT_MASK == BERGCloudConst.BC_EVENT_START_BINARY:
- return_hash['name'] = "event_binary"
- return_hash['event_id'] = eventCode & BERGCloudConst.BC_EVENT_ID_MASK
- return_hash['data'] = data[offset:]
- elif eventCode & BERGCloudConst.BC_EVENT_FORMAT_MASK == BERGCloudConst.BC_EVENT_START_PACKED:
- return_hash['name'] = "event_packed"
- return_hash['event_id'] = eventCode & BERGCloudConst.BC_EVENT_ID_MASK
- return_hash['data'] = data[offset:]
- elif eventCode == DeviceEventPayload.EVENT_DID_POWER_ON:
- if eventPayloadLength == DeviceEventPayload.EVENT_DID_POWER_ON_SIZE_LONG:
- deviceType, firmwareBuildVersion, loaderBuildVersion, protocolVersion, resetDescription \
- = struct.unpack_from("<I32s32sIH", data, offset)
- elif eventPayloadLength == DeviceEventPayload.EVENT_DID_POWER_ON_SIZE_SHORT:
- deviceType, firmwareBuildVersion, loaderBuildVersion, protocolVersion, resetDescription \
- = struct.unpack_from("<I24s24sIH", data, offset)
- else:
- return_hash['error'] = 'Invalid did_power_on payload length of %d. Should be %d or %d.' % \
- (eventPayloadLength, DeviceEventPayload.EVENT_DID_POWER_ON_SIZE_SHORT, DeviceEventPayload.EVENT_DID_POWER_ON_SIZE_LONG)
- return return_hash
-
- return_hash['name'] = "did_power_on"
- return_hash['device_type'] = deviceType
- return_hash['firmware_build_version'] = firmwareBuildVersion
- return_hash['loader_build_version'] = loaderBuildVersion
- return_hash['protocol_version'] = protocolVersion
-
- # High byte of resetDescription is the reset 'base type', low byte gives
- # extended information about the reset cause.
- if (resetDescription & 0xff00) in DeviceEventPayload.resetDict:
- return_hash['reset_text'] = DeviceEventPayload.resetDict[resetDescription & 0xff00]
- else:
- return_hash['reset_text'] = "Unknown"
-
- return_hash['reset_description'] = resetDescription
-
- elif eventCode == BERGCloudConst.BC_EVENT_PRODUCT_ANNOUNCE:
- if eventPayloadLength != 20:
- return_hash['error'] = 'Invalid product announce payload length of %d. Should be 20' % eventPayloadLength
- return return_hash
-
- id0, id1, id2, id3, version = struct.unpack_from(">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("<I", data, offset)
- return_hash['name'] = "heartbeat"
- return_hash['uptime'] = uptime
-
- elif eventCode == DeviceEventPayload.EVENT_DID_PRINT:
- if eventPayloadLength != DeviceEventPayload.EVENT_DID_PRINT_SIZE:
- return_hash['error'] = 'Invalid did_print payload length of %d. Should be %d' % (eventPayloadLength, DeviceEventPayload.EVENT_DID_PRINT_SIZE)
- return return_hash
-
- print_type, print_id = struct.unpack_from("<BI", data, offset)
- return_hash['name'] = "did_print"
- return_hash['type'] = print_type
- return_hash['id'] = print_id
-
- else:
- return_hash['name'] = "unknown"
- return_hash['code'] = eventCode
-
- return return_hash
-
-
- #init_params = {}
- # fill in here
-
- #instance = cls(**init_params)
- #return instance
+++ /dev/null
-from PIL import Image
-from itertools import groupby
-import struct
-import io
-import time
-
-WHITE = 0
-BLACK = 1
-THRESHOLD = 127
-TRANSLATE = [ (1536, 255), (1152, 254), (768, 253), (384, 252), (251, 251) ]
-
-def pixel_to_bw(p):
- if p == (0, 0, 0, 0):
- return WHITE
- elif p[0] > 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("<BL", 0x01, len(compressed_data)) + compressed_data
-
- # return (number of pixels, output)
- return len(pixels), output
-
-def rle_html(html):
- """ This works:
- <html><body style="width: 384px; margin: 0;">
- <img src="https://dl.dropboxusercontent.com/u/165957/Escher.gif">
- </body></html>
- """
- 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
+++ /dev/null
-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/<device_address>', 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 = """<html><body style="width: 384px; margin: 0;"><h1>%s</h1></body></html>""" % 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)
+++ /dev/null
-# 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
+++ /dev/null
-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)
+++ /dev/null
-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
+++ /dev/null
-{% extends "base.html" %}
-
-{% block title %}Sirius - Admin{% endblock %}
-
-{% block page_content %}
-<h1>Admin!</h1>
-{% endblock %}
\ No newline at end of file
+++ /dev/null
-{% extends "bootstrap/base.html" %}
-
-{% block title %}Sirius{% endblock %}
-
-{% block navbar %}
-<div class="navbar navbar-inverse" role="navigation">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle"
- data-toggle="collapse" data-target=".navbar-collapse">
- <span class="sr-only">Toggle navigation</span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- <a class="navbar-brand" href="{{ url_for('main.index') }}">Sirius</a>
- </div>
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- </ul>
- </div>
- </div>
-</div>
-{% endblock %}
-
-{% block content %}
-<div class="container">
- {% for message in get_flashed_messages() %}
- <div class="alert alert-warning">
- <button type="button" class="close" data-dismiss="alert">×</button>
- {{ message }}
- </div>
- {% endfor %}
-
- {% block page_content %}{% endblock %}
-</div>
-{% endblock %}
+++ /dev/null
-{% extends "base.html" %}
-{% import "bootstrap/wtf.html" as wtf %}
-
-{% block title %}Sirius - Device{% endblock %}
-
-{% block page_content %}
-<h1>Send a message</h1>
-
-<pre>
-{{ dump }}
-</pre>
-
-{{ wtf.quick_form(form) }}
-
-{% endblock %}
\ No newline at end of file
+++ /dev/null
-{% extends "base.html" %}
-
-{% block title %}Sirius - Index{% endblock %}
-
-{% block page_content %}
-<h1>Hello, World!</h1>
-
-<ul>
- {% for d in devices %}
- <li><a href="{{ url_for('main.device', device_address=d.device_address) }}">{{ d.device_address }}</a></li>
- {% endfor %}
-</ul>
-
-{% endblock %}
\ No newline at end of file