Ejemplo n.º 1
0
    def __init__(
        self,
        session: Session,
        device_id: str,
        dev_data_callback: Optional[Callable] = None,
        node_update_callback: Optional[Callable] = None,
        verbose: bool = False,
        add_sigint_handler: bool = False,
        ping_interval: int = 20,
        reconnect_attempts: int = _DEFAULT_RECONNECT_ATTEMPTS,
        backoff_factor: float = _DEFAULT_BACKOFF_FACTOR,
    ) -> None:
        self._session = session
        self._device_id = device_id
        self._ping_interval = ping_interval
        self._reconnect_attempts = reconnect_attempts
        self._backoff_factor = backoff_factor

        if verbose:
            self._sio = socketio.AsyncClient(
                logger=True,
                engineio_logger=True,
                reconnection_attempts=reconnect_attempts,
            )
        else:
            logging.getLogger("socketio").setLevel(logging.ERROR)
            logging.getLogger("engineio").setLevel(logging.ERROR)
            self._sio = socketio.AsyncClient()

        self._api_v2_ns = SmartboxAPIV2Namespace(
            session, _API_V2_NAMESPACE, dev_data_callback, node_update_callback
        )
        self._sio.register_namespace(self._api_v2_ns)

        @self._sio.event
        async def connect():
            _LOGGER.debug("Received connect socket event")
            if add_sigint_handler:
                # engineio sets a signal handler on connect, which means we have to set our
                # own in the connect callback if we want to override it
                _LOGGER.debug("Adding signal handler")
                event_loop = asyncio.get_event_loop()

                def sigint_handler():
                    _LOGGER.debug("Caught SIGINT, cancelling loop")
                    asyncio.ensure_future(self.cancel())

                event_loop.add_signal_handler(signal.SIGINT, sigint_handler)
Ejemplo n.º 2
0
    def __init__(self, encoder_server_path, store, ra_axis_id, dec_axis_id):
        self.server_path = encoder_server_path
        self.store = store
        self.ra_axis_id = ra_axis_id
        self.dec_axis_id = dec_axis_id

        sio = self.sio = socketio.AsyncClient()

        @sio.on('disconnect')
        async def onerror(payload=None):
            await asyncio.sleep(1)
            await self.start()

        @sio.on('position')
        async def update_position(payload):
            parameter_map = {
                self.ra_axis_id: [
                    ('position_astronomical', 'mount.right_ascencion'),
                    ('target_astronomical', 'mount.target.right_ascencion'),
                ],
                self.dec_axis_id: [
                    ('position_angle', 'mount.declination'),
                    ('target_angle', 'mount.target.declination'),
                ]
            }

            for src, dest in parameter_map[payload['id']]:
                self.store[dest].update(payload[src])

            if payload['id'] == self.ra_axis_id:
                self.store['mount.alignment_status'].update({
                    'is_tracking': payload['tracking']
                })
Ejemplo n.º 3
0
    async def async_step_user(self, user_input=None):
        """Handle the initial step."""

        if self._async_current_entries():
            _LOGGER.warn("Only a single instance is allowed.")
            return self.async_abort(reason="single_instance_allowed")

        data_schema = vol.Schema(
            {vol.Required("url", default="http://localhost:3001/"): str})

        if user_input is None:
            return self.async_show_form(step_id="user",
                                        data_schema=data_schema)

        url = user_input.get("url")

        sio = socketio.AsyncClient()

        try:
            # Connect to make sure it's a valid URL
            # If it isn't, connect will throw a ConnectionError
            await sio.connect(url)
            # Disconnect now that we know it is
            await sio.disconnect()
            return self.async_create_entry(title=f"{url}", data={"url": url})
        except socketio.exceptions.ConnectionError as err:
            _LOGGER.exception(err)
            errors = {"url": "did_not_connect"}
            return self.async_show_form(step_id="user",
                                        data_schema=data_schema,
                                        errors=errors)
        except Exception as e:
            _LOGGER.exception(e)
Ejemplo n.º 4
0
async def main():
    sio = socketio.AsyncClient()
    print('connecting')
    await sio.connect('ws://localhost:3333')
    service = get_service_proxy(sio, 'ServerSideService')
    rpc_serve(sio, ClientSideService())
    await asyncio.gather(sio.wait(), test_func(sio, service))
Ejemplo n.º 5
0
async def run():
    print("Connecting to droneserver")
    sio = socketio.AsyncClient()
    await sio.connect(droneserver)
    print("droneserver connected")

    # Send home location
    location = { "lat": 22.309058, "lon": 114.304060, "alt": 19.5 }
    await sio.emit('home_location_updated', location)

    drone_location = { "lat": 22.309058, "lon": 114.304060, "alt": 50, "heading": 270 }
    lat_move = 0.0
    lon_move = 0.0
    
    while True:
        # Update drone location
        # location = { "lat": 22.307990, "lon": 114.301596 }
        await sio.emit('drone_location_updated', drone_location)
        
        lat_move = lat_move + random.uniform(-0.00005,0.00005)
        lon_move = lon_move + random.uniform(-0.00005,0.00005)
        drone_location['lat'] = drone_location['lat'] + lat_move
        drone_location['lon'] = drone_location['lon'] + lon_move
        drone_location['heading'] = drone_location['heading'] + 25

        await asyncio.sleep(2)
Ejemplo n.º 6
0
 def get_unit_under_test(self) -> SocketClient:
     sio_mock = socketio.AsyncClient()
     sio_mock.on = MagicMock(return_value=None)
     self._body = MagicMock(return_value=None)
     self._origin = MagicMock(return_value=None)
     self._adapter_name = MagicMock(return_value=None)
     return SocketClient(sio_mock)
Ejemplo n.º 7
0
    async def do_ping_pong(self):
        private = socketio.AsyncClient()
        self.private = private

        @private.on('connect',
                    namespace='/{}'.format(self._private_channel_id))
        async def connect():
            print('Connected to private namespace /{}'.format(
                self._private_channel_id))

        @private.on('presence',
                    namespace='/{}'.format(self._private_channel_id))
        async def presence(data):
            assert self._private_channel_id
            if not self.ping_timeout:
                assert data == 'PING'
            else:
                assert data in ('PING', 'PING TIMEOUT')
            await private.emit('presence',
                               'PONG',
                               namespace='/{}'.format(
                                   self._private_channel_id))
            self._pings.append([int(time.time()), data])

        @private.on('msg', namespace='/{}'.format(self._private_channel_id))
        async def presence(data):
            assert self._private_channel_id
            self._on_cmd_answer and self._on_cmd_answer(data)

        await private.connect(
            'http://127.0.0.1:{}'.format(self.socketioport),
            namespaces=['/{}'.format(self._private_channel_id)])
Ejemplo n.º 8
0
    def __init__(self, configuration):
        # keep a copy of the configuration for later use.
        self.__configuration = configuration

        # create a socket connection to the robot.
        self.__sio = socketio.AsyncClient()
        loop.run_until_complete(self.__sio.connect(server_url))

        if token_authentication_required:
            loop.run_until_complete(
                authenticate_with_token(self.__sio, configuration["token"]))

        if wait_for_game_start:
            loop.run_until_complete(wait_for_game_start_message(self.__sio))

        # for each robot-part specified in the configuration, generate an api to it accessible via it's chosen name.
        for part_conf in configuration["parts"]:
            setattr(
                self, part_conf['name'],
                Part(self.__emit, part_conf['name'], part_conf["type"],
                     configuration["name"]))

        # notify about a response from the robot to all the api's (only the api waiting for a
        # response will propagate it eventually)
        @self.__sio.on(socket_on_route)
        def on_message(data):
            for part_conf in configuration["parts"]:
                getattr(self, part_conf['name']).on_message(data)
Ejemplo n.º 9
0
    async def connect(self):
        self.sio = socketio.AsyncClient(
            logger=self.socketio_logger, reconnection=False
        )

        @self.sio.event(namespace=SOCKETIO_NAMESPACE)
        def connect_error(msg):
            logging.error(f"GE socketio connection error: {msg}")
            self.connected = False
            if self.connected_future is not None:
                self.connected_future.set_exception(Exception(msg))
                self.connected_future = None
            if "Invalid robot token" in msg:
                sys.exit(2)

        self.sio.register_namespace(self)

        logging.info(f"connecting to {self.url}")

        await self.sio.connect(self.url, transports="websocket")

        if self.connected is not True:
            self.connected_future = asyncio.get_running_loop().create_future()
            await self.connected_future

        logging.info("connected")
Ejemplo n.º 10
0
    def __init__(
        self, endpoint,
        transports = ['websocket'], reconnection = True,
        reconnection_attempts = 0, reconnection_delay=0.1,
        reconnection_delay_max=0.5, logger=False, headers=None, namespace = '/', **kwargs):

        """
        logger_level : str
            CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET
        """
        self.logger = logging.getLogger(self.__class__.__name__)

        self.is_connect = False
        self.endpoint = endpoint
        self.transports = transports
        self.headers = headers
        self.namespace  = namespace
        self.sio_ = socketio.AsyncClient(
            reconnection = reconnection,
            reconnection_attempts = reconnection_attempts,
            reconnection_delay = reconnection_delay,
            reconnection_delay_max = reconnection_delay_max,
            logger = logger
        )
        self.Namespace   = self.NamespaceClass(self.namespace)
        self.overload_event()
        self.sio_.register_namespace(self.Namespace)

        super().__init__(**kwargs)
Ejemplo n.º 11
0
    def __init__(self,
                 client: discord.Client,
                 token: str,
                 autoupdate: bool = False,
                 logger: bool = False,
                 **kwargs):
        """
        :param client: Discord Client
        :param token: primebots.it API Token
        :param autoupdate: Auto-Aggiornamento dei server riportati sul sito
        :param logger: Debug Logs
        """
        self.socket = socketio.AsyncClient(logger=logger)

        self.token = token
        self.client = client
        self.client_id = None
        self.auto_update = autoupdate
        self.loop = kwargs.get("loop", client.loop)

        self.loop.create_task(self._socket_connect())

        self.loop.create_task(self._socket_logger())

        if self.auto_update:
            self._auto_update_task = self.loop.create_task(self._auto_update())
Ejemplo n.º 12
0
    def __init__(self, server_address, market_configs):
        # Initialize client-server data
        self.server_address = server_address
        self.sio_client = socketio.AsyncClient(reconnection=True,
                                               reconnection_attempts=100,
                                               reconnection_delay=1,
                                               reconnection_delay_max=5,
                                               randomization_factor=0.5,
                                               json=jkson)

        market_configs = market_configs
        market_configs['market_id'] = market_configs.pop('id', '')
        grid_params = market_configs.pop('grid', {})

        # Initialize market information
        Market = importlib.import_module('_clients.markets.' + market_configs['type']).Market
        NSMarket = importlib.import_module('_clients.markets.' + market_configs['type']).NSMarket

        self.market = Market(sio_client=self.sio_client,
                             **market_configs,
                             grid_params=grid_params)

        # register client in server rooms
        self.sio_client.register_namespace(NSDefault(self.market))
        self.sio_client.register_namespace(NSMarket(self.market))
        self.sio_client.register_namespace(NSSimulation(self.market))

        self.data_recorded = False
        self.recording_complete = False
Ejemplo n.º 13
0
async def main(NamespaceClass, namespace_address):
    # Define async socket client
    sio = socketio.AsyncClient()

    # Register the namespace to the client
    namespace = NamespaceClass(namespace_address)
    sio.register_namespace(namespace)

    async def connect_to_server():
        # Connect to the server
        await sio.connect(namespace.server_address)

        # add the SID to the namespace
        namespace.sid = sio.sid

        # Wait a short while just in case
        await asyncio.sleep(1.0)

    # Add the connection method to the namespace (for reconnects)
    namespace.connect_to_server = connect_to_server

    # Wait for the connection to be established
    await connect_to_server()

    # Run the background job
    asyncio.create_task(namespace.background_job())

    # Run the event loop
    await sio.wait()
    async def do_ping_pong(self):
        private = socketio.AsyncClient()
        self.private = private

        @private.on('connect',
                    namespace='/{}'.format(self._private_channel_id))
        async def connect():
            print('Connected to private namespace /{}'.format(
                self._private_channel_id))
            self.loop.create_task(self.monitor_execution())

        @private.on('presence',
                    namespace='/{}'.format(self._private_channel_id))
        async def presence(data):
            if not self.ping_timeout:
                assert data == 'PING'
            else:
                assert data in ('PING', 'PING TIMEOUT')
            self._pings.append([int(time.time()), data])

        await private.connect(
            'http://127.0.0.1:{}'.format(self.socketioport),
            namespaces=['/{}'.format(self._private_channel_id)],
        )
        self._engaged_private_channel_id = self._private_channel_id
Ejemplo n.º 15
0
 def __init__(self, hass, api_key):
     self._hass = hass
     self._api_key = api_key
     self._http_session = aiohttp.ClientSession()
     self._lights_updated = None
     self._scenes_updated = None
     self._sio = socketio.AsyncClient(logger=_IO_LOGGER, engineio_logger=_IO_LOGGER)
Ejemplo n.º 16
0
 def __init__(self, auth_query, listener):
     self.auth_query = auth_query
     self.listener = listener
     self.sio = socketio.AsyncClient()
     self.bind_events()
     self.connect_future = None
     self.subscribe_future = None
Ejemplo n.º 17
0
    def __init__(self, server_address, participant_type, participant_id,
                 market_id, db_path, trader_params, storage_params, **kwargs):
        # Initialize client related data
        self.server_address = server_address
        self.sio_client = socketio.AsyncClient(reconnection=True,
                                               reconnection_attempts=100,
                                               reconnection_delay=1,
                                               reconnection_delay_max=5,
                                               randomization_factor=0.5,
                                               json=jkson)

        Participant = importlib.import_module('_clients.participants.' +
                                              participant_type).Participant
        NSMarket = importlib.import_module('_clients.participants.' +
                                           participant_type).NSMarket

        self.participant = Participant(sio_client=self.sio_client,
                                       participant_id=participant_id,
                                       market_id=market_id,
                                       db_path=db_path,
                                       trader_params=trader_params,
                                       storage_params=storage_params,
                                       market_ns='_clients.participants.' +
                                       participant_type,
                                       **kwargs)

        self.sio_client.register_namespace(
            NSDefault(participant=self.participant))
        self.sio_client.register_namespace(
            NSMarket(participant=self.participant))
        self.sio_client.register_namespace(
            NSSimulation(participant=self.participant))
Ejemplo n.º 18
0
 def setUp(self):
     assert settings.RUNNING_TESTS
     self.connected = False
     self.socketioport = random.randint(10000, 50000)
     self.randstuff = binascii.hexlify(os.urandom(8)).decode()
     self.typeschecked = False
     self.sio_client = socketio.AsyncClient()
     self._on_create = []
     self._on_auth = []
     self.end = False
     self._private_channel_id = None
     self.max_execution_time = 120
     self._pings = []
     self.loop = asyncio.get_event_loop()
     self.channels_factory = mock.create_autospec(
         WebsocketChannelsRepository)
     self.data_repository = mock.create_autospec(RedisDataRepository)
     self.cmd_queue = asyncio.Queue()
     self.channels_monitor = WebsocketChannelsService(
         channels_repository=self.channels_factory,
         loop=self.loop,
         data_repository=self.data_repository,
         ping_interval=30,
         ping_timeout=50,
         redis_queue=self.cmd_queue)
     self._on_cmd_answer = None
     self.loop.set_debug(True)
     self.ping_timeout = False
Ejemplo n.º 19
0
async def test_send_updates_for_one_user(game_api, client, socketio_server,
                                         loop):
    socketio_client = socketio.AsyncClient(reconnection=False)
    mock_log_listener = mock.MagicMock()

    game_api.worker_manager.add_new_worker(1)

    socketio_client.on("log", mock_log_listener)

    worker = game_api.worker_manager.player_id_to_worker[1]
    worker.log = "Logs one"

    await socketio_client.connect(
        f"http://{client.server.host}:{client.server.port}?avatar_id=1&EIO=3&transport=polling&t=MJhoMgb"
    )

    await game_api.send_updates_to_all()

    await socketio_server.sleep(TIME_TO_PROCESS_SOME_EVENT_LOOP)
    await socketio_client.disconnect()

    mock_log_listener.assert_has_calls(
        [mock.call({
            "message": "Logs one",
            "turn_count": 0
        })])
Ejemplo n.º 20
0
    async def start_agent(self) -> None:
        """ Startup function for agent. """

        await asyncio.sleep(5)
        logging.info("[RL Agent] Contacting the central server.")

        self.sio = socketio.AsyncClient(reconnection=True)
        self.sio.register_namespace(
            RLAgentEvents(namespace='/', plato_rl_agent=self))

        uri = ""
        if hasattr(Config().server, 'use_https'):
            uri = 'https://{}'.format(Config().server.address)
        else:
            uri = 'http://{}'.format(Config().server.address)

        uri = '{}:{}'.format(uri, Config().server.port)

        logging.info("[RL Agent] Connecting to the server at %s.", uri)
        await self.sio.connect(uri)
        await self.sio.emit('agent_alive', {
            'agent': self.agent,
            'current_rl_episode': self.current_episode
        })

        logging.info("[RL Agent] Waiting to be updated with new state.")
        await self.sio.wait()
Ejemplo n.º 21
0
async def upload_loop(url="http://127.0.0.1:6789"):
    # =====================Uploader Setsup========================
    def result_to_json(res):
        landmarks, iris_pois, blinks = res
        return {'shape': landmarks.tolist(),
                'iris': iris_pois.tolist(),
                'blinks': blinks.tolist()}

    sio = socketio.AsyncClient()
    @sio.on('response', namespace='/sakuya')
    async def on_response(data):
        upload_frame = upstream_queue.get()
        # await sio.emit('frame_data', encode_image(upload_frame), namespace='/sakuya')
        await sio.emit('frame_data', 0, namespace='/sakuya')
        try:
            result_string = result_to_json(result_queue.get_nowait())
            await sio.emit('result_data', result_string, namespace='/sakuya')
        except Exception as e:
            print(e)
            pass

    @sio.on('connect', namespace='/sakuya')
    async def on_connect():
        await sio.emit('frame_data', 0, namespace='/sakuya')

    await sio.connect(url)
    await sio.wait()
Ejemplo n.º 22
0
    async def sio_connect(self, director_bearer_token):
        """Start WebSockets connection and listen, using the provided director_bearer_token to authenticate with the Control4 Director.
        If a connection already exists, it will be disconnected and a new connection will be created.

        This function should be called using a new token every 86400 seconds (the expiry time of the director tokens), otherwise the Control4 Director will stop sending WebSocket messages.

        Parameters:
            `director_bearer_token` - The bearer token used to authenticate with the Director. See `pyControl4.account.C4Account.getDirectorBearerToken` for how to get this.
        """
        # Disconnect previous sio object
        await self.sio_disconnect()

        self._sio = socketio.AsyncClient(ssl_verify=False)
        self._sio.register_namespace(
            _C4DirectorNamespace(
                token=director_bearer_token,
                url=self.base_url,
                callback=self._callback,
                session=self.session,
                connect_callback=self.connect_callback,
                disconnect_callback=self.disconnect_callback,
            ))
        await self._sio.connect(
            self.wss_url,
            transports=["websocket"],
            headers={"JWT": director_bearer_token},
        )
    def __init__(self, configuration):
        # save a copy of the configuration for later use.
        self.__configuration = configuration

        # asyncio black magic variables to be able to work asynchronously while
        # the end-user gets a synchronous experience.
        self.__event = asyncio.Event()
        self.__event.set()
        self.__socket_response = None

        # create a socket connection to the robot.
        self.__sio = socketio.AsyncClient()
        loop.run_until_complete(self.__sio.connect(configuration["server_url"]))

        # if a token authentication is required, authenticate.
        if configuration["use_authentication_token"]:
            loop.run_until_complete(self.__authenticate_with_token())

        # a function that is triggered whenever there is a response from the robot.
        @self.__sio.on(self.__configuration["socket_on_route"])
        def on_message(data):
            # when receiving a message, get the response
            # data and set the event to release the waiting on the request sending function.
            self.__socket_response = data
            self.__event.set()
async def upload_loop(url="http://127.0.0.1:6789"):
    # =====================Uploader Setsup========================
    sio = socketio.AsyncClient()
    @sio.on('response', namespace='/remilia')
    async def on_response(data):
        current_address, upload_frame = upstream_frame_queue.get()
        image_string = 0
        # strat_time = time.time()
        if current_address == data:
            image_string = encode_image(upload_frame)
        # mid_time = time.time()
        await sio.emit('frame_data', image_string, namespace='/remilia')
        try:
            img, dt, prob, name = result_queue.get_nowait()
            result_string = {'image': encode_image(img),
                             'time': dt, 'name': name, 'prob': prob}
            await sio.emit('result_data', result_string, namespace='/remilia')
        except Exception as e:
            pass
        # print(mid_time-strat_time, time.time()-mid_time)
        # sys.stdout.flush()

    @sio.on('connect', namespace='/remilia')
    async def on_connect():
        await sio.emit('frame_data', 0, namespace='/remilia')

    await sio.connect(url)
    await sio.wait()
Ejemplo n.º 25
0
async def test_anonymous_websocket_connection(
    client_session_id,
    socketio_url: str,
    security_cookie,
    mocker,
):
    from yarl import URL

    sio = socketio.AsyncClient(
        ssl_verify=False)  # enginio 3.10.0 introduced ssl verification
    url = str(
        URL(socketio_url).with_query(
            {"client_session_id": client_session_id()}))
    headers = {}
    if security_cookie:
        # WARNING: engineio fails with empty cookies. Expects "key=value"
        headers.update({"Cookie": security_cookie})

    socket_connect_error = mocker.Mock()
    sio.on("connect_error", handler=socket_connect_error)
    with pytest.raises(socketio.exceptions.ConnectionError):
        await sio.connect(url, headers=headers)
    assert sio.sid is None
    socket_connect_error.assert_called_once()
    await sio.disconnect()
    assert not sio.sid
Ejemplo n.º 26
0
    async def _connect_socketio(self, url):
        self.conn = sio = socketio.AsyncClient(reconnection=False)
        #messages to .recv are forwarded via signal_recv_queue
        q = self._socket_recv_queue
        connected = asyncio.Event()

        async def message(data):
            await q.put(data)

        for event in self.event_names:
            sio.on(event)(message)

        @sio.event
        async def connect():
            connected.set()

        @sio.event
        async def connect_error(*args):
            self.log('socketio encountered connect error')
            await q.put(
                websockets.ConnectionClosed(-1, 'socketio connect error'))

        # This isn't executed when user itself evokes sio.disconnect (or here Connection.stop())
        @sio.event
        async def disconnect():
            self.log('socketio connection has crashed')
            await q.put(websockets.ConnectionClosed(-1, 'socketio ws crashed'))

        await sio.connect(url, transports='websocket')
        await connected.wait()
Ejemplo n.º 27
0
async def test_send_updates_for_one_user(
    game_api, client, socketio_server: AsyncServer, loop
):
    socketio_client = socketio.AsyncClient(reconnection=False)
    mock_listener = mock.MagicMock()

    game_api.game_state.avatar_manager.add_avatar(1)

    socketio_client.on("game-state", mock_listener)

    avatar = game_api.game_state.avatar_manager.get_avatar(1)
    avatar.logs = ["Avatar log"]

    await socketio_client.connect(
        f"http://{client.server.host}:{client.server.port}?avatar_id=1",
    )
    await socketio_server.sleep(TIME_TO_PROCESS_SOME_EVENT_LOOP)

    await game_api.send_updates_to_all()

    await socketio_server.sleep(TIME_TO_PROCESS_SOME_EVENT_LOOP)
    await socketio_client.disconnect()
    await socketio_client.sleep(TIME_TO_PROCESS_SOME_EVENT_LOOP)

    expected_game_state = game_api.game_state.serialize()
    expected_game_state["playerLog"] = "Avatar log"
    mock_listener.assert_has_calls([mock.call(expected_game_state)])
Ejemplo n.º 28
0
async def ensureConnected():
    global sio, connectFuture
    if not sio:
        sio = socketio.AsyncClient()
        connectFuture = asyncio.Future()
        await connect()
    await connectFuture
Ejemplo n.º 29
0
    async def createSIO(self):
        print("create a new async sio client")
        self.sio = socketio.AsyncClient()
        print("connect to a server")
        await self.sio.connect(self.ip_address)

        @self.sio.on("on-connect")
        def on_connect(data):
            self.initiator = data["initiator"]
            print("on-connect: is the",
                  "caller" if self.initiator else "callee")

        @self.sio.on("established")
        async def established():
            print('connection established')

        @self.sio.on("offer-or-answer")
        async def offerOrAnswer(sdp):
            print("offer-or-answer", sdp["type"])
            if sdp["type"] == 'offer':
                await self.pc.setRemoteDescription(
                    RTCSessionDescription(sdp['sdp'], sdp['type']))
                # print(self.pc.remoteDescription)
                answer = await self.pc.createAnswer()
                # print('answer:', answer)
                await self.pc.setLocalDescription(answer)
                await self.sendToPeer(
                    "offer-or-answer", {
                        'sdp': self.pc.localDescription.sdp,
                        'type': self.pc.localDescription.type
                    })

        @self.sio.on("candidate")
        async def addCandidate(candidate):
            self.candidates.append(candidate)
            # decode the candidate info
            split_candidate = candidate["candidate"].split(" ")
            sdpMLineIndex = candidate["sdpMLineIndex"]
            sdpMid = candidate["sdpMid"]
            foundation = split_candidate[0].split(":")[-1]
            component = int(split_candidate[1])
            protocol = split_candidate[2]
            priority = int(split_candidate[3])
            ip = split_candidate[4]
            port = int(split_candidate[5])
            candidate_type = split_candidate[7]
            tcp_type = split_candidate[9]
            new_candidate = RTCIceCandidate(component=component,
                                            foundation=foundation,
                                            ip=ip,
                                            port=port,
                                            priority=priority,
                                            protocol=protocol,
                                            type=candidate_type,
                                            sdpMid=sdpMid,
                                            sdpMLineIndex=sdpMLineIndex,
                                            tcpType=tcp_type)
            await self.pc.addIceCandidate(new_candidate)
            print("successfully add new candidate")
Ejemplo n.º 30
0
async def connect(url="http://localhost:5283"):
    global sio, connectFuture
    if not sio:
        sio = socketio.AsyncClient()
        connectFuture = asyncio.Future()
    await sio.connect(url)
    connectFuture.set_result(None)
    sio.on("sandboxEnded", handler=sandboxEnded)