from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
- from .core import coresocket, command_sender
-
+ #from .core import coresocket
+ from .core.command_sender import CommandSender
+ from .core.events import process_event
+
+ @sockets.route('/api/v1/connection')
+ def coresocket(ws):
+ print "here"
+ while True:
+ message = ws.receive()
+ #pprint(message)
+
+ #try:
+ event = json.loads(message)
+ with app.request_context(ws.environ):
+ process_event(ws, event, sender)
+ #except Exception, e:
+ # print "Exception: %r" % e
+
+ sender = CommandSender()
+ sender.run()
+
return app
from app import sockets
from .events import process_event
+from .command_sender import CommandSender
import json
-class CommandBackend(object):
- """ Interface for registering and updating Websocket clients
- to receive commands. """
-
- def __init__(self):
- self.clients = list()
- self.bridge_commands_queue = {} # bridge_address: [bc]
- self.pending_bridge_command = {} # bridge_address: bc
- self.device_commands_queue = {} # device_address: [dc]
- self.pending_device_command = {} # device_address: dc
-
- self.did_send_image = False
-
- def register(self, ws):
- self.clients.append( WebsocketClient(ws) )
-
- def add_bridge_address(self, bridge_address, ws):
- for c in self.clients:
- if c.ws == ws:
- c.bridge_address = bridge_address
-
- def add_device(self, device_address, ws):
- [c.add_device(device_address) for c in self.clients if c.ws == ws]
-
- def remove_device(self, device_address, ws):
- [c.remove_device(device_address) for c in self.clients if c.ws == ws]
-
- def send_to_bridge(self, bridge_address, command):
- matches = [c for c in self.clients if c.bridge_address == bridge_address]
- if matches:
- matches[0].ws.send(command.to_json())
-
- def send_to_device(self, device_address, command):
- matches = [c for c in self.clients if c.has_device(device_address)]
- if matches:
- matches[0].ws.send(command.to_json())
-
-command_sender = CommandBackend()
-#command_sender.run()
-
-class WebsocketClient(object):
-
- def __init__(self, ws):
- self.ws = ws
- self.bridge_address = None
- self.connected_devices = set() # device_address
-
- def add_device(self, device_address):
- self.connected_devices.add(device_address)
-
- def remove_device(self, device_address):
- self.connected_devices.remove(device_address)
-
- def has_device(self, device_address):
- return device_address in self.connected_devices
+#sender = CommandSender()
+#sender.run()
# shouldn't be here, should be attached as a blueprint
# there needs to be a single backend object per process
# using redis, so it works over multiple processes
# see https://devcenter.heroku.com/articles/python-websockets
# for a good pattern
-@sockets.route('/api/v1/connection')
+#@sockets.route('/api/v1/connection')
def coresocket(ws):
print "here"
- command_sender.register(ws)
while True:
message = ws.receive()
#pprint(message)
- try:
- event = json.loads(message)
- process_event(ws, event, command_sender)
- except Exception, e:
- print "Exception: %r" % e
\ No newline at end of file
+ #try:
+ event = json.loads(message)
+ with app.request_context(ws.environ):
+ process_event(ws, event, sender)
+ #except Exception, e:
+ # print "Exception: %r" % e
\ No newline at end of file
#
# Return the link key in Base64, and the XORed hardware_address
def process_claim_code(claim_code):
- hardware_address_xor, secret, crc, raw_value = unpack_claim_code(claim_code)
+ 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)
link_key = generate_link_key(packed_secret)
link_key_b64 = base64.encodestring(link_key)
- return (hardware_address_xor, link_key_b64)
+ return (hardware_xor, link_key_b64)
-def make_hardware_address_xor(device_address):
- # the hardware_address_xor from device_address 000d6f000273ce0b
- # should match the hardware_address_xor from claim_code
+def make_hardware_xor(device_address):
+ # the hardware_xor from device_address 000d6f000273ce0b
+ # should match the hardware_xor from claim_code
# ps2f-gsjg-8wsq-7hc4
b = bytearray.fromhex(device_address)
--- /dev/null
+from ..models.core import BridgeCommand, DeviceCommand
+
+import gevent
+
+class CommandSender(object):
+ """ Single object per process to send bridge and device commands
+ down the Websocket connection.
+ @TODO use Reddis to pass information around between processes.
+ """
+
+ def __init__(self):
+ self.queues = {} # ws: _CommandQueue
+ self.did_send_image = False # temporary
+
+ def register(self, ws, bridge):
+ # when a power_on event is received from a bridge,
+ # register its websocket so that bridge (and devices
+ # connected to that bridge) can receive commands
+ for k, v in self.queues.items():
+ if bridge.bridge_address == v.bridge:
+ self.queues.pop(k)
+ q = _CommandQueue(bridge=bridge)
+ self.queues[ws] = q
+ # queue old bridge commands
+ commands = BridgeCommand.query.filter_by(state='ready', bridge_address=bridge.bridge_address).all()
+ for c in commands:
+ q.queue_bridge_command(c)
+
+ def device_connect(self, bridge, device):
+ # device can be connected only to one bridge at a time
+ qb = self.for_bridge(bridge)
+ for q in [qq for qq in self.queues.values() if qq != qb]:
+ if q.has_device(device):
+ q.remove_device(device)
+ qb.add_device(device)
+ # queue old device commands
+ commands = DeviceCommand.query.filter_by(state='ready', device_address=device.device_address).all()
+ for c in commands:
+ qb.queue_device_command(c)
+
+ def device_disconnect(self, bridge, device):
+ q = self.for_bridge(bridge)
+ q.remove_device(device)
+
+ def for_bridge(self, bridge):
+ queues = [q for q in self.queues.values() if q.bridge == bridge.bridge_address]
+ if queues:
+ return queues[0]
+ else:
+ return None
+
+ def for_device(self, device):
+ queues = [q for q in self.queues.values() if q.has_device(device)]
+ if queues:
+ return queues[0]
+ else:
+ return None
+
+ def send_commands(self):
+ """ called periodically by run """
+ for ws, q in self.queues.items():
+ for c in q.prepare_commands_to_send():
+ ws.send(c)
+
+ def _run(self):
+ while True:
+ self.send_commands()
+ gevent.sleep(0.5)
+
+ def run(self):
+ """ spawns and loops, calling send_commands periodically """
+ gevent.spawn(self._run)
+
+
+class _CommandQueue(object):
+ """ There is one _CommandQueue per websocket connection,
+ and it handles the command queues and pending commands.
+ Uses bridge_address and device_address internally. """
+
+ def __init__(self, bridge):
+ self.bridge = bridge.bridge_address
+ self.devices = set()
+ self.bridge_queue = []
+ self.device_queue = {} # device_address: [DeviceCommand]
+ self.bridge_pending = None
+ self.device_pending = {} # device_address: None|DeviceCommand
+
+ def add_device(self, device):
+ da = device.device_address
+ if da not in self.devices:
+ print "==> Adding device %s to queue for bridge %s" % (da, self.bridge)
+ self.devices.add(da)
+ self.device_queue[da] = []
+ self.device_pending[da] = None
+
+ def remove_device(self, device):
+ da = device.device_address
+ self.devices.remove(da)
+ self.device_queue.pop(da, None)
+ self.device_pending.pop(da, None)
+
+ def has_device(self, device):
+ return device.device_address in self.devices
+
+ def queue_bridge_command(self, command):
+ self.bridge_queue.insert(0, (command.id, command.to_json()))
+
+ def queue_device_command(self, command):
+ da = command.device_address
+ self.device_queue[da].insert(0, (command.id, command.to_json()))
+
+ def handle_bridge_response(self, command):
+ if self.bridge_pending[0] == command.id:
+ self.bridge_pending = None
+ self.bridge_queue = [c for c in self.bridge_queue if c[0] != command.id]
+
+ def handle_device_response(self, command):
+ da = command.device_address
+ if self.device_pending[da][0] == command.id:
+ self.device_pending[da] = None
+ self.device_queue[da] = \
+ [c for c in self.device_queue[da] if c.id != command.id]
+
+ def prepare_commands_to_send(self):
+ commands_to_send = []
+ if self.bridge_pending is None and len(self.bridge_queue) > 0:
+ c = self.bridge_queue.pop()
+ self.bridge_pending = c
+ commands_to_send.append(c[1])
+ for da in self.devices:
+ if self.device_pending[da] is None and \
+ len(self.device_queue[da]) > 0:
+ c = self.device_queue[da].pop()
+ self.device_pending[da] = c
+ commands_to_send.append(c[1])
+ return commands_to_send
\ No newline at end of file
+from app import db
+
from ..models.core import BridgeCommand
from ..models.core import DeviceCommand
from ..image_encoding import rle_image
TEST_FILE_ID = 1
#TEST_PNG_FN = '/Users/matt/Documents/dev-unversioned/sirius2/iconrethink.png'
-TEST_PNG_FN = '/Users/matt/Documents/dev/sirius/tests/iconrethink.png'
+#TEST_PNG_FN = '/Users/matt/Documents/dev/sirius/tests/iconrethink.png'
+TEST_PNG_FN = '/Users/matt/Documents/dev/sirius/tests/riley.png'
# some constants
DEVICE_TYPE = '\x01' # rBergCloud::Barringer::DEVICE_TYPE in weminuche-server
command = BridgeCommand(
bridge_address='000d6f0001b397c3',
json_payload=json.dumps(payload),
- timestamp=datetime.utcnow()
+ timestamp=datetime.utcnow(),
+ state='ready'
)
- command.id = 1
+
+ db.session.add(command)
+ db.session.commit()
+
return command
def set_delivery_and_print_payload(file_id, png_fn):
return entire_payload
-def set_delivery_and_print():
+def set_delivery_and_print(device_address):
command = DeviceCommand(
- device_address='000d6f000273ce0b',
+ device_address=device_address,
binary_payload=base64.b64encode(set_delivery_and_print_payload(TEST_FILE_ID, TEST_PNG_FN)),
state='ready',
deliver_at=datetime.utcnow()
)
- command.id = 1
+ db.session.add(command)
+ db.session.commit()
return command
\ No newline at end of file
+from app.models.core import BridgeCommand, DeviceCommand, Device, Bridge
+from .. import db
+
from . import commands
from .payload import DeviceEventPayload
from . import claiming
from datetime import datetime
+from pprint import pprint
# process_event should...
# - break apart the event
class PendingClaims(object):
def __init__(self):
- self.encryption_keys = {} # hardware_address_xor: encryption_key
+ self.encryption_keys = {} # hardware_xor: encryption_key
def add_claim_code(self, claim_code):
- hardware_address_xor, encryption_key = claiming.process_claim_code(claim_code)
+ hardware_xor, encryption_key = claiming.process_claim_code(claim_code)
#@TODO handle exception
- self.encryption_keys[hardware_address_xor] = encryption_key
+ self.encryption_keys[hardware_xor] = encryption_key
def key_for_address(self, device_address):
- hardware_address_xor = claiming.make_hardware_address_xor(device_address)
- return self.encryption_keys.get(hardware_address_xor, None)
+ hardware_xor = claiming.make_hardware_xor(device_address)
+ return self.encryption_keys.get(hardware_xor, None)
pending_claims = PendingClaims()
# @TODO command_sender shouldn't be passed in here, and of course it
# shouldn't be horribly synchronous like it is
-def process_event(ws, event, command_sender):
+def process_event(ws, event, sender):
print "Received event type %r" % event['type']
if event['type'] == 'DeviceEvent':
# unwrap here, even though it breaks abstraction... three event
timestamp = datetime.fromtimestamp(event['timestamp'])
print "DeviceEvent: %r at %s" % (payload['name'], timestamp.isoformat())
if payload['name'] == 'heartbeat':
- if command_sender.did_send_image is False:
+ if sender.did_send_image is False:
print "Sending set_delivery_and_print"
- dc = commands.set_delivery_and_print()
- command_sender.send_to_device(event['device_address'], dc)
- command_sender.did_send_image = True
+ device = Device.query.get(event['device_address'])
+ if device is not None:
+ q = sender.for_device(device)
+ if q is not None:
+ dc = commands.set_delivery_and_print(event['device_address'])
+ q.queue_device_command(dc)
+ sender.did_send_image = True
elif event['type'] == 'BridgeEvent':
# unwrap here. use device_connect and device_disconnect to
# change the command delivery map. there is also power_on,
# encryption_key_required [4 events are all I can find]
+ bridge = Bridge.get_or_create(event['bridge_address'])
event_name = event['json_payload']['name']
timestamp = datetime.fromtimestamp(event['timestamp'])
print "BridgeEvent: %r at %s" % (event_name, timestamp.isoformat())
if event_name == 'device_connect':
- command_sender.add_device(event['json_payload']['device_address'], ws)
+ device = Device.get_or_create(event['json_payload']['device_address'])
+ sender.device_connect(bridge, device)
elif event_name == 'device_disconnect':
- command_sender.remove_device(event['json_payload']['device_address'], ws)
+ device = Device.get_or_create(event['json_payload']['device_address'])
+ sender.device_disconnect(bridge, device)
elif event_name == 'power_on':
- command_sender.add_bridge_address(event['bridge_address'], ws)
+ sender.register(ws, bridge)
elif event_name == 'encryption_key_required':
print "Sending add_device_encryption_key"
bc = commands.add_device_encryption_key()
- command_sender.send_to_bridge(event['bridge_address'], bc)
+ sender.for_bridge(bridge).queue_bridge_command(bc)
else:
raise EventProcessingException("Unknown BridgeEvent command name: %r" % command_name)
pass
elif event['type'] == 'BridgeLog':
- # print it or something
- pass
+ pprint(event)
elif event['type'] == 'BridgeCommandResponse':
# if the return_code is 0 or not set, set state as delivered
# else mark it as failed
# (what happens if there is never any update? is there a timeout?)
# (30 minute time-out in the command gate)
- pass
+ r = event['return_code']
+ # update the database,
+ c = BridgeCommand.query.get(event['command_id'])
+ if c is None:
+ raise EventProcessingException("BridgeCommandResponse for unknown command_id %r" % event['command_id'])
+ c.return_code = r
+ if r == 0:
+ c.state = 'delivered'
+ else:
+ c.state = 'failed'
+ db.session.add(c)
+ db.session.commit()
+ # let the command_sender know to remove the command from
+ # the queue, or to resend it
+ bridge = Bridge.query.get(event['bridge_address'])
+ if bridge is not None:
+ sender.for_bridge(bridge).handle_bridge_response(c)
elif event['type'] == 'DeviceCommandResponse':
# if the return_code is 0, set state as delivered
# else mark it as failed
# (what happens if there is never any update? is there a timeout?)
- pass
+ r = event['return_code']
+ # update the database,
+ c = DeviceCommand.query.get(event['command_id'])
+ if c is None:
+ raise EventProcessingException("DeviceCommandResponse for unknown command_id %r" % event['command_id'])
+ c.return_code = r
+ if r == 0:
+ c.state = 'delivered'
+ else:
+ c.state = 'failed'
+ db.session.add(c)
+ db.session.commit()
+ # let the command_sender know to remove the command from
+ # the queue, or to resend it
+ device = Device.query.get(event['device_address'])
+ if device is not None:
+ sender.for_device(device).handle_device_response(c)
else:
raise EventProcessingException("Unknown event type: %r" % event['type'])
-from .. import db
+from app import db
+from app.core import claiming
import json
binary_payload = db.Column(db.Text, nullable=False)
state = db.Column(db.Enum('ready', 'failed', 'delivered', 'skipped'), nullable=False)
deliver_at = db.Column(db.DateTime, nullable=False)
+ return_code = db.Column(db.SmallInteger, nullable=True)
def to_json(self):
json_hash = {
class Bridge(db.Model):
__tablename__ = 'bridges'
bridge_address = db.Column(db.String, primary_key=True)
- last_power_on = db.Column(db.DateTime, nullable=False)
+ last_power_on = db.Column(db.DateTime, nullable=True) #@TODO should be false
+
+ @classmethod
+ def get_or_create(cls, bridge_address):
+ b = cls.query.get(bridge_address)
+ if b is None:
+ b = cls(bridge_address=bridge_address)
+ db.session.add(b)
+ db.session.commit()
+ return b
+
class Device(db.Model):
__tablename__ = 'devices'
device_address = db.Column(db.String, primary_key=True)
hardware_xor = db.Column(db.String, nullable=False)
+
+ @classmethod
+ def get_or_create(cls, device_address):
+ d = cls.query.get(device_address)
+ if d is None:
+ d = cls(device_address=device_address,
+ hardware_xor=claiming.make_hardware_xor(device_address))
+ db.session.add(d)
+ db.session.commit()
+ return d
+
class PendingClaim(db.Model):
__tablename__ = 'pending_claims'