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
+
bootstrap = Bootstrap()
db = SQLAlchemy()
+sockets = Sockets()
+
+from . import commands
+
+
+# @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 create_app(config_name):
app = Flask(__name__)
bootstrap.init_app(app)
db.init_app(app)
+ sockets.init_app(app)
# attach routes and custom error pages
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
+ # shouldn't be here, should be attached as a blueprint
+ @sockets.route('/api/v1/connection')
+ def echo_socket(ws):
+ print "here"
+ done_once = False
+ while True:
+ message = ws.receive()
+ pprint(message)
+ print ""
+
+ # temporary logic
+ try:
+ event = json.loads(message)
+ if event['type'] == 'BridgeEvent' and event['json_payload']['name'] == 'encryption_key_required':
+ print "==> encryption_key_required"
+ j = commands.add_device_encryption_key().to_json()
+ ws.send(j)
+ gevent.sleep(0.5)
+ print "===> %s" % j
+ j = commands.set_delivery_and_print().to_json()
+ ws.send(j)
+ if event['type'] == 'BridgeEvent' and done_once == False:
+ j = commands.set_delivery_and_print().to_json()
+ ws.send(j)
+ print "===> tried to send image"
+ done_once = True
+ except:
+ pass
+
+ #ws.send(message)
+
return app
--- /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_address_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_address_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 .models import BridgeCommand
+from .models import DeviceCommand
+from .image_encoding import rle_image
+
+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'
+
+# 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_address = "000d6f00026c6edd"
+ device_address = "000d6f000273ce0b"
+ #claim_code = "6xwh-441j-8115-zyrh"
+ claim_code = "ps2f-gsjg-8wsq-7hc4"
+ _, encryption_key = process_claim_code(claim_code)
+
+ payload = {
+ 'name': 'add_device_encryption_key',
+ 'params': {
+ 'device_address': device_address,
+ 'encryption_key': encryption_key
+ }
+ }
+
+ command = BridgeCommand(
+ bridge_address='000d6f0001b397c3',
+ json_payload=json.dumps(payload),
+ timestamp=datetime.utcnow()
+ )
+ command.id = 1
+ return command
+
+def set_delivery_and_print_payload(file_id, png_fn):
+ # file ID is a 32 bit ID which is returned as a did_print event
+ # three parts:
+ # - command header
+ # - >cxHL
+ # - 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)
+ command_header = struct.pack(">cxHL", '\x01', 1, 1)
+
+ # get the encoded image now, because we'll need the data later
+ pixel_count, encoded_image = rle_image(png_fn)
+
+ # payload header region
+ printer_control = struct.pack("<ccccccccccccc",
+ '\x1d', '\x73', '\x03', '\xe8', # max printer speed
+ '\x1d', '\x61', '\xd0', # printer acceleration
+ '\x1d', '\x2f', '\x0f', # peak current
+ '\x1d', '\x44', '\x80' # 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("<cccccxxc",
+ '\x1b', '\x2a', chr(n1), chr(n2), chr(n3), chr(48))
+ header_region = struct.pack(">xL", len(printer_control) + len(printer_data))
+ header_region += printer_control + printer_data
+
+ # payload including the header
+ payload = struct.pack(">Lx", len(header_region) + len(encoded_image) + 1)
+ payload += header_region + encoded_image
+
+ entire_payload = command_header + struct.pack(">L", len(payload)) + payload
+
+ return entire_payload
+
+def set_delivery_and_print():
+ command = DeviceCommand(
+ device_address='000d6f000273ce0b',
+ binary_payload=base64.b64encode(set_delivery_and_print_payload(TEST_FILE_ID, TEST_PNG_FN)),
+ state='ready',
+ deliver_at=datetime.utcnow()
+ )
+ command.id = 1
+ return command
\ No newline at end of file
--- /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 PIL import Image
+from itertools import groupby
+import array
+import struct
+
+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):
+ # get image pixels
+ im = Image.open(image_fn)
+ 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))
+ output = struct.pack(">%ds" % len(x), str(x))
+
+ # return (number of pixels, output)
+ return len(pixels), output
+from . 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)
+ 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.Enum('ready', 'failed', 'delivered', 'skipped'), nullable=False)
+ deliver_at = db.Column(db.DateTime, nullable=False)
+
+ 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')
-#!/usr/bin/env python3
+#!/usr/bin/env python2.7
import os
manager = Manager(app)
migrate = Migrate(app, db)
-
def make_shell_context():
- return dict(app=app, db=db, User=User, Follow=Follow, Role=Role,
- Permission=Permission, Post=Post, Comment=Comment)
+ return dict(app=app, db=db)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
-
if __name__ == '__main__':
manager.run()
+
+# run with
+#gunicorn -b 0.0.0.0:5000 -k flask_sockets.worker manage:app
Flask-Migrate==1.2.0
Flask-SQLAlchemy==2.0
Flask-Script==2.0.5
+Flask-Sockets==0.1
Jinja2==2.7.3
Mako==1.0.0
MarkupSafe==0.23
+Pillow==2.5.3
SQLAlchemy==0.9.7
Werkzeug==0.9.6
alembic==0.6.7
+gevent==1.0.1
+gevent-websocket==0.9.3
+greenlet==0.4.4
+gunicorn==19.1.1
itsdangerous==0.24
+pycrypto==2.6.1
+wsgiref==0.1.2