Example #1
0
    def __init__(
        self,
        client,
        host_name,
        port,
        client_id,
        clean_session=True,
        on_connection_interrupted=None,
        on_connection_resumed=None,
        reconnect_min_timeout_secs=5,
        reconnect_max_timeout_secs=60,
        keep_alive_secs=1200,
        ping_timeout_ms=3000,
        will=None,
        username=None,
        password=None,
        socket_options=None,
        use_websockets=False,
        websocket_proxy_options=None,
        websocket_handshake_transform=None,
    ):

        assert isinstance(client, Client)
        assert callable(
            on_connection_interrupted) or on_connection_interrupted is None
        assert callable(on_connection_resumed) or on_connection_resumed is None
        assert isinstance(will, Will) or will is None
        assert isinstance(socket_options,
                          SocketOptions) or socket_options is None
        assert isinstance(websocket_proxy_options,
                          HttpProxyOptions) or websocket_proxy_options is None
        assert callable(websocket_handshake_transform
                        ) or websocket_handshake_transform is None

        if reconnect_min_timeout_secs > reconnect_max_timeout_secs:
            raise ValueError(
                "'reconnect_min_timeout_secs' cannot exceed 'reconnect_max_timeout_secs'"
            )

        if keep_alive_secs * 1000 <= ping_timeout_ms:
            raise ValueError(
                "'keep_alive_secs' duration must be longer than 'ping_timeout_ms'"
            )

        super().__init__()

        # init-only
        self.client = client
        self._on_connection_interrupted_cb = on_connection_interrupted
        self._on_connection_resumed_cb = on_connection_resumed
        self._use_websockets = use_websockets
        self._ws_handshake_transform_cb = websocket_handshake_transform

        # may be changed at runtime, take effect the the next time connect/reconnect occurs
        self.client_id = client_id
        self.host_name = host_name
        self.port = port
        self.clean_session = clean_session
        self.reconnect_min_timeout_secs = reconnect_min_timeout_secs
        self.reconnect_max_timeout_secs = reconnect_max_timeout_secs
        self.keep_alive_secs = keep_alive_secs
        self.ping_timeout_ms = ping_timeout_ms
        self.will = will
        self.username = username
        self.password = password
        self.socket_options = socket_options if socket_options else SocketOptions(
        )
        self.websocket_proxy_options = websocket_proxy_options

        self._binding = _awscrt.mqtt_client_connection_new(
            self,
            client,
            use_websockets,
        )
Example #2
0
    def __init__(
        self,
        client,
        host_name,
        port,
        client_id,
        clean_session=True,
        on_connection_interrupted=None,
        on_connection_resumed=None,
        reconnect_min_timeout_secs=5,
        reconnect_max_timeout_secs=60,
        keep_alive_secs=3600,
        ping_timeout_ms=3000,
        will=None,
        username=None,
        password=None,
        socket_options=None,
        use_websockets=False,
        websocket_proxy_options=None,
        websocket_handshake_transform=None,
    ):
        """
        Arguments:
            client (Client): MQTT Client

            host_name (str): Server name to connect to.

            port (int): Server port to connect to.

            client_id (str): ID to place in CONNECT packet. Must be unique across all devices/clients.
                    If an ID is already in use, the other client will be disconnected.

            clean_session (bool): Whether or not to start a clean session with each reconnect.
                    If True, the server will forget all subscriptions with each reconnect.
                    Set False to request that the server resume an existing session
                    or start a new session that may be resumed after a connection loss.
                    The `session_present` bool in the connection callback informs
                    whether an existing session was successfully resumed.
                    If an existing session is resumed, the server remembers previous subscriptions
                    and sends mesages (with QoS1 or higher) that were published while the client was offline.

            on_connection_interrupted (function): Optional callback invoked whenever the MQTT connection is lost.
                    The MQTT client will automatically attempt to reconnect.
                    The function should take the following arguments return nothing.
                        connection (Connection): This MQTT Connection.
                        error (awscrt.exceptions.AwsCrtError): Exception which caused connection loss.
                        **kwargs (dict): Forward-compatibility kwargs.

            on_connection_resumed (function): Optional callback invoked whenever the MQTT connection
                    is automatically resumed. Function should take the following arguments and return nothing:
                        connection (Connection): This MQTT Connection
                        return_code (ConnectReturnCode): Connect return code received from the server.
                        session_present (bool): True if resuming existing session. False if new session.
                                Note that the server has forgotten all previous subscriptions if this is False.
                                Subscriptions can be re-established via resubscribe_existing_topics().
                        **kwargs (dict): Forward-compatibility kwargs.

            reconnect_min_timeout_secs (int): Minimum time to wait between reconnect attempts.
                Wait starts at min and doubles with each attempt until max is reached.

            reconnect_max_timeout_secs (int): Maximum time to wait between reconnect attempts.
                Wait starts at min and doubles with each attempt until max is reached.

            keep_alive_secs (int): The keep alive value, in seconds, to send in CONNECT packet.
                        A PING will automatically be sent at this interval.
                        The server will assume the connection is lost if no PING is received after 1.5X this value.
                        This value must be higher than ping_timeout_ms.

            ping_timeout_ms (int): Milliseconds to wait for ping response before client assumes
                        the connection is invalid and attempts to reconnect.
                        This value must be less than keep_alive.
                        Alternatively, TCP keep-alive may accomplish this in a more efficient (low-power) scenario,
                        but keep-alive options may not work the same way on every platform and OS version.

            will (awscrt.mqtt.Will): Will to send with CONNECT packet. The will is
                        published by the server when its connection to the client
                        is unexpectedly lost.

            username (str): Username to connect with.

            password (str): Password to connect with.

            socket_options: awscrt.io.SocketOptions

            use_websocket: If true, connect to MQTT over websockets.

            websocket_proxy_options: optional awscrt.http.HttpProxyOptions for
                    websocket connections.

            websocket_handshake_transform: optional function to transform websocket handshake request.
                    If provided, function is called each time a websocket connection is attempted.
                    The function may modify the request before it is sent to the server.
                    See WebsocketHandshakeTransformArgs for more info.
                    Function should take the following arguments and return nothing:
                        transform_args (WebsocketHandshakeTransformArgs): Contains request to be transformed.
                                Function must call transform_args.done() when complete.
                        **kwargs (dict): Forward-compatibility kwargs.
        """

        assert isinstance(client, Client)
        assert callable(
            on_connection_interrupted) or on_connection_interrupted is None
        assert callable(on_connection_resumed) or on_connection_resumed is None
        assert isinstance(will, Will) or will is None
        assert isinstance(socket_options,
                          SocketOptions) or socket_options is None
        assert isinstance(websocket_proxy_options,
                          HttpProxyOptions) or websocket_proxy_options is None
        assert callable(websocket_handshake_transform
                        ) or websocket_handshake_transform is None

        super(Connection, self).__init__()

        # init-only
        self.client = client
        self._on_connection_interrupted_cb = on_connection_interrupted
        self._on_connection_resumed_cb = on_connection_resumed
        self._use_websockets = use_websockets
        self._ws_handshake_transform_cb = websocket_handshake_transform

        # may be changed at runtime, take effect the the next time connect/reconnect occurs
        self.client_id = client_id
        self.host_name = host_name
        self.port = port
        self.clean_session = clean_session
        self.keep_alive_secs = keep_alive_secs
        self.ping_timeout_ms = ping_timeout_ms
        self.will = will
        self.username = username
        self.password = password
        self.socket_options = socket_options if socket_options else SocketOptions(
        )
        self.websocket_proxy_options = websocket_proxy_options

        # TODO: reconnect_min_timeout_secs & reconnect_max_timeout_secs currently unused

        self._binding = _awscrt.mqtt_client_connection_new(
            self,
            client,
            use_websockets,
        )