From f3d8d4d9815b47386dc3eeeda2d0bb3636287082 Mon Sep 17 00:00:00 2001 From: Tom Hunger Date: Mon, 22 Dec 2014 18:05:05 +0000 Subject: [PATCH] Initial protocol sketch for maintaining the bridge/device state. This version is dealing just with state initiated by bridges and devices. The only "user-initiated" state is a fake claims database. The next step is specifying a database schema that allows modifying the little printer world, e.g. claiming one, queuing messages etc. The last step is making sure that these intentions are communicated down-stream + dealing with any errors that can arise (timeout, printer out of paper etc.). --- README.md | 56 ++++++ app/core/claiming.py | 24 +-- app/core/commands.py | 23 +-- app/core/events.py | 12 +- app/core/payload.py | 56 +++--- app/models/core.py | 16 +- notes/capture_notes.md | 110 +++++++++++ notes/listen_ws.py | 21 +++ notes/protocol.proto | 192 +++++++++++++++++++ notes/states.md | 28 +++ requirements.txt | 1 + sirius/__init__.py | 0 sirius/coding/__init__.py | 0 sirius/coding/bitshuffle.py | 22 +++ sirius/coding/claiming.py | 165 +++++++++++++++++ sirius/coding/crc16.py | 39 ++++ sirius/coding/decoders.py | 254 ++++++++++++++++++++++++++ sirius/coding/encoders.py | 96 ++++++++++ sirius/coding/image_encoding.py | 142 ++++++++++++++ sirius/database.py | 22 +++ sirius/protocol/__init__.py | 0 sirius/protocol/messages.py | 146 +++++++++++++++ sirius/protocol/protocol_loop.py | 197 ++++++++++++++++++++ sirius/protocol/test_protocol_loop.py | 162 ++++++++++++++++ sirius/server.py | 38 ++++ sirius/stats.py | 8 + 26 files changed, 1765 insertions(+), 65 deletions(-) create mode 100644 notes/capture_notes.md create mode 100644 notes/listen_ws.py create mode 100644 notes/protocol.proto create mode 100644 notes/states.md create mode 100644 sirius/__init__.py create mode 100644 sirius/coding/__init__.py create mode 100644 sirius/coding/bitshuffle.py create mode 100755 sirius/coding/claiming.py create mode 100644 sirius/coding/crc16.py create mode 100644 sirius/coding/decoders.py create mode 100644 sirius/coding/encoders.py create mode 100644 sirius/coding/image_encoding.py create mode 100644 sirius/database.py create mode 100644 sirius/protocol/__init__.py create mode 100644 sirius/protocol/messages.py create mode 100644 sirius/protocol/protocol_loop.py create mode 100644 sirius/protocol/test_protocol_loop.py create mode 100644 sirius/server.py create mode 100644 sirius/stats.py diff --git a/README.md b/README.md index fbeb14b..6d638d4 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,58 @@ sirius ====== + +First point your bridge at your laptop, port 5002 (or similar). + +Then run: + +```sh +$ bin/gunicorn -k flask_sockets.worker sirius.server:app -b 0.0.0.0:5002 -w 1 +``` + +## Layers + +``` +UI / database +---------------------------- +protocol_loop / send_message +---------------------------- +encoders / decoders +---------------------------- +websockets +---------------------------- +``` + +## Information flow (websockets) + +The entry point for the bridge is in +`sirius.server.api_v1_connection`. Each new websocket connection +spawns a gevent thread (specified by running the flask_sockets +gunicorn worker) which runs `sirius.protocol.protocol_loop.accept` +immediately. `accept` registers the websocket/bridge_address mapping +in a global dictionary; it then loops forever, decoding messages as +they come in. + +While useful for debugging we don't strictly need to store the bridges +and devices in the database. + + +## Information flow (user-facing) + +So far we aren't sending any messages to the devices or bridges other +than encryption keys derived from claim codes (see below). + +In order to inject messages into the flow we need to look up a device +in the `connected_devices` member of +`sirius.protocol.protocol_loop.BridgeState`. If we found a matching +`BridgeState` we can use its websocket to send the message. + + +## Claim codes + +Devices are associated with an account when a user enters a "claim +code". This claim code contains a "hardware-xor" which is derived via +a lossy 3-byte hash from the device address. + +We are also deriving this hardware xor when a device calls home with +an "encryption_key_required". We then connect the device to the claim +code via the hardware-xor and send back the correct encryption key. diff --git a/app/core/claiming.py b/app/core/claiming.py index 07f2df2..fa3b305 100755 --- a/app/core/claiming.py +++ b/app/core/claiming.py @@ -10,7 +10,7 @@ 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. @@ -61,18 +61,18 @@ class InvalidClaimCode(Exception): 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 @@ -107,7 +107,7 @@ def generate_link_key(input): #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 @@ -119,8 +119,8 @@ def generate_link_key(input): output = bytes(output) return output - - + + # Codes go through the following process: # # 1. Cleaning @@ -131,20 +131,20 @@ def generate_link_key(input): # 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(" 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(">> DeviceEventPayload.from_base64('AwAAAAAASgAAAAAAAAB2MC41LTEyLWcyNmU4MmYwAAAAAAAAAAAAAAAAAAAAAHYwLjUtMC1nMTQ4NTljYgAAAAAAAAAAAAAAAAAAAAAABAAAAAEE') +{'event_code': 3, 'event_payload_length': 74, 'reset_text': 'Power on', 'command_invocation_id': 0, 'reset_description': 1025, 'device_type': 0, 'protocol_version': 4, 'loader_build_version': 'v0.5-0-g14859cb\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 'firmware_build_version': 'v0.5-12-g26e82f0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 'name': 'did_power_on'} + + +## device-connect: + +``` +{"bridge_address": "000d6f0002ff7a91", "type": "BridgeEvent", "timestamp": 1346504081.8327731, "json_payload": {"device_address": "000d6f000273ce0b", "name": "device_connect"}} +``` + +## This looks like heart-beat: + +``` +{"device_address": "000d6f000273ce0b", "timestamp": 1346504091.5216279, "bridge_address": "000d6f0002ff7a91", "binary_payload": "AQAAAAAABAAAABQAAAA=", "rssi_stats": [-31, -32, -30], "type": "DeviceEvent"} +``` + +decoding: + +>>> p.DeviceEventPayload.from_base64('AQAAAAAABAAAABQAAAA=') +{'event_payload_length': 4, 'uptime': (20,), 'command_invocation_id': 0, 'event_code': 1, 'name': 'heartbeat'} + + + +# disconnecting the device + +``` +{"bridge_address": "000d6f0002ff7a91", "type": "BridgeEvent", "timestamp": 1346504219.3027338, "json_payload": {"device_address": "000d6f000273ce0b", "name": "device_disconnect"}} +``` + +# intermission (bridge died) + + +# What happens after reset + +``` +{"bridge_address": "000d6f0001b3719d", "type": "BridgeEvent", "timestamp": 1419107228.911871, "json_payload": {"device_address": "000d6f000273ce0b", "name": "encryption_key_required"}} +``` + +I.e. the bridge will send encryption_key_required every ~30 seconds. + +While in this state there will be no device_connected, device_disconnected events. + + +# Notes + +The bridge itself doesn't send any health pings. The only way we know +the bridge is online is by websocket-connect. That's TCP which doesn't +send any health pings so we don't really know whether a bridge by +itself is online. + +# What to model on the high level layer + +- bridges + - address + - devices +- devices + - claim code (entered by user) + - address +- users diff --git a/notes/listen_ws.py b/notes/listen_ws.py new file mode 100644 index 0000000..76cf7c2 --- /dev/null +++ b/notes/listen_ws.py @@ -0,0 +1,21 @@ +"""We accept commands from two sources: The web-UI and from the +individual bridges connecting through websockets. +""" + +import collections +from eventlet import wsgi, websocket +import eventlet +import json + + +@websocket.WebSocketWSGI +def bridge(ws): + print "accepted", ws + while True: + data = json.loads(ws.wait()) + print data + if data['type'] == 'BrideEvent': + if data['json_payload']['name'] == 'encryption_key_required': + ws.send('{name = "add_device_encryption_key"}') + +wsgi.server(eventlet.listen(('', 5002)), bridge) diff --git a/notes/protocol.proto b/notes/protocol.proto new file mode 100644 index 0000000..30c8800 --- /dev/null +++ b/notes/protocol.proto @@ -0,0 +1,192 @@ +// Write down protocol buffer definitions of the protocol as observed +// in the wild. We are not actually using these, I added them for reference. +// +// Note that the protocol is slightly weird in that the json-message +// is polymorphic based on one of its member's values. So the decode +// process is: +// 1) read message.type +// 2) look up decoder based on message.type +// 3) run specific decoder +// +// The same is true for the sub-messages in json_payload and +// binary_payload. + +message BridgeEvent { + // e.g. "000d6f0002ff7a91" + required string bridge_address = 1; + // e.g. "BridgeEvent" + required string type = 2; + // e.g. 1346501618.506583 + required float timestamp = 3; + // json_payload dispatches on type + required Payload json_payload = 4; +} + +message BridgeLog { + // e.g. "000d6f0002ff7a91" + required string bridge_address = 1; + // "BridgeLog" + required string type = 2; + // e.g. 1346501618.506583 + required float timestamp = 3; + // standard python logging stuff + repeated LogRecord records = 4; +} + +message DeviceEvent { + required string bridge_address = 1; + // "DeviceEvent" + required string type = 2; + // e.g. 1346501618.506583 + required float timestamp = 3; + // e.g. 000d6f000273ce0b + required string device_address = 4; + // e.g. "AQAAAAAABAAAABQAAAA=" + required bytes binary_payload = 5; + // [-31, -32, -30] + repeated int rssi_stats = 6; +} + +message LogRecord { + // {"name": "ws4py", "created": 1346503015.4821309, "process": 495, + // "levelno": 40, "processName": "MainProcess", "message": "Failed + // to receive data", "levelname": "ERROR"} + required string name = 1; + // e.g. 1346501618.506583 + required float created = 2; + required int process = 3; + required int levelno = 4; + required string processName = 5; + required string message = 6; + required string levelname = 7; +} + +// poweron is the json_payload for a BridgeEvent +message PowerOn { + // power_on: + required string name = 1; + required string model = 2; // e.g. B + // "v2.3.1-f3c7946", + required string firmware_version = 3; + // "0x46C5" + required string ncp_version = 4; + // "local_ip_address" : "192.168.2.117", + required string local_ip_address = 5; + // "mac_address" : "40:d8:55:19:77:2e", + required string mac_address = 6; + // "uptime" : "830.55 798.31", + required string uptime = 7; + // "uboot_environment" : + required bytes uboot_environment = 8; + required NetworkInfo network_info = 9; +} + +message NetworkInfo { + // "node_type" : "EMBER_COORDINATOR", + required string node_type = 1; + // "security_level" : 5, + required int security_level = 2; + // "security_profile" : "Custom", + required string security_profile = 3; + // "network_status" : "EMBER_JOINED_NETWORK", + required string network_status = 4; + // "pan_id" : "0xDCC9", + required string pan_id = 5; + // "node_eui64" : "0x000d6f0002ff7a91", + required string node_eui64 = 6; + // "power" : 8, + required int power = 7; + // "node_id" : "0x0000", + required string node_id = 8; + // "channel" : 16, + required int channel = 9; + // "radio_power_mode" : "EMBER_TX_POWER_MODE_BOOST", + required string radio_power_mode = 10; + // "extended_pan_id" : "0x42455247b439420c" + required string extended_pan_id = 11; +} + +enum EmberNetworkStatus { + EMBER_NO_NETWORK = 0; + EMBER_JOINING_NETWORK = 1; + EMBER_JOINED_NETWORK = 2; + EMBER_JOINED_NETWORK_NO_PARENT = 3; + EMBER_LEAVING_NETWORK = 4; +} +enum EmberSecurityProfile { + NONE_SECURITY_PROFILE = 0; + HA_SECURITY_PROFILE = 1; + SE_SECURITY_PROFILE_TEST = 2; + SE_SECURITY_PROFILE_FULL = 3; +} + +enum EmberNodeType { + EMBER_UNKNOWN_DEVICE = 0; + EMBER_COORDINATOR = 1; + EMBER_ROUTER = 2; + EMBER_END_DEVICE = 3; + EMBER_SLEEPY_END_DEVICE = 4; + EMBER_MOBILE_END_DEVICE = 5; +} + +enum EmberPowerMode { + EMBER_TX_POWER_MODE_DEFAULT = 0; + EMBER_TX_POWER_MODE_BOOST = 1; + EMBER_TX_POWER_MODE_ALTERNATE = 2; + EMBER_TX_POWER_MODE_BOOST_AND_ALTERNATE = 3; // 1 | 2 +} + +message BridgeCommand { + // type == "BridgeCommand" + required string type = 1; + + // AFAICT command_id is a unique id that's used to match requests + // and responses. + required int command_id = 2; + required string bridge_address = 3; + required AddDeviceEncryptionKey json_payload = 4; + required float timestamp = 5; +} + + +// Possible bridge commands = ['add_device_encryption_key', 'leave', +// 'form', 'reboot', 'restart', 'set_cloud_log_level'] +message AddDeviceEncryptionKey { + // 'add_device_encryption_key', + required string name = 1; + message Params { + // 'device_address': device.device_address, + required bytes device_address = 1; + // 'encryption_key': pending_claims[device.hardware_xor] + required bytes encryption_key = 2; + }; + required Params params = 2; +} + + +// The little printer (barringer) device type is 0x01. +enum LittlePrinterCommand { + 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; +} + +enum LittlePrinterCommandResponse { + success = 0; + eui64_not_found = 0x01; + failed_network = 0x02; + invalid_sequence = 0x20; + busy = 0x30; + invalid_size = 0x80; + invalid_devicetype = 0x81; + filesystem_error = 0x82; + filesystem_invalid_id = 0x90; + filesystem_no_free_filehandles = 0x91; + filesystem_write_error = 0x92; + bridge_error = 0xff; +} diff --git a/notes/states.md b/notes/states.md new file mode 100644 index 0000000..0e0ad31 --- /dev/null +++ b/notes/states.md @@ -0,0 +1,28 @@ +# (OBSOLETE) + +# Possible events: + +- BridgeEvent (json_payload) + - power_on + - encryption_key_required + - device_connect + - device_disconnect +- BridgeLog (list of records) +- BridgeCommandResponse +- DeviceEvent +- DeviceCommandResponse +- WifiEvent + +# Bridge states + +- unknown (never seen) +- up (websocket connected) +- down + +# Device events + +- unknown (never seen) +- unclaimed_encryption_key_required +- claimed_encryption_key_required (encryption_key_required is sent as a BridgeEvent but it's really a device event). +- claimed_connected +- claimed_disconnected diff --git a/requirements.txt b/requirements.txt index 4e2ed5c..64b7e7f 100755 --- a/requirements.txt +++ b/requirements.txt @@ -23,3 +23,4 @@ pycrypto==2.6.1 redis==2.10.3 selenium==2.43.0 wsgiref==0.1.2 +nose diff --git a/sirius/__init__.py b/sirius/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sirius/coding/__init__.py b/sirius/coding/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sirius/coding/bitshuffle.py b/sirius/coding/bitshuffle.py new file mode 100644 index 0000000..705c8f9 --- /dev/null +++ b/sirius/coding/bitshuffle.py @@ -0,0 +1,22 @@ +"""This module contains encoder/decoder functions that are needed but +don't fit neatly into any category. +""" + +def hardware_xor_from_device_address(device_address): + """The "hardware xor" is a 3-byte representation of the device_address. + + :param device_address: A str containing the hex-encoded device address. + """ + 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 diff --git a/sirius/coding/claiming.py b/sirius/coding/claiming.py new file mode 100755 index 0000000..f4c33af --- /dev/null +++ b/sirius/coding/claiming.py @@ -0,0 +1,165 @@ +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(">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/sirius/coding/decoders.py b/sirius/coding/decoders.py new file mode 100644 index 0000000..725a2ed --- /dev/null +++ b/sirius/coding/decoders.py @@ -0,0 +1,254 @@ +"""This module decodes incoming the incoming dictionaries into +"messages". Each message is its own type for easier dispatching. +""" +import base64 +import struct + +from sirius.protocol import messages +from sirius.coding import bitshuffle + + +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 DeviceEventConst(object): + 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 + + RESET_DICT = { + 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", + } + +def decode_message(data): + """Decodes a single incoming message from data. + + :param data: A python dictionary, as decoded from json. + """ + if data['type'] == 'BridgeEvent': + return _decode_bridge_event(data) + + elif data['type'] == 'BridgeLog': + return _decode_bridge_log(data) + + elif data['type'] == 'BridgeCommandResponse': + return _decode_bridge_command_response(data) + + elif data['type'] == 'DeviceEvent': + return _decode_device_event(data) + + else: + return messages.UnknownEvent(data) + + +def _decode_bridge_event(data): + """Decodes a single bridge event from data. + + :param data: A python dictionary, as decoded from json. + """ + try: + name = data['json_payload']['name'] + payload = data['json_payload'] + except KeyError: + return messages.UnknownEvent(data) + + if name == 'power_on': + return messages.PowerOn( + bridge_address=data['bridge_address'], + model=payload['model'], + firmware_version=payload['firmware_version'], + ncp_version=payload['ncp_version'], + local_ip_address=payload['local_ip_address'], + mac_address=payload['mac_address'], + uptime=payload['uptime'], + uboot_environment=payload['uboot_environment'], + network_info=payload['network_info'], + ) + elif name == 'device_connect': + return messages.DeviceConnect( + bridge_address=data['bridge_address'], + device_address=payload['device_address'], + ) + elif name == 'device_disconnect': + return messages.DeviceDisconnect( + bridge_address=data['bridge_address'], + device_address=payload['device_address'], + ) + elif name == 'encryption_key_required': + return messages.EncryptionKeyRequired( + bridge_address=data['bridge_address'], + device_address=payload['device_address'], + hardware_xor=bitshuffle.hardware_xor_from_device_address( + payload['device_address']), + ) + else: + return messages.UnknownEvent(data) + + assert False, "never reached" + + +def _decode_bridge_log(data): + """Decodes the bridge log from data. + + :param data: A python dictionary, as decoded from json. + """ + return messages.BridgeLog( + bridge_address=data['bridge_address'], + records=data['records'], + ) + + +def _decode_device_event(data): + """Decodes a device event from data. + + :param data: A python dictionary, as decoded from json. + """ + try: + payload = data['binary_payload'] + device_address = data['device_address'] + binary = base64.b64decode(payload) + except KeyError: + return messages.UnknownEvent(data) + + offset = 0 + code, command_id, payload_length = \ + struct.unpack_from("LLLLL", binary, offset) + return messages.ProductAnnounce( + device_address=device_address, + product_id='%08x%08x%08x%08x' % (id0, id1, id2, id3), + product_version=version, + ) + + elif code == DeviceEventConst.EVENT_HEARTBEAT: + if payload_length != DeviceEventConst.EVENT_HEARTBEAT_SIZE: + return messages.MalformedEvent( + data, 'Invalid EVENT_HEARTBEAT length. Is: {}. Expected: {}'.format( + payload_length, DeviceEventConst.EVENT_HEARTBEAT_SIZE)) + + 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/sirius/database.py b/sirius/database.py new file mode 100644 index 0000000..6cd2442 --- /dev/null +++ b/sirius/database.py @@ -0,0 +1,22 @@ +"""Fake database to be connected to a real database at some point. + +""" +import collections + + +ClaimedDevice = collections.namedtuple('ClaimedDevice', 'address hardware_xor claim_code') +claimed_devices = { + 0x73c164: ClaimedDevice( + '000d6f000273ce0b', + 0x73c164, + 'n5ry-p6x6-kth7-7hc4', + ), + 0xaacafe: ClaimedDevice( + '000d6f000273ce0b', + 0xaacafe, + 'n5ry-p6x6-kth7-7hc4', + ), +} + +def get_claim_code(hardware_xor): + return claimed_devices.get(hardware_xor) diff --git a/sirius/protocol/__init__.py b/sirius/protocol/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sirius/protocol/messages.py b/sirius/protocol/messages.py new file mode 100644 index 0000000..f3fd387 --- /dev/null +++ b/sirius/protocol/messages.py @@ -0,0 +1,146 @@ +"""Data structures for device events. + +This is a mix of BridgeEvent, DeviceEvent, BridgeCommand, etc. + +TODO: The messages are messy because I added them as I encountered +them. I will group and sort them at some point. +""" +from collections import namedtuple + + +PowerOn = namedtuple('PowerOn', [ + 'bridge_address', + 'model', + 'firmware_version', + 'ncp_version', + 'local_ip_address', + 'mac_address', + 'uptime', + 'uboot_environment', + 'network_info', +]) + +BridgeLog = namedtuple('BridgeLog', [ + 'bridge_address', + 'records', +]) + +EncryptionKeyRequired = namedtuple('EncryptionKeyRequired', [ + 'bridge_address', + 'device_address', + 'hardware_xor', +]) + +DeviceConnect = namedtuple('DeviceConnect', [ + 'bridge_address', + 'device_address', +]) + +DeviceDisconnect = namedtuple('DeviceDisconnect', [ + 'bridge_address', + 'device_address', +]) + +# BridgeCommands +AddDeviceEncryptionKey = namedtuple('AddDeviceEncryptionKey', [ + 'bridge_address', + 'device_address', + 'claim_code', +]) + +BridgeCommandResponse = namedtuple('BridgeCommandResponse', [ + 'bridge_address', + 'command_id', + 'return_code', + 'timestamp', +]) + +SetDeliveryAndPrint = namedtuple('SetDeliveryAndPrint', [ + 'pixels', # 384 pixels wide +]) + +SetDelivery = namedtuple('SetDelivery', [ + 'pixels', +]) + +SetLogLevel = namedtuple('SetLogLevel', [ + 'level', # lower-case string, e.g. 'critical' +]) + +EnableCloudLogging = namedtuple('EnableCloudLogging', []) + +DisableCloudLogging = namedtuple('DisableCloudLogging', []) + +Leave = namedtuple('Leave', []) + +Form = namedtuple('Form', [ + 'channels', # list of numbers +]) + +Pjoin = namedtuple('Pjoin', [ + 'duration', # int +]) + +Restart = namedtuple('Restart', []) + +Reboot = namedtuple('Reboot', []) + +SetCommandPollFrequency = namedtuple('SetCommandPollFrequency', [ + 'frequency', # int in seconds, clamped to [10, 30] +]) + +SetBridgeLogFrequency = namedtuple('SetBridgeLogFrequency', [ + 'frequency', # int in seconds, clamped to [10, 30] +]) + +EnableSlowEvents = namedtuple('EnableSlowEvents', []) + +DisableSlowEvents = namedtuple('DisableSlowEvents', []) + +DeviceHeartbeat = namedtuple('DeviceHeartbeat', [ + 'bridge_address', + 'device_address', + 'uptime', +]) + +DeviceDidPrint = namedtuple('DeviceDidPrint', [ + 'device_address', + 'type', + 'id', +]) + +DeviceDidPowerOn = namedtuple('DeviceDidPowerOn', [ + 'device_address', + 'device_type', + 'firmware_build_version', + 'loader_build_version', + 'protocol_version', + 'reset_description', +]) + +BergCloudProductAnnounce = namedtuple('BergCloudProductAnnounce', [ + 'device_address', + 'product_id', + 'product_version', +]) + +BergCloudStartBinary = namedtuple('BergCloudStartBinary', [ + 'device_address', + 'event_id', + 'data', +]) + +BergCloudStartPacked = namedtuple('BergCloudStartPacked', [ + 'device_address', + 'event_id', + 'data', +]) + +UnknownEvent = namedtuple('UnknownEvent', [ + 'raw_dict', +]) + +MalformedEvent = namedtuple('MalformedEvent', [ + 'raw_data', + 'error', +]) diff --git a/sirius/protocol/protocol_loop.py b/sirius/protocol/protocol_loop.py new file mode 100644 index 0000000..2205b14 --- /dev/null +++ b/sirius/protocol/protocol_loop.py @@ -0,0 +1,197 @@ +"""This file contains the core logic (state machine) for a +websocket-connected bridge. + +The official API is two functions: + +accept(websocket) +send_message(device_address, message) +""" +import messages +import json +import logging + +from sirius.coding import encoders +from sirius.coding import decoders +from sirius import stats +from sirius import database + +logger = logging.getLogger(__name__) + + +# Global ephemeral state. If we move to more than one process then +# either 1) this state needs to move to a central server or 2) we need +# a pubsub message distribution for send_message so the correct +# process can reply. +bridge_by_address = dict() + + +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.websocket = websocket + self.pending_commands = dict() + self.connected_devices = set() + self.next_command_id = 0 + + +def send_message(device_address, message): + """Sends a single message to a connected device. + + :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. + """ + for bridge_state in bridge_by_address.values(): + if device_address in bridge_state.connected_devices: + break + else: + return False + + # Send data through the websocket. + command = encoders.encode_bridge_command( + message, + bridge_state.next_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 + + return True + + +def accept(ws): + """Receiving loop for a single websocket. We're storing the websocket + in a BridgeState class keyed on the bridge address. This is + necessary to later find connected devices in `send_message`. + + :param ws: A gevent websocket object. + """ + loop = _decoder_loop(ws) + power_on = loop.next() + + # stats & logging + stats.inc('accepted.count') + stats.inc('by_type.{}.count'.format(type(power_on).__name__)) + logger.info("New connection from %r.", power_on) + + # Note that there is a potential race condition. If the bridge + # responds to command_id 0 over a restart we may receive that + # response just after we have sent out a command with id 0, but + # it's the wrong response from an earlier command. + bridge_state = BridgeState(websocket=ws, address=power_on.bridge_address) + bridge_by_address[power_on.bridge_address] = bridge_state + + try: + for message in loop: + # stats & logging + stats.inc('received.count') + stats.inc('by_type.{}.count'.format(type(message).__name__)) + logger.debug("Received %r.", message) + + _accept_step(message, bridge_state) + + # If the iterator closes normally then the client closed the + # socket and we clean up normally. + stats.inc('client_closed.count') + + except: + stats.inc('protocol_loop_exception.count') + logger.exception("Unexpected bridge error.") + raise + + finally: + logger.debug("Bridge disonnected: %r.", bridge_state) + del bridge_by_address[power_on.bridge_address] + + +def _decoder_loop(ws): + """We run one decoder loop for every connected web socket. The first + message is always PowerOn which contains a bridge_address. + + :param ws: A gevent websocket object. + """ + while True: + raw_data = ws.receive() + if raw_data == '': + break # websocket closed by client + + try: + data = json.loads(raw_data) + except ValueError: + stats.inc('json_decode_error.count') + yield messages.MalformedEvent(raw_data, 'Could not decode json.') + + yield decoders.decode_message(data) + + +def _accept_step(x, bridge_state): + """Handle a single decoded message. This is in its own function to + simplify testing and to keep the if/elif indentation low. + + :param x: A type from sirius.protocol.message + :param bridge_state: The BridgeState for this connection + """ + if type(x) == messages.DeviceConnect: + bridge_state.connected_devices.add(x.device_address) + + elif type(x) == messages.DeviceDisconnect: + bridge_state.connected_devices.discard(x.device_address) + + elif type(x) == messages.BridgeLog: + pass # TODO - write log to a place + + elif type(x) == messages.EncryptionKeyRequired: + bridge_state.connected_devices.add(x.device_address) + + claimed_device = database.get_claim_code(x.hardware_xor) + if claimed_device is None: + # It's OK to have an unclaimed device, we just ignore it + # for now. + stats.inc('unclaimed.encryption_key_required.count') + return + + add_key = messages.AddDeviceEncryptionKey( + bridge_address=x.bridge_address, + device_address=x.device_address, + claim_code=claimed_device.claim_code, + ) + + send_message(x.device_address, add_key) + + elif type(x) == messages.DeviceHeartbeat: + bridge_state.connected_devices.add(x.device_address) + + elif type(x) == messages.PowerOn: + logging.info('Received superfluous PowerOn message. ' + 'Probably backlog from previous socket error.') + + elif type(x) == messages.DeviceDidPowerOn: + # We don't really care about this one other than for debugging + # maybe. + bridge_state.connected_devices.add(x.device_address) + + elif type(x) == messages.DeviceDidPrint: + # TODO - This message is sent for two reasons: + # 1) The user pressed the button and nothing was in the queue + # "hello, I don't have anything to print [...]" + # 2) We printed a queued job. + # In case 2 we want to ack the print in the database. + pass + + elif type(x) == messages.BridgeCommandResponse: + if x.command_id not in bridge_state.pending_commands: + logger.error('Unexpected response (command_id not known) %r', x) + return + + # TODO: some commands need special handling. E.g. what happens + # on invalid claim codes? How do we communicate send-errors or + # timeouts back to the user? + else: + assert False, "Unexpected message {}".format(x) diff --git a/sirius/protocol/test_protocol_loop.py b/sirius/protocol/test_protocol_loop.py new file mode 100644 index 0000000..e944c9b --- /dev/null +++ b/sirius/protocol/test_protocol_loop.py @@ -0,0 +1,162 @@ +"""Simple protocol_loop steps. + +Run like: + +$ bin/nosetests sirius/ +""" +import unittest + +from sirius.protocol import messages +from sirius.protocol import protocol_loop + +# The messages are taken from a real network dump so slightly ugly. +m_power_on = messages.PowerOn( + bridge_address=u'000d6f0001b3719d', + model=u'A', + firmware_version=u'v2.3.1-f3c7946', + ncp_version=u'0x46C5', + local_ip_address=u'192.168.1.98', + mac_address=u'40:d8:55:01:c1:b3', + uptime=u'4135.25 4083.53', + uboot_environment=u'truncated', + network_info={ + u'network_status': u'EMBER_JOINED_NETWORK', + u'power': 8, + u'node_eui64': u'0x000d6f0001b3719d', + u'pan_id': u'0xDF3A', + u'node_type': u'EMBER_COORDINATOR', + u'node_id': u'0x0000', + u'security_level': 5, + u'extended_pan_id': u'0x42455247fbbbbd7f', + u'security_profile': u'Custom', + u'channel': 25, + u'radio_power_mode': u'EMBER_TX_POWER_MODE_BOOST', + } +) + +m_hearbeat = messages.DeviceHeartbeat( + bridge_address=u'000d6f0001b3719d', + device_address=u'000d6f000273ce0b', + uptime=(1,)) + +m_hearbeat_2 = messages.DeviceHeartbeat( + bridge_address=u'000d6f0001b3719d', + device_address=u'000d6f00cafecccc', + uptime=(1,)) + +m_bridge_log = messages.BridgeLog( + bridge_address=u'000d6f0001b3719d', + records=[ + {u'name': u'cloud.socketclient', u'created': 1419267045.369878, + u'process': 490, u'levelno': 30, u'processName': u'MainProcess', + u'message': u'Closed down websocket, code: 1006, reason: Going away', + u'levelname': u'WARNING'}, + {u'name': u'cloud.socket', u'created': 1419267045.569464, + u'process': 490, u'levelno': 40, u'processName': u'MainProcess', + u'message': u'Socket connection refused', u'levelname': u'ERROR'} + ] +) + +m_device_connect = messages.DeviceConnect( + bridge_address=u'000d6f0001b3719d', + device_address=u'000d6f000273ce0b') + +m_device_disconnect = messages.DeviceDisconnect( + bridge_address=u'000d6f0001b3719d', + device_address=u'000d6f000273ce0b') + +m_encryption_key_required = messages.EncryptionKeyRequired( + bridge_address=u'000d6f0001b3719d', + device_address=u'000d6f000273ce0b', + hardware_xor=0xaacafe, +) + +m_command_response = messages.BridgeCommandResponse( + bridge_address=u'000d6f0001b3719d', + command_id=10, + return_code=0, + timestamp=0, +) + +class FakeWebsocket: + "Use to create an in-memory a BridgeState." + def __init__(self): + self.messages = [] + def send(self, message): + self.messages.append(message) + + +class TestNormalFlow(unittest.TestCase): + "A bunch of smoke tests that exercise the _accept_step." + def setUp(self): + self.bridge_state = protocol_loop.BridgeState( + FakeWebsocket(), m_power_on.bridge_address) + + def test_bridge_log(self): + protocol_loop._accept_step(m_bridge_log, self.bridge_state) + + def test_heartbeat(self): + self.assertNotIn(m_hearbeat.device_address, self.bridge_state.connected_devices) + + protocol_loop._accept_step(m_hearbeat, self.bridge_state) + + self.assertIn(m_hearbeat.device_address, self.bridge_state.connected_devices) + + def test_device_connect(self): + self.assertNotIn(m_device_connect.device_address, self.bridge_state.connected_devices) + + protocol_loop._accept_step(m_device_connect, self.bridge_state) + + self.assertIn(m_device_connect.device_address, self.bridge_state.connected_devices) + + def test_device_disconnect(self): + self.assertNotIn(m_hearbeat.device_address, self.bridge_state.connected_devices) + + protocol_loop._accept_step(m_device_connect, self.bridge_state) + protocol_loop._accept_step(m_device_disconnect, self.bridge_state) + + self.assertNotIn(m_hearbeat.device_address, self.bridge_state.connected_devices) + + def test_encryption_key_required(self): + protocol_loop.bridge_by_address = { + self.bridge_state.address: self.bridge_state + } + protocol_loop._accept_step(m_encryption_key_required, self.bridge_state) + + self.assertEquals(len(self.bridge_state.websocket.messages), 1) + + +class TestBrokenFlow(unittest.TestCase): + "Check unexpected interactions." + def setUp(self): + self.bridge_state = protocol_loop.BridgeState( + None, m_power_on.bridge_address) + + def test_device_double_disconnect(self): + self.assertNotIn(m_hearbeat.device_address, self.bridge_state.connected_devices) + + protocol_loop._accept_step(m_device_connect, self.bridge_state) + protocol_loop._accept_step(m_device_disconnect, self.bridge_state) + protocol_loop._accept_step(m_device_disconnect, self.bridge_state) + + self.assertNotIn(m_hearbeat.device_address, self.bridge_state.connected_devices) + + def test_device_double_power_on(self): + protocol_loop._accept_step(m_power_on, self.bridge_state) + protocol_loop._accept_step(m_power_on, self.bridge_state) + + def test_command_response_unseed_command_id(self): + protocol_loop._accept_step(m_command_response, self.bridge_state) + + +class TestMultiDevice(unittest.TestCase): + "What happens when we have more than one device." + def setUp(self): + self.bridge_state = protocol_loop.BridgeState( + FakeWebsocket(), m_power_on.bridge_address) + + def test_two_heartbeats(self): + protocol_loop._accept_step(m_hearbeat, self.bridge_state) + protocol_loop._accept_step(m_hearbeat_2, self.bridge_state) + + self.assertEquals(len(self.bridge_state.connected_devices), 2) diff --git a/sirius/server.py b/sirius/server.py new file mode 100644 index 0000000..a7d1577 --- /dev/null +++ b/sirius/server.py @@ -0,0 +1,38 @@ +"""Main server entry. Run like: + +$ bin/gunicorn -k flask_sockets.worker sirius.server:app -b 0.0.0.0:5002 -w 1 +""" + +import logging +import flask +import flask_sockets + +from sirius.protocol import protocol_loop +from sirius import stats + +logger = logging.getLogger(__name__) + + +def create_app(): + sockets = flask_sockets.Sockets() + + logging.basicConfig(level=logging.DEBUG) + + app = flask.Flask(__name__) + app.debug = True + sockets.init_app(app) + + @app.route('/_/stats') + def showstats(): + "Expose some trivial stats" + return stats.as_text() + + @sockets.route('/api/v1/connection') + def api_v1_connection(ws): + protocol_loop.accept(ws) + + logger.info('Creating app.') + return app + + +app = create_app() diff --git a/sirius/stats.py b/sirius/stats.py new file mode 100644 index 0000000..876d245 --- /dev/null +++ b/sirius/stats.py @@ -0,0 +1,8 @@ +import collections +STATS = collections.defaultdict(int) + +def as_text(): + return '
' + '\n'.join('{} {}'.format(k, v) for k, v in STATS.items())
+
+def inc(key):
+    STATS[key] += 1
-- 
2.47.3