How to use the awscrt.io.SocketOptions function in awscrt

To help you get started, we’ve selected a few awscrt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aws / aws-iot-device-sdk-python-v2 / samples / basic_discovery.py View on Github external
help='Logging level')

args = parser.parse_args()

io.init_logging(getattr(LogLevel, args.verbosity), 'stderr')

event_loop_group = io.EventLoopGroup(1)
host_resolver = io.DefaultHostResolver(event_loop_group)
client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)

tls_options = io.TlsContextOptions.create_client_with_mtls_from_path(args.certificate_path, args.private_key_path)
if args.root_ca_path:
    tls_options.override_default_trust_store_from_path(None, args.root_ca_path)
tls_context = io.ClientTlsContext(tls_options)

socket_options = io.SocketOptions()
socket_options.connect_timeout_ms = 3000

print('Performing greengrass discovery...')
discovery_client = DiscoveryClient(client_bootstrap, socket_options, tls_context, args.region)
resp_future = discovery_client.discover(args.thing_name)
discover_response = resp_future.result()

print(discover_response)
if args.print_discover_resp_only:
    exit(0)


def on_connection_interupted(connection, error, **kwargs):
    print('connection interrupted with error {}'.format(error))
github awslabs / aws-crt-python / awscrt / awsiot_mqtt_connection_builder.py View on Github external
elif ca_filepath or ca_dirpath:
        tls_ctx_options.override_default_trust_store_from_path(ca_dirpath, ca_filepath)

    if use_websockets:
        port = 443
        if awscrt.io.is_alpn_available():
            tls_ctx_options.alpn_list = ['http/1.1']
    else:
        port = 8883
        if awscrt.io.is_alpn_available():
            port = 443
            tls_ctx_options.alpn_list = ['x-amzn-mqtt-ca']

    port = kwargs.get('port', port)

    socket_options = awscrt.io.SocketOptions()
    socket_options.connect_timeout_ms = kwargs.get('tcp_connect_timeout_ms', 5000)
    socket_options.keep_alive = kwargs.get('tcp_keepalive', False)
    socket_options.keep_alive_timeout_secs = kwargs.get('tcp_keepalive_timeout_secs', 0)
    socket_options.keep_alive_interval_secs = kwargs.get('tcp_keep_alive_interval_secs', 0)
    socket_options.keep_alive_max_probes = kwargs.get('tcp_keep_alive_max_probes', 0)

    username = kwargs.get('username', '')
    if kwargs.get('enable_metrics_collection', True):
        username += _get_metrics_str()

    client_bootstrap = kwargs.get('client_bootstrap')
    tls_ctx = awscrt.io.ClientTlsContext(tls_ctx_options)
    mqtt_client = awscrt.mqtt.Client(client_bootstrap, tls_ctx)

    return awscrt.mqtt.Connection(
        client=mqtt_client,
github awslabs / aws-crt-python / awscrt / http.py View on Github external
bootstrap,
            socket_options=None,
            tls_connection_options=None,
            proxy_options=None):
        """
        Initiates a new connection to host_name and port using socket_options and tls_connection_options if supplied.
        if tls_connection_options is None, then the connection will be attempted over plain-text.

        Returns a future where the result is a new instance to HttpClientConnection, once the connection has completed
        and is ready for use.
        """
        assert isinstance(bootstrap, ClientBootstrap) or bootstrap is None
        assert isinstance_str(host_name)
        assert isinstance(port, int)
        assert isinstance(tls_connection_options, TlsConnectionOptions) or tls_connection_options is None
        assert isinstance(socket_options, SocketOptions) or socket_options is None
        assert isinstance(proxy_options, HttpProxyOptions) or proxy_options is None

        future = Future()
        try:
            if not socket_options:
                socket_options = SocketOptions()

            if not bootstrap:
                event_loop_group = EventLoopGroup(1)
                host_resolver = DefaultHostResolver(event_loop_group)
                bootstrap = ClientBootstrap(event_loop_group, host_resolver)

            connection = cls()
            connection._host_name = host_name
            connection._port = port
github awslabs / aws-crt-python / elasticurl.py View on Github external
output.write(chunk)


data_len = 0
data_stream = None

if args.data:
    data_bytes = args.data.encode(encoding='utf-8')
    data_len = len(data_bytes)
    data_stream = BytesIO(data_bytes)
elif args.data_file:
    data_len = os.stat(args.data_file).st_size
    data_stream = open(args.data_file, 'rb')


socket_options = io.SocketOptions()
socket_options.connect_timeout_ms = args.connect_timeout

hostname = url.hostname
connect_future = http.HttpClientConnection.new(
    host_name=hostname,
    port=port,
    socket_options=socket_options,
    tls_connection_options=tls_connection_options,
    bootstrap=client_bootstrap)

connection = connect_future.result(10)
connection.shutdown_future.add_done_callback(on_connection_shutdown)

request = http.HttpRequest(args.method, body_stream=data_stream)

if args.get:
github awslabs / aws-crt-python / awscrt / mqtt.py View on Github external
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
github awslabs / aws-crt-python / awscrt / http.py View on Github external
if tls_connection_options is None, then the connection will be attempted over plain-text.

        Returns a future where the result is a new instance to HttpClientConnection, once the connection has completed
        and is ready for use.
        """
        assert isinstance(bootstrap, ClientBootstrap) or bootstrap is None
        assert isinstance_str(host_name)
        assert isinstance(port, int)
        assert isinstance(tls_connection_options, TlsConnectionOptions) or tls_connection_options is None
        assert isinstance(socket_options, SocketOptions) or socket_options is None
        assert isinstance(proxy_options, HttpProxyOptions) or proxy_options is None

        future = Future()
        try:
            if not socket_options:
                socket_options = SocketOptions()

            if not bootstrap:
                event_loop_group = EventLoopGroup(1)
                host_resolver = DefaultHostResolver(event_loop_group)
                bootstrap = ClientBootstrap(event_loop_group, host_resolver)

            connection = cls()
            connection._host_name = host_name
            connection._port = port

            def on_connection_setup(binding, error_code):
                if error_code == 0:
                    connection._binding = binding
                    future.set_result(connection)
                else:
                    future.set_exception(awscrt.exceptions.from_code(error_code))
github aws / aws-iot-device-sdk-python-v2 / awsiot / greengrass_discovery.py View on Github external
def __init__(self, bootstrap, socket_options, tls_context, region):
        assert isinstance(bootstrap, ClientBootstrap)
        assert isinstance(socket_options, SocketOptions)
        assert isinstance(tls_context, ClientTlsContext)
        assert isinstance(region, str)

        self._bootstrap = bootstrap
        self._socket_options = socket_options
        self._region = region
        self._gg_server_name = 'greengrass-ats.iot.{}.amazonaws.com'.format(region)
        self._tls_connection_options = tls_context.new_connection_options()
        self._tls_connection_options.set_server_name(self._gg_server_name)
        self.port = 8443

        if is_alpn_available():
            self._tls_connection_options.set_alpn_list(['x-amzn-http-ca'])
            self.port = 443
github awslabs / aws-crt-python / awscrt / mqtt.py View on Github external
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,
        )