class Client: def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT): LOGGER.debug('init client') self._host = host self._port = port self.lamp = Lamp() def add_command(self): LOGGER.debug('add commands') self.lamp.actions = On(ref(self.lamp)()) self.lamp.actions = Off(ref(self.lamp)()) self.lamp.actions = ChangeColor(ref(self.lamp)()) @gen.coroutine def client(self): LOGGER.debug('connecting to server %s:%s', self._host, self._port) try: stream = yield tcpclient.TCPClient().connect(self._host, self._port) except socket.error: LOGGER.error('failed to connect') self.close() return while not stream.closed(): try: res = yield stream.read_bytes(NUM_START_BYTES) except iostream.StreamClosedError: self.close() return tag, length = struct.unpack('>BB', res) if length > 0: try: value = yield stream.read_bytes(length) r, g, b = struct.unpack('BBB', value) except iostream.StreamClosedError: LOGGER.warning('connection closed in the middle of command') self.close() return value = (r, g, b) else: value = None LOGGER.debug('got message %s %s %s', tag, length, repr(value)) self.execute_command(tag, value) print(self.lamp.draw()) def start(self): self.client() ioloop.IOLoop.instance().start() def close(self): ioloop.IOLoop.instance().close() def execute_command(self, tag, value=None): self.lamp.execute_command(tag, value)
def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT): LOGGER.debug('init client') self._host = host self._port = port self.lamp = Lamp()