def discover_gg_host()

in aws-iot-greengrass-for-beginners/sensor/main.py [0:0]


def discover_gg_host():

    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(
        certificate_path, private_key_path)
    #tls_options.override_default_trust_store_from_path(None, root_ca_path)
    tls_context = io.ClientTlsContext(tls_options)

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

    logger.info('Performing greengrass discovery...')
    discovery_client = DiscoveryClient(
        client_bootstrap, socket_options, tls_context, region)
    resp_future = discovery_client.discover(device_name)
    discover_response = resp_future.result()

    logger.debug(discover_response)

    for gg_group in discover_response.gg_groups:
        for gg_core in gg_group.cores:
            for connectivity_info in gg_core.connectivity:
                try:
                    print(
                        'Trying core {} at host {} port {}'.format(
                            gg_core.thing_arn,
                            connectivity_info.host_address,
                            connectivity_info.port))
                    connection = mqtt_connection_builder.mtls_from_path(
                        endpoint=connectivity_info.host_address,
                        port=connectivity_info.port,
                        cert_filepath=certificate_path,
                        pri_key_filepath=private_key_path,
                        client_bootstrap=client_bootstrap,
                        ca_bytes=gg_group.certificate_authorities[0].encode(
                            'utf-8'),
                        on_connection_interrupted=on_connection_interupted,
                        on_connection_resumed=on_connection_resumed,
                        client_id=device_name,
                        clean_session=False,
                        keep_alive_secs=6)

                    connect_future = connection.connect()
                    connect_future.result()
                    print('Connected!')

                    return connection

                except Exception as e:
                    print('Connection failed with exception {}'.format(e))
                    continue

    sys.exit('All connection attempts failed')