Пример #1
0
 def test_get_lamp_state(self):
     handler = MessageHandler()
     handler.set_connection(True)
     lights.STATE = "NOT IDLE"
     self.assertEqual("SetLight", lights.get_lamp_state(True, handler))
     lights.STATE = "IDLE"
     self.assertEqual("IDLE", lights.get_lamp_state(True, handler))
     self.assertEqual("NOTIDLE", lights.get_lamp_state(False, handler))
     handler.set_connection(False)
     self.assertEqual("IDLENotConnected",
                      lights.get_lamp_state(True, handler))
Пример #2
0
async def ensure_connection(handler: MessageHandler) -> None:
    """Task that attempts server connection, if connection closes, it waits for retry period.

    Args:
        handler (MessageHandler): Message handler
    """
    message = json.dumps({'type': "Auth", 'payload': {
        'username': USER_NAME, 'secret': SHARED_SECRET}})
    t = 1
    while True:
        logging.info("Establishing connection")
        await init_connection(message, handler)
        logging.info("Connection closed")
        handler.set_connection(False)
        await asyncio.sleep(t)
        t = get_connection_retry_time(t)
        logging.info(f'Retrying connection in {t} seconds')
Пример #3
0
async def init_connection(message: str, handler: MessageHandler) -> None:
    """Initiate websocket connection and bind message handler

    Args:
        message (str): Auth Message
        handler (MessageHandler): Message handler
    """
    uri = WS_URI
    try:
        logging.info("Connecting to server")
        async with websockets.connect(uri) as websocket:
            handler.set_connection(True)
            handler.set_websocket(websocket)
            await websocket.send(message)
            logging.info("Connection is open")
            await handle_messages(websocket, message, handler)
            logging.info("Connection is closed")
            await websocket.close()
    except TimeoutError as err:
        logging.error(f'Could not connect to web server {err}')