]> git.aero2k.de Git - sirius.git/commitdiff
Initial protocol sketch for maintaining the bridge/device state.
authorTom Hunger <tehunger@gmail.com>
Mon, 22 Dec 2014 18:05:05 +0000 (18:05 +0000)
committerTom Hunger <tehunger@gmail.com>
Mon, 22 Dec 2014 18:27:18 +0000 (18:27 +0000)
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.).

26 files changed:
README.md
app/core/claiming.py
app/core/commands.py
app/core/events.py
app/core/payload.py
app/models/core.py
notes/capture_notes.md [new file with mode: 0644]
notes/listen_ws.py [new file with mode: 0644]
notes/protocol.proto [new file with mode: 0644]
notes/states.md [new file with mode: 0644]
requirements.txt
sirius/__init__.py [new file with mode: 0644]
sirius/coding/__init__.py [new file with mode: 0644]
sirius/coding/bitshuffle.py [new file with mode: 0644]
sirius/coding/claiming.py [new file with mode: 0755]
sirius/coding/crc16.py [new file with mode: 0644]
sirius/coding/decoders.py [new file with mode: 0644]
sirius/coding/encoders.py [new file with mode: 0644]
sirius/coding/image_encoding.py [new file with mode: 0644]
sirius/database.py [new file with mode: 0644]
sirius/protocol/__init__.py [new file with mode: 0644]
sirius/protocol/messages.py [new file with mode: 0644]
sirius/protocol/protocol_loop.py [new file with mode: 0644]
sirius/protocol/test_protocol_loop.py [new file with mode: 0644]
sirius/server.py [new file with mode: 0644]
sirius/stats.py [new file with mode: 0644]

index fbeb14b5d2c02ce67a67417e92c088d72522ac4b..6d638d4b88642a638f9ff67c1236ef5bcdcfabf2 100644 (file)
--- 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.
index 07f2df23dc24fdfeb5f1726926e6026eb5a33f67..fa3b305b8af0d76cda3a32794b61479c7675d2b4 100755 (executable)
@@ -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("<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)
 
 
index 0ea4a7d1a9d403affc7bc215f8a41c127817c141..dab0c53ae64554fdf049001e1edf8ce5679e9a4f 100644 (file)
@@ -37,13 +37,13 @@ def add_device_encryption_key(bridge, device):
        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': {
@@ -51,17 +51,17 @@ def add_device_encryption_key(bridge, device):
                        '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):
@@ -80,7 +80,7 @@ def set_delivery_and_print_payload(file_id, png_fn, html=None):
     #       - 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)
@@ -107,15 +107,16 @@ def set_delivery_and_print_payload(file_id, png_fn, html=None):
     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,
@@ -125,4 +126,4 @@ def set_delivery_and_print(device_address, html=None):
     )
     db.session.add(command)
     db.session.commit()
-    return command
\ No newline at end of file
+    return command
index 107b99e563e69ab950eefd63c02505607f8ca93c..b8bcd9706d745824ca79efa284e9c4f52dee88c8 100644 (file)
@@ -17,16 +17,16 @@ from pprint import pprint
 # 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)
@@ -105,7 +105,7 @@ def process_event(ws, event, sender):
         # 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)       
+            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
@@ -126,6 +126,6 @@ def process_event(ws, event, sender):
         # 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)   
+            sender.for_device(device).handle_device_response(c)
     else:
         raise EventProcessingException("Unknown event type: %r" % event['type'])
index 951909cc84737993f21f690e013ee8d6b2eb58c7..0316c8d0eaace13d8d539e94c47fa8cd7863d1a5 100644 (file)
@@ -33,11 +33,11 @@ class DeviceCommandPayload(object):
         '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
@@ -55,7 +55,7 @@ class DeviceCommandPayload(object):
 
         # 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)
@@ -76,16 +76,16 @@ class DeviceCommandPayload(object):
 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",
@@ -98,28 +98,28 @@ class DeviceEventPayload(object):
                  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
         #
@@ -142,60 +142,60 @@ class DeviceEventPayload(object):
                 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
\ No newline at end of file
+        #return instance
index 6c8840ac8d9500d3a553bb0342b0ef91b861b41a..1e4056d929c0c3176e7bb2c917b0cd5c34269468 100755 (executable)
@@ -45,7 +45,7 @@ class DeviceCommand(db.Model):
     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,
@@ -59,7 +59,7 @@ 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)
@@ -67,14 +67,14 @@ class Bridge(db.Model):
             b = cls(bridge_address=bridge_address)
             db.session.add(b)
             db.session.commit()
-        return b           
+        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)
@@ -84,7 +84,7 @@ class Device(db.Model):
             db.session.add(d)
             db.session.commit()
         return d
-    
+
     @staticmethod
     def make_hardware_xor(device_address):
         # the hardware_xor from device_address 000d6f000273ce0b
@@ -94,17 +94,17 @@ class Device(db.Model):
         # 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
 
 
diff --git a/notes/capture_notes.md b/notes/capture_notes.md
new file mode 100644 (file)
index 0000000..ace53e9
--- /dev/null
@@ -0,0 +1,110 @@
+# Capture the connect attempt with nc
+
+```
+$ nc -l -p 5002
+GET /api/v1/connection HTTP/1.1
+Host: 192.168.1.88
+Connection: Upgrade
+Upgrade: websocket
+Sec-WebSocket-Key: LJUqJa44qfNRKHts7rnNsQ==
+Origin: ws://192.168.1.88:5002/api/v1/connection
+Sec-WebSocket-Version: 13
+Sec-WebSocket-Protocol: bergcloud-bridge-v1
+```
+
+Apparently `Sec-WebSocket-Protocol: bergcloud-bridge-v1` is for
+protocol negotiation. CF Accept headers in HTTP.
+
+# Lets provide a websocket and see what happens.
+
+```python
+from eventlet import wsgi, websocket
+import eventlet
+
+@websocket.WebSocketWSGI
+def bridge(ws):
+    while True:
+        print ws.wait()
+        eventlet.sleep(1)
+
+wsgi.server(eventlet.listen(('', 5002)), bridge)
+```
+
+Output is two messages:
+
+```
+{"bridge_address": "000d6f0002ff7a91", "type": "BridgeEvent", "timestamp": 1346500898.052285, "json_payload": {"uptime": "89.52 68.99", "name": "power_on", "uboot_environment": "YXBwZW5kX3J1bl9tb2RlPXNldGVudiBib290YXJncyAke2Jvb3RhcmdzfSBydW5tb2RlPSR7cnVubW9kZX07CmF1dG9sb2FkPW5vCmJhdWRyYXRlPTExNTIwMApib2FyZF9tYW51ZmFjdHVyZV9pbmZvPUJSSURHRUFBMTM0NzIyNTUKYm9vdGFyZ3M9Y29uc29sZT10dHlTMCwxMTUyMDAgcm9vdD0vZGV2L210ZGJsb2NrNiBtdGRwYXJ0cz1hdG1lbF9uYW5kOjEyOGsoYm9vdHN0cmFwKXJvLDI1NmsodWJvb3Qpcm8sMTI4ayhlbnYxKSwxMjhrKGVudjIpLDJNKGxpbnV4KSwxNk0oY29uZmlnKSwtKHJvb3QpIHJ3IHJvb3Rmc3R5cGU9amZmczIKYm9vdGNtZD1ydW4gY2F0Y2hfYnRuOyBydW4gaW5zdF9pZl9yZXF1aXJlZDsgcnVuIGFwcGVuZF9ydW5fbW9kZTsgcnVuIHJlc2V0X2xlZHM7IG5hbmQgcmVhZCAke2tlcm5lbF9sb2FkX2FkZHJlc3N9ICR7a2VybmVsX2ZsYXNoX2FkZHJlc3N9ICR7a2VybmVsX3NpemV9OyBib290bSAke2tlcm5lbF9sb2FkX2FkZHJlc3N9CmJvb3RkZWxheT0xCmNhdGNoX2J0bj1zZXRlbnYgcnVubW9kZSBzdGFuZGFyZDsgc2V0ZW52IGxvb3AgMTsgd2hpbGUgdGVzdCAke2xvb3B9IC1lcSAiMSIgOyBkbyBydW4gZmxhc2hfd2hlbl9oZWxkOyBkb25lOyBzZXRfY2xvdWRfbGVkIDA7IHNldF9ldGhfbGVkIDA7IHNldF96aWdiZWVfbGVkIDAKZXRoYWN0PW1hY2IwCmV0aGFkZHI9NDA6RDg6NTU6MTk6Nzc6MkUKZmFjdG9yeV9mZXRjaF9pbWFnZT1kaGNwOyB0ZnRwIDB4MjA4MDAwMDAgZmFjdG9yeV9mbGFzaC5pbWcKZmFjdG9yeV9ydW5faW1hZ2U9c291cmNlIDB4MjA4MDAwMDAKZmFjdG9yeV9zZXR1cD1ydW4gZmFjdG9yeV9mZXRjaF9pbWFnZSBmYWN0b3J5X3J1bl9pbWFnZQpmYWlsX2xvb3A9c2V0ZW52IGxvb3AgMTsgd2hpbGUgdGVzdCAke2xvb3B9IC1lcSAiMSIgOyBkbyBsZWRfc2VxIDA7IGRvbmUKZmlsZWFkZHI9MjAwMDAwMDAKZmlsZXNpemU9QkI2NzM0CmZsYXNoX3doZW5faGVsZD1nZXRfZW5nX2J0bjsgaWYgdGVzdCAkPyAtZXEgMDsgdGhlbiBzZXRlbnYgcnVubW9kZSBlbmd0ZXN0OyBsZWRfc2VxIDE7IGVsc2Ugc2V0ZW52IGxvb3AgMDsgZmk7CmdhdGV3YXlpcD0xMC4xMC4wLjEKaW5zdF9mZXRjaF9pbWFnZT10ZnRwICR7a2VybmVsTG9hZEFkZHJ9ICR7ZmFjdG9yeVNjcmlwdEZpbGVuYW1lfQppbnN0X2lmX3JlcXVpcmVkPWlmIHRlc3QgIiR7cnVubW9kZX0iID0gImVuZ3Rlc3QiOyB0aGVuIHJ1biBpbnN0X3NldHVwOyBmaTsKaW5zdF9ydW5faW1hZ2U9c291cmNlICR7a2VybmVsTG9hZEFkZHJ9Cmluc3Rfc2V0dXA9cnVuIGZhY3RvcnlfZmV0Y2hfaW1hZ2UgZmFjdG9yeV9ydW5faW1hZ2UKaXBhZGRyPTEwLjEwLjAuMTUyCmtlcm5lbF9maWxlbmFtZT11SW1hZ2UKa2VybmVsX2ZsYXNoX2FkZHJlc3M9MHhhMDAwMAprZXJuZWxfbG9hZF9hZGRyZXNzPTB4MjA4MDAwMDAKa2VybmVsX3NpemU9MHgyMDAwMDAKbWVtX2xvYWRfYWRkcmVzcz0weDIwMDAwMDAwCm5ldG1hc2s9MjU1LjI1NS4yNDguMApvcHRfZmlsZW5hbWU9YnJpZGdlX29wdC5qZmZzMgpvcHRfZmxhc2hfYWRkcmVzcz0weDJhMDAwMApvcHRfc2l6ZT0weDE2MDAwMDAKcmVzZXRfbGVkcz1zZXRfZXRoX2xlZCAwOyBzZXRfemlnYmVlX2xlZCAwOyBzZXRfY2xvdWRfbGVkIDA7CnJvb3Rmc19lcmFzZV9zaXplPTB4ZTc2MDAwMApyb290ZnNfZmlsZW5hbWU9cm9vdGZzLmpmZnMyCnJvb3Rmc19mbGFzaF9hZGRyZXNzPTB4MThBMDAwMApyb290ZnNfd3JpdGVfc2l6ZT0weDE4MDAwMDAKc2VydmVyaXA9MTAuMTAuMC4xCnN0ZGVycj1zZXJpYWwKc3RkaW49c2VyaWFsCnN0ZG91dD1zZXJpYWwKd3JpdGVfa2VybmVsPWVjaG8gIkZldGNoICsgV3JpdGUga2VybmVsIjsgbXcuYiAke21lbV9sb2FkX2FkZHJlc3N9IDB4ZmYgJHtrZXJuZWxfc2l6ZX07IHRmdHAgJHttZW1fbG9hZF9hZGRyZXNzfSAke2tlcm5lbF9maWxlbmFtZX07IG5hbmQgZXJhc2UgJHtrZXJuZWxfZmxhc2hfYWRkcmVzc30gJHtrZXJuZWxfc2l6ZX07IG5hbmQgd3JpdGUgJHttZW1fbG9hZF9hZGRyZXNzfSAke2tlcm5lbF9mbGFzaF9hZGRyZXNzfSAke2tlcm5lbF9zaXplfTsKd3JpdGVfb3B0PWVjaG8gIkZldGNoICsgV3JpdGUgb3B0IjsgbXcuYiAke21lbV9sb2FkX2FkZHJlc3N9IDB4ZmYgJHtvcHRfc2l6ZX07IHRmdHAgJHttZW1fbG9hZF9hZGRyZXNzfSAke29wdF9maWxlbmFtZX07IG5hbmQgZXJhc2UgJHtvcHRfZmxhc2hfYWRkcmVzc30gJHtvcHRfc2l6ZX07IG5hbmQgd3JpdGUgJHttZW1fbG9hZF9hZGRyZXNzfSAke29wdF9mbGFzaF9hZGRyZXNzfSAke29wdF9zaXplfTsKd3JpdGVfcm9vdGZzPWVjaG8gIkZldGNoICsgV3JpdGUgcm9vdGZzIjsgbXcuYiAke21lbV9sb2FkX2FkZHJlc3N9IDB4ZmYgJHtyb290ZnNfd3JpdGVfc2l6ZX07IHRmdHAgJHttZW1fbG9hZF9hZGRyZXNzfSAke3Jvb3Rmc19maWxlbmFtZX07IHNldF9jbG91ZF9sZWQgMTsgbmFuZCBlcmFzZSAke3Jvb3Rmc19mbGFzaF9hZGRyZXNzfSAke3Jvb3Rmc19lcmFzZV9zaXplfTsgbmFuZCB3cml0ZSAke21lbV9sb2FkX2FkZHJlc3N9ICR7cm9vdGZzX2ZsYXNoX2FkZHJlc3N9ICR7cm9vdGZzX3dyaXRlX3NpemV9Owo=", "local_ip_address": "192.168.2.117", "mac_address": "40:d8:55:19:77:2e", "ncp_version": "0x46C5", "network_info": {"network_status": "EMBER_JOINED_NETWORK", "power": 8, "node_eui64": "0x000d6f0002ff7a91", "pan_id": "0xDCC9", "node_type": "EMBER_COORDINATOR", "node_id": "0x0000", "security_level": 5, "extended_pan_id": "0x42455247b439420c", "security_profile": "Custom", "channel": 25, "radio_power_mode": "EMBER_TX_POWER_MODE_BOOST"}, "firmware_version": "v2.3.1-f3c7946", "model": "B"}}
+{"bridge_address": "000d6f0002ff7a91", "type": "BridgeLog", "records": [{"name": "cloud.socket", "created": 1346500877.330243, "process": 465, "levelno": 40, "processName": "MainProcess", "message": "Socket connection refused", "levelname": "ERROR"}, {"name": "cloud.socket", "created": 1346500882.4734199, "process": 465, "levelno": 40, "processName": "MainProcess", "message": "Socket connection refused", "levelname": "ERROR"}, {"name": "cloud.socket", "created": 1346500887.6230842, "process": 465, "levelno": 40, "processName": "MainProcess", "message": "Socket connection refused", "levelname": "ERROR"}, {"name": "cloud.socket", "created": 1346500892.7610618, "process": 465, "levelno": 40, "processName": "MainProcess", "message": "Socket connection refused", "levelname": "ERROR"}], "timestamp": 1346500898.143672}
+```
+
+Note that the bridge also sends power_on after being disconnected from
+it's websocket, e.g. by removing the cable or by killing the websocket server.
+
+# What happens when I plug little printer in?
+
+Getting the following on before sending the device-connect message:
+
+```
+{"device_address": "000d6f000273ce0b", "timestamp": 1346504081.836229, "bridge_address": "000d6f0002ff7a91", "binary_payload": "AwAAAAAASgAAAAAAAAB2MC41LTEyLWcyNmU4MmYwAAAAAAAAAAAAAAAAAAAAAHYwLjUtMC1nMTQ4NTljYgAAAAAAAAAAAAAAAAAAAAAABAAAAAEE", "rssi_stats": [-30, -30, -30], "type": "DeviceEvent"}
+```
+Decoding that:
+
+>>> 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 (file)
index 0000000..76cf7c2
--- /dev/null
@@ -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 (file)
index 0000000..30c8800
--- /dev/null
@@ -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 (file)
index 0000000..0e0ad31
--- /dev/null
@@ -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
index 4e2ed5cd206dc32a473971cb98d8bcedc1e4fb4f..64b7e7fcf65725ac797966e84de0f9aab47af311 100755 (executable)
@@ -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 (file)
index 0000000..e69de29
diff --git a/sirius/coding/__init__.py b/sirius/coding/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/sirius/coding/bitshuffle.py b/sirius/coding/bitshuffle.py
new file mode 100644 (file)
index 0000000..705c8f9
--- /dev/null
@@ -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 (executable)
index 0000000..f4c33af
--- /dev/null
@@ -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("<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)
+
+
+def key_from_claim_code(claim_code):
+    _, key = process_claim_code(claim_code)
+    return key
+
+
+# ~~~~
+# 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)
diff --git a/sirius/coding/crc16.py b/sirius/coding/crc16.py
new file mode 100644 (file)
index 0000000..73ec189
--- /dev/null
@@ -0,0 +1,39 @@
+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
+    ]
diff --git a/sirius/coding/decoders.py b/sirius/coding/decoders.py
new file mode 100644 (file)
index 0000000..725a2ed
--- /dev/null
@@ -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("<HII", binary, offset)
+
+    expected_length = DeviceEventConst.EVENT_HEADER_SIZE + payload_length
+    if len(binary) != expected_length:
+        return messages.MalformedEvent(data, 'Is: {}, should be: {}'.format(
+            len(binary), expected_length))
+
+    if code & BERGCloudConst.BC_EVENT_FORMAT_MASK == BERGCloudConst.BC_EVENT_START_BINARY:
+        return messages.BergCloudStartBinary(
+            device_address=device_address,
+            event_id=code & BERGCloudConst.BC_EVENT_ID_MASK,
+            data=binary[offset:],
+        )
+
+    elif code & BERGCloudConst.BC_EVENT_FORMAT_MASK == BERGCloudConst.BC_EVENT_START_PACKED:
+        return messages.BergCloudStartPacked(
+            device_address=device_address,
+            event_id=code & BERGCloudConst.BC_EVENT_ID_MASK,
+            data=binary[offset:],
+        )
+
+    elif code == DeviceEventConst.EVENT_DID_POWER_ON:
+        if payload_length == DeviceEventConst.EVENT_DID_POWER_ON_SIZE_LONG:
+            power_on_fields = struct.unpack_from("<I32s32sIH", binary, offset)
+
+        elif payload_length == DeviceEventConst.EVENT_DID_POWER_ON_SIZE_SHORT:
+            power_on_fields = struct.unpack_from("<I24s24sIH", binary, offset)
+
+        else:
+            return messages.MalformedEvent(
+                data, 'power_on payload wrong size. Is {}. Expected: {}'.format(
+                len(payload_length),
+            ))
+
+        deviceType, firmwareBuildVersion, loaderBuildVersion, protocolVersion, resetDescription = power_on_fields
+
+        # High byte of resetDescription is the reset 'base type', low byte gives
+        # extended information about the reset cause.
+        reset_description = DeviceEventConst.RESET_DICT.get(resetDescription & 0xff00)
+        if reset_description is None:
+            return messages.MalformedEvent(
+                data, 'Invalid reset description. {}'.foemat(resetDescription))
+
+        return messages.DevicePowerOn(
+            device_address=device_address,
+            device_type=deviceType,
+            firmware_build_version=firmwareBuildVersion,
+            loader_build_version=loaderBuildVersion,
+            protocol_version=protocolVersion,
+            reset_description=resetDescription,
+        )
+
+    elif code == BERGCloudConst.BC_EVENT_PRODUCT_ANNOUNCE:
+        if payload_length != 20:
+            return messages.MalformedEvent(
+                data, 'Invalid BC_EVENT_PRODUCT_ANNOUNCE. Is {}. Expected 20.'.format(payload_length))
+
+        id0, id1, id2, id3, version =  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("<I", binary, offset)
+        return messages.DeviceHeartbeat(
+            bridge_address=data['bridge_address'],
+            device_address=device_address,
+            uptime=uptime,
+        )
+
+    elif code == DeviceEventConst.EVENT_DID_PRINT:
+        if payload_length != DeviceEventConst.EVENT_DID_PRINT_SIZE:
+            return messages.MalformedEvent(
+                data, 'Invalid EVENT_DID_PRINT length. Is: {}. Expected: {}'.format(
+                    payload_length, DeviceEventConst.EVENT_DID_PRINT_SIZE))
+
+        print_type, print_id = struct.unpack_from("<BI", binary, offset)
+        return messages.DeviceDidPrint(
+            device_address=device_address,
+            type=print_type,
+            id=print_id,
+        )
+
+    else:
+        return messages.UnknownEvent(data)
+
+
+def _decode_bridge_command_response(data):
+    """Decodes a BridgeCommandResponse.
+
+    :param data: A python dictionary, as decoded from json.
+    """
+    return messages.BridgeCommandResponse(
+        bridge_address=data['bridge_address'],
+        command_id=data['command_id'],
+        timestamp=data['timestamp'],
+        return_code=data['return_code'],
+    )
diff --git a/sirius/coding/encoders.py b/sirius/coding/encoders.py
new file mode 100644 (file)
index 0000000..1e78e85
--- /dev/null
@@ -0,0 +1,96 @@
+"""Encoders for various commands. All encoders return python
+dictionaries that can be encoded directly as json.
+"""
+import struct
+
+from sirius.coding import image_encoding
+from sirius.coding import claiming
+from sirius.protocol import messages
+
+__all__ = [
+    'encode_bridge_command',
+]
+
+
+def _encode_printer_message(command, pixel_count, rle_image, print_id):
+    """
+    :param command: See LittlePrinterCommand in protocol.proto.
+    :param pixel_count: total number of pixels
+    :param rle_image: Run-length encoded black and white image.
+    :print_id: unique 32-bit number for ack-ing the print (sent back in didprint event)
+    """
+    LITTLE_PRINTER_DEVICE_ID = 1
+
+    # device type c, reserved byte c,
+    # command_name <H (short), file_id <L (long),
+    # unimplemented CRC (long is zero)
+    command_header = struct.pack(
+        "<BBHII",
+        LITTLE_PRINTER_DEVICE_ID, 0,
+        command,
+        print_id, 0,
+    )
+
+    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, n3_remainder = divmod(printer_byte_count, 65536)
+    n2, n1 = divmod(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(rle_image) + 1, 0)
+    payload += header_region + rle_image
+
+    entire_payload = command_header + struct.pack("<I", len(payload)) + payload
+
+    return entire_payload
+
+
+def encode_bridge_command(command, command_id, timestamp):
+    """Encodes a BridgeCommand into a dict that can be serialized as json.
+
+    :param command: A command from messages.py
+    :param command_id: A unique id that is used to ack the command.
+    :param timestamp: unix timestamp. Unclear why this is necessary.
+    """
+    def make(extra):
+        base = {
+            'type': 'BridgeCommand',
+            'bridge_address': command.bridge_address,
+            'command_id': command_id,
+            # Apparently in ISO format?
+            'timestamp': timestamp,
+        }
+        base.update(extra)
+        return base
+
+    if type(command) == messages.AddDeviceEncryptionKey:
+        return make({
+            'json_payload': {
+                'name': 'add_device_encryption_key',
+                'params': {
+                    'device_address': command.device_address,
+                    'encryption_key': claiming.key_from_claim_code(command.claim_code),
+                },
+            },
+        })
+
+    elif type(command) == messages.SetDeliveryAndPrint:
+        pixel_count, pixels = image_encoding.rle(command.pixels)
+        return make({'binary_payload': _encode_printer_message(
+            0x1, pixel_count, pixels, command_id)})
+
+    elif type(command) == messages.SetDelivery:
+        pixel_count, pixels = image_encoding.rle(command.pixels)
+        return make({'binary_payload': _encode_printer_message(
+            0x2, pixel_count, pixels, command_id)})
+
+    else:
+        assert False, "unknown command type: {}".format(command)
diff --git a/sirius/coding/image_encoding.py b/sirius/coding/image_encoding.py
new file mode 100644 (file)
index 0000000..2400681
--- /dev/null
@@ -0,0 +1,142 @@
+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
diff --git a/sirius/database.py b/sirius/database.py
new file mode 100644 (file)
index 0000000..6cd2442
--- /dev/null
@@ -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 (file)
index 0000000..e69de29
diff --git a/sirius/protocol/messages.py b/sirius/protocol/messages.py
new file mode 100644 (file)
index 0000000..f3fd387
--- /dev/null
@@ -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 (file)
index 0000000..2205b14
--- /dev/null
@@ -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 (file)
index 0000000..e944c9b
--- /dev/null
@@ -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 (file)
index 0000000..a7d1577
--- /dev/null
@@ -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 (file)
index 0000000..876d245
--- /dev/null
@@ -0,0 +1,8 @@
+import collections
+STATS = collections.defaultdict(int)
+
+def as_text():
+    return '<pre>' + '\n'.join('{} {}'.format(k, v) for k, v in STATS.items())
+
+def inc(key):
+    STATS[key] += 1