def mqttStart(self): event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=self.ENDPOINT, cert_filepath=self.PATH_TO_CERT, pri_key_filepath=self.PATH_TO_KEY, client_bootstrap=client_bootstrap, ca_filepath=self.PATH_TO_ROOT, client_id=self.CLIENT_ID, clean_session=False, keep_alive_secs=6) print("Connecting to {} with client ID '{}'...".format( self.ENDPOINT, self.CLIENT_ID)) connect_future = mqtt_connection.connect() connect_future.result() print("Connected!") print() print("Enter message to Publish. or Enter 'exit' to close.") while True: self.MESSAGE = input(">> ") if self.MESSAGE == "exit": break message = {"message": self.MESSAGE} mqtt_connection.publish(topic=self.TOPIC, payload=json.dumps(message), qos=mqtt.QoS.AT_LEAST_ONCE) print("Published: '" + json.dumps(message) + "' to the topic: " + self.TOPIC) t.sleep(1) print('Closing connection') disconnect_future = mqtt_connection.disconnect() disconnect_future.result()
def __init__(self): self.logger = get_logger(self.__class__.__name__) self.shutdown_flag = threading.Event() self.id = args.endpoint.split('-')[0] # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) self.mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=args.endpoint, cert_filepath=args.cert, pri_key_filepath=args.key, client_bootstrap=client_bootstrap, ca_filepath=args.root_ca, on_connection_interrupted=self.on_connection_interrupted, on_connection_resumed=self.on_connection_resumed, client_id=args.client_id, clean_session=False, keep_alive_secs=60) self.logger.debug("Connecting to {} with client ID '{}'...".format( args.endpoint, args.client_id)) connect_future = self.mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() self.logger.info(f"Connected with {args.endpoint}")
def start(self): 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(self.certificate_path, self.private_key_path) if self.root_ca_path: tls_options.override_default_trust_store_from_path(None, self.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, self.region) resp_future = discovery_client.discover(self.thing_name) discover_response = resp_future.result() mqtt_connection = self.try_iot_endpoints(discover_response, client_bootstrap) self.conn = mqtt_connection if self.mode == 'both' or self.mode == 'subscribe': def on_publish(topic, payload, **kwargs): print('Publish received on topic {}'.format(topic)) f = open(self.response_file_path, "w") f.write(payload) f.close() print(payload) subscribe_future, _ = mqtt_connection.subscribe(self.topic_response_validateTicket, QoS.AT_MOST_ONCE, on_publish) subscribe_result = subscribe_future.result() print(subscribe_result)
def get_mqtt_connection_over_websocket(): client_id = conf.CLIENT_ID + str(uuid.uuid4()) # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) # use websocket proxy_options = http.HttpProxyOptions(host_name=conf.PROXY_HOST, port=conf.PROXY_PORT) credentials_provider = auth.AwsCredentialsProvider.new_default_chain(client_bootstrap) mqtt_connection = mqtt_connection_builder.websockets_with_default_aws_signing( endpoint=conf.ENDPOINT, client_bootstrap=client_bootstrap, region=conf.SIGNING_REGION, credentials_provider=credentials_provider, websocket_proxy_options=proxy_options, ca_filepath=conf.ROOT_CERT_PATH, on_connection_interrupted=cb.on_connection_interrupted, on_connection_resumed=cb.on_connection_resumed, client_id=client_id, clean_session=False, keep_alive_secs=6) return mqtt_connection
def connect(endpoint, cert, pri_key, root_ca, client_id): """ Connects to IoT. Arguments: endpoint - take it from aws site->IoT->Manage->Things->Interact cert, pri_key, root_ca - path to certificates incl. filename client ID - id for the messages posting """ event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=endpoint, cert_filepath=cert, pri_key_filepath=pri_key, client_bootstrap=client_bootstrap, ca_filepath=root_ca, on_connection_interrupted=on_connection_interrupted, on_connection_resumed=on_connection_resumed, client_id=client_id, clean_session=False, keep_alive_secs=6) print("Connecting to {} with client ID '{}'...".format( endpoint, client_id)) connect_future = mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() print("Connected!") return mqtt_connection
def _initialize(self,): # Spin up resources self.process.start() event_loop_group = io.EventLoopGroup(2) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) self.mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint="a3uxhx2wvbys89-ats.iot.us-east-2.amazonaws.com", cert_filepath="key_files/2844a6fa72-cert.pem", pri_key_filepath="key_files/2844a6fa72-private.pem.key", client_bootstrap=client_bootstrap, ca_filepath="key_files/root-CA.crt", on_connection_interrupted=self.on_connection_interrupted, on_connection_resumed=self.on_connection_resumed, client_id=self.config_clientId, clean_session=False, keep_alive_secs=6) print("Connecting to {} with client ID '{}'...".format( "endpoint", "muvva mac")) connect_future = self.mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() print("Connected!")
def core_connect(self): """ Method used to connect to connect to AWS IoTCore Service. Endpoint collected from config. """ if self.isRotation: self.logger.info('##### CONNECTING WITH EXISTING CERT #####') print('##### CONNECTING WITH EXISTING CERT #####') self.get_current_certs() else: self.logger.info('##### CONNECTING WITH PROVISIONING CLAIM CERT #####') print('##### CONNECTING WITH PROVISIONING CLAIM CERT #####') event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) self.primary_MQTTClient = mqtt_connection_builder.mtls_from_path( endpoint=self.iot_endpoint, cert_filepath="{}/{}".format(self.secure_cert_path, self.claim_cert), pri_key_filepath="{}/{}".format(self.secure_cert_path, self.secure_key), client_bootstrap=client_bootstrap, ca_filepath="{}/{}".format(self.secure_cert_path, self.root_cert), on_connection_interrupted=self.on_connection_interrupted, on_connection_resumed=self.on_connection_resumed, client_id=self.unique_id, clean_session=False, keep_alive_secs=6) print("Connecting to {} with client ID '{}'...".format(self.iot_endpoint, self.unique_id)) connect_future = self.primary_MQTTClient.connect() # Future.result() waits until a result is available connect_future.result() print("Connected!")
def connect(self): self.device_name = self.scope['url_route']['kwargs']['device_name'] self.accept() # Creating event loop self.event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(self.event_loop_group) client_bootstrap = io.ClientBootstrap(self.event_loop_group, host_resolver) self.mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=os.getenv('MQTT_ENDPOINT'), port=int(os.getenv('MQTT_PORT')), cert_filepath="./certs/iot_multisensor_certificate.pem.crt", pri_key_filepath="./certs/iot_multisensor_private.pem.key", ca_filepath="./certs/AmazonRootCA1.pem", client_bootstrap=client_bootstrap, clean_session=False, client_id="iot-" + str(uuid4()), keep_alive_secs=6, ) connect_future = self.mqtt_connection.connect() connect_future.result() subscribe_temp, packet_id_t = self.mqtt_connection.subscribe( topic="temperature", qos=mqtt.QoS.AT_LEAST_ONCE, callback=self.on_temp_received) subscribe_result = subscribe_temp.result() print("Subscribed with {}".format(str(subscribe_result['qos']))) subscribe_humid, packet_id_h = self.mqtt_connection.subscribe( topic="humidity", qos=mqtt.QoS.AT_LEAST_ONCE, callback=self.on_humid_received) subscribe_result = subscribe_humid.result() print("Subscribed with {}".format(str(subscribe_result['qos'])))
def sendData(data): # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=ENDPOINT, cert_filepath=PATH_TO_CERT, pri_key_filepath=PATH_TO_KEY, client_bootstrap=client_bootstrap, ca_filepath=PATH_TO_ROOT, client_id=CLIENT_ID, clean_session=False, keep_alive_secs=6) print("Connecting to {} with client ID '{}'...".format( ENDPOINT, CLIENT_ID)) # Make the connect() call connect_future = mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() print("Connected!") # Publish message to server desired number of times. print('Begin Publish') mqtt_connection.publish(topic=TOPIC, payload=json.dumps(data), qos=mqtt.QoS.AT_LEAST_ONCE) print("Published: '" + json.dumps(data) + "' to the topic: " + TOPIC) print('Publish End') disconnect_future = mqtt_connection.disconnect() disconnect_future.result()
def connect(self): """ Method to connect to IoT MQTT via IAM mode. It uses the current exection role to setup the connection. """ event_loop_group = io.EventLoopGroup() host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) credentials_provider = auth.AwsCredentialsProvider.new_default_chain( client_bootstrap) iot_client = boto3.client('iot') endpoint = iot_client.describe_endpoint( endpointType='iot:Data-ATS')['endpointAddress'] region = endpoint.split(".")[2] mqtt_connection = mqtt_connection_builder.websockets_with_default_aws_signing( endpoint=endpoint, client_bootstrap=client_bootstrap, client_id=self.client_id, region=region, credentials_provider=credentials_provider, clean_session=False) logging.info("Connecting to {} with client ID '{}'...".format( endpoint, self.client_id)) # Make the connect() call connect_future = mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() logging.info("Connected!") self.mqtt_connection = mqtt_connection return True
def Connect(self): self.logging.info("Getting mqtt secrets...") secret = Secrets.GetSecrets(self.settings.mqtt_region, self.settings.mqtt_secretname) self.event_loop_group = io.EventLoopGroup(1) self.host_resolver = io.DefaultHostResolver(self.event_loop_group) self.client_bootstrap = io.ClientBootstrap(self.event_loop_group, self.host_resolver) self.logging.info("Building a connection...") self.mqtt_connection = mqtt_connection_builder.mtls_from_bytes( cert_bytes=secret.CertFileBin, pri_key_bytes=secret.PropertyFileBin, endpoint=self.settings.mqtt_endpoint, client_bootstrap=self.client_bootstrap, client_id=self.settings.mqtt_clientid, region=self.settings.mqtt_region, clean_session=False, keep_alive_secs=6) self.logging.info( f"Connecting to {self.settings.mqtt_endpoint} with client ID '{self.settings.mqtt_clientid}'..." ) self.connect_future = self.mqtt_connection.connect() # Future.result() waits until a result is available self.connect_future.result() self.logging.info("MQTT Connected!") self.connected = True
def initialize_shadow(config): endpoint_id = config["id"] client_id = "{}-{}".format(CLIENT_ID_CONTROLLER, endpoint_id) event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=config["endpoint"], cert_filepath=config["certificatePath"], pri_key_filepath=config["privateKeyPath"], ca_filepath=config["rootCAPath"], client_bootstrap=client_bootstrap, client_id=client_id, clean_session=False, keep_alive_secs=6, ) print("Connectin to {} with client ID '{}'...".format( config["endpoint"], client_id)) connected_future = mqtt_connection.connect() shadow_client = iotshadow.IotShadowClient(mqtt_connection) connected_future.result() print("Connected and created device shadow for {}".format(client_id)) return shadow_client
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')
def connect(self): """Connect to AWS IoT""" if not self.certificate_path or not self.private_key_path: print("Missing credentials for authentication.") exit(2) # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) if self.use_websocket == True: proxy_options = None if (self.proxy_host): proxy_options = http.HttpProxyOptions( host_name=self.proxy_host, port=self.proxy_port) credentials_provider = auth.AwsCredentialsProvider.new_default_chain( client_bootstrap) self.iot_client = mqtt_connection_builder.websockets_with_default_aws_signing( endpoint=self.host, client_bootstrap=client_bootstrap, region=self.signing_region, credentials_provider=credentials_provider, websocket_proxy_options=proxy_options, ca_filepath=self.root_ca_path, on_connection_interrupted=on_connection_interrupted, on_connection_resumed=on_connection_resumed, client_id=self.client_id, clean_session=False, keep_alive_secs=6) else: self.iot_client = mqtt_connection_builder.mtls_from_path( endpoint=self.host, cert_filepath=self.certificate_path, pri_key_filepath=self.private_key_path, client_bootstrap=client_bootstrap, ca_filepath=self.root_ca_path, on_connection_interrupted=on_connection_interrupted, on_connection_resumed=on_connection_resumed, client_id=self.client_id, clean_session=False, keep_alive_secs=6) print("Connecting to {} with client ID '{}'...".format( self.host, self.client_id)) connect_future = self.iot_client.connect() # Future.result() waits until a result is available connect_future.result() sleep(2)
def __init__(self): self.logger = get_logger(self.__class__.__name__) self.shutdown_flag = threading.Event() self.id = args.endpoint.split('-')[0] self.interval = args.interval # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) if args.use_websocket == True: proxy_options = None if (args.proxy_host): proxy_options = http.HttpProxyOptions(host_name=args.proxy_host, port=args.proxy_port) credentials_provider = auth.AwsCredentialsProvider.new_default_chain(client_bootstrap) self.mqtt_connection = mqtt_connection_builder.websockets_with_default_aws_signing( endpoint=args.endpoint, client_bootstrap=client_bootstrap, region=args.signing_region, credentials_provider=credentials_provider, websocket_proxy_options=proxy_options, ca_filepath=args.root_ca, on_connection_interrupted=self.on_connection_interrupted, on_connection_resumed=self.on_connection_resumed, client_id=args.client_id, clean_session=False, keep_alive_secs=60) else: self.mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=args.endpoint, cert_filepath=args.cert, pri_key_filepath=args.key, client_bootstrap=client_bootstrap, ca_filepath=args.root_ca, on_connection_interrupted=self.on_connection_interrupted, on_connection_resumed=self.on_connection_resumed, client_id=args.client_id, clean_session=False, keep_alive_secs=60) self.logger.debug("Connecting to {} with client ID '{}'...".format( args.endpoint, args.client_id)) connect_future = self.mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() self.logger.info(f"Connected with {args.endpoint}")
def begin_resources(): config = get_mqtt_config() endpoint = config["endpoint"] client_id = config["client_id"] topic = config["topic"] event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) credentials_provider = auth.AwsCredentialsProvider.new_default_chain( client_bootstrap) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=endpoint, cert_filepath=config["cert_filepath"], pri_key_filepath=config["pri_key_filepath"], client_bootstrap=client_bootstrap, ca_filepath=config["ca_filepath"], on_connection_interrupted=on_connection_interrupted, on_connection_resumed=on_connection_resumed, client_id=client_id, clean_session=config["clean_session"], keep_alive_secs=config["keep_alive_secs"]) print('Connecting to {} with client ID "{}"...'.format( endpoint, client_id)) connect_future = mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() print("Connected!") # Subscribe print("Subscribing to topic '{}'".format(topic)) subscribe_future, packet_id = mqtt_connection.subscribe( topic=topic, qos=mqtt.QoS.AT_LEAST_ONCE, callback=on_message_received) subscribe_result = subscribe_future.result() print("Subscribed with {}".format(str(subscribe_result['qos']))) while True: message = "test" print("Publishing message to topic '{}': {}".format(topic, message)) mqtt_connection.publish(topic=topic, payload=message, qos=mqtt.QoS.AT_LEAST_ONCE) time.sleep(5)
def device_main(): """ main loop for dummy device """ global device_name, mqtt_connection init_info = arg_check() device_name = init_info['device_name'] iot_endpoint = init_info['endpoint'] rootca_file = init_info['certs'][0] private_key_file = init_info['certs'][1] certificate_file = init_info['certs'][2] logger.info("device_name: %s", device_name) logger.info("endpoint: %s", iot_endpoint) logger.info("rootca cert: %s", rootca_file) logger.info("private key: %s", private_key_file) logger.info("certificate: %s", certificate_file) # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=iot_endpoint, cert_filepath=certificate_file, pri_key_filepath=private_key_file, client_bootstrap=client_bootstrap, ca_filepath=rootca_file, client_id=device_name, clean_session=False, keep_alive_secs=KEEPALIVE) connected_future = mqtt_connection.connect() # Start sending dummy data topic = BASE_TOPIC + device_name logging.info("topic: %s", topic) while True: now = datetime.now().strftime('%Y-%m-%dT%H:%M:%S') tmp = 20 + random.randint(-5, 5) payload = {"DEVICENAME": device_name, "TIMESTAMP": now, "VALUE": tmp} logger.debug(" payload: %s", payload) mqtt_connection.publish(topic=topic, payload=json.dumps(payload), qos=mqtt.QoS.AT_LEAST_ONCE) time.sleep(DEFAULT_WAIT_TIME)
def __init__( self, endpoint, cert_path, key_path, root_ca_path, client_id, settings_topic, device_update_topic, ): self.endConnection = Event() event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) self.endpoint = endpoint self.cert = cert_path self.key = key_path self.root_ca = root_ca_path self.settings_topic = settings_topic self.data_topic = device_update_topic self.client_id = client_id self.mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=self.endpoint, cert_filepath=self.cert, pri_key_filepath=self.key, client_bootstrap=client_bootstrap, ca_filepath=self.root_ca, on_connection_interrupted=on_connection_interrupted, on_connection_resumed=on_connection_resumed, client_id=self.client_id, clean_session=False, keep_alive_secs=6, ) print( "Connecting to {} with client ID '{}'...".format( self.endpoint, self.client_id ) ) self.connect_future = self.mqtt_connection.connect() # Future.result() waits until a result is available self.connect_future.result() print("Connected!") self.settings_topic = settings_topic self.data_topic = device_update_topic
def __init__(self, client_id, endpoint, cert, key, root_ca, conn_int, conn_res): self.event_loop_group = io.EventLoopGroup(1) self.host_resolver = io.DefaultHostResolver(self.event_loop_group) self.client_bootstrap = io.ClientBootstrap(self.event_loop_group, self.host_resolver) self.connection = mqtt_connection_builder.mtls_from_path( endpoint=endpoint, cert_filepath=cert, pri_key_filepath=key, client_bootstrap=self.client_bootstrap, ca_filepath=root_ca, on_connection_interrupted=conn_int, on_connection_resumed=conn_res, client_id=client_id, clean_session=False, keep_alive_secs=6)
def connect(): global connect_future, mqtt_connection session = boto3.session.Session() client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) credentials_provider = auth.AwsCredentialsProvider.new_default_chain( client_bootstrap) mqtt_connection = mqtt_connection_builder.websockets_with_default_aws_signing( endpoint=os.getenv("IOT_ENDPOINT"), client_bootstrap=client_bootstrap, region="us-east-1", credentials_provider=credentials_provider, client_id=str(uuid.uuid4()), clean_session=False, keep_alive_secs=6, ) connect_future = mqtt_connection.connect() connect_future.result()
def main(vin, dtc): #Set Config path CONFIG_PATH = 'config.ini' payloadhandler = payloadHandler(CONFIG_PATH) #c = Cognito(profile) #m = ConnectedMobility(profile, stackname) config = Config(CONFIG_PATH) config_parameters = config.get_section('SETTINGS') ENDPOINT = config_parameters['IOT_ENDPOINT'] CLIENT_ID = vin PATH_TO_CERT = "{}/{}".format(config_parameters['SECURE_CERT_PATH'].format(unique_id=CLIENT_ID), config_parameters['PROD_CERT']) PATH_TO_KEY = "{}/{}".format(config_parameters['SECURE_CERT_PATH'].format(unique_id=CLIENT_ID), config_parameters['PROD_KEY']) PATH_TO_ROOT = "{}/{}".format(config_parameters['ROOT_CERT_PATH'], config_parameters['ROOT_CERT']) event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) test_MQTTClient = mqtt_connection_builder.mtls_from_path( endpoint=ENDPOINT, cert_filepath=PATH_TO_CERT, pri_key_filepath=PATH_TO_KEY, client_bootstrap=client_bootstrap, ca_filepath=PATH_TO_ROOT, client_id=CLIENT_ID, clean_session=False, on_connection_interrupted=on_connection_interrupted, on_connection_resumed=on_connection_resumed, keep_alive_secs=6) print("Connecting with Prod certs to {} with client ID '{}'...".format(ENDPOINT, CLIENT_ID)) connect_future = test_MQTTClient.connect() connect_future.result() print("Connected with production certificates to the endpoint") payload = payloadhandler.getDTCPayload( dtc, CLIENT_ID) payloadhandler.publishDTCPayload(test_MQTTClient, payload, CLIENT_ID) print("Successfully published DTC: {}".format(dtc)) exit()
def main(): # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=config['endpoint'], cert_filepath=config['cert'], pri_key_filepath=config['key'], client_bootstrap=client_bootstrap, ca_filepath=config['root-ca'], on_connection_interrupted=on_connection_interrupted, on_connection_resumed=on_connection_resumed, client_id=config['sensor-name'], clean_session=False, keep_alive_secs=6) log.info("Connecting to {} with client ID '{}'...".format( config['endpoint'], config['sensor-name'])) connect_future = mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() log.info("Connected!") # initialise & start sensor sensor = AM2315.AM2315() topic_name = "{}/{}/{}/{}".format(config['topic-root'], config['site-name'], config['location'], config['sensor-name']) while True: # read payload from sensor payload = read_sensor(sensor) payload['location'] = config['location'] print("Publishing message to topic '{}': {}".format( topic_name, json.dumps(payload))) mqtt_connection.publish(topic=topic_name, payload=json.dumps(payload), qos=mqtt.QoS.AT_LEAST_ONCE) time.sleep(config['cycle-period'])
def __init__(self): self.constants = json.load(open('config.json', 'r'))['mqtt'] event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) self.mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=self.constants['endpoint'], cert_filepath=self.constants['path_to_cert'], pri_key_filepath=self.constants['path_to_key'], client_bootstrap=client_bootstrap, ca_filepath=self.constants['path_to_root'], client_id=self.constants['client_id'], clean_session=False, keep_alive_secs=6) connect_future = self.mqtt_connection.connect() connect_future.result() print("MQTT Client Connected!")
def publish(event: object, context: object): """IoTCoreにPublishメッセージを送信します Args: event (object): [description] context (object): [description] """ logger.info('=== PUBLISH ===') # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=ENDPOINT, cert_filepath=PATH_TO_CERT, pri_key_filepath=PATH_TO_KEY, client_bootstrap=client_bootstrap, ca_filepath=PATH_TO_ROOT, client_id=CLIENT_ID, clean_session=False, keep_alive_secs=6) print("Connecting to {} with client ID '{}'...".format( ENDPOINT, CLIENT_ID)) # Make the connect() call connect_future = mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() logger.info('=== CONNECTED ===') # Publish message to server desired number of times. for i in range(RANGE): data = "{} [{}]".format(MESSAGE, i + 1) message = {"message": data} mqtt_connection.publish(topic=TOPIC, payload=json.dumps(message), qos=mqtt.QoS.AT_LEAST_ONCE) logger.info(f'{TOPIC} : {json.dumps(message)}') t.sleep(0.1) disconnect_future = mqtt_connection.disconnect() disconnect_future.result() logger.info('=== PUBLISH END ===')
def cert_validation_test(self): event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) self.test_MQTTClient = mqtt_connection_builder.mtls_from_path( endpoint=self.iot_endpoint, cert_filepath="{}/{}".format(self.secure_cert_path, self.new_cert_name), pri_key_filepath="{}/{}".format(self.secure_cert_path, self.new_key_name), client_bootstrap=client_bootstrap, ca_filepath="{}/{}".format(self.secure_cert_path, self.root_cert), client_id=self.unique_id + "-Prod", clean_session=False, keep_alive_secs=6) print("Connecting with Prod certs to {} with client ID '{}'...".format(self.iot_endpoint, self.unique_id + "-Prod")) connect_future = self.test_MQTTClient.connect() # Future.result() waits until a result is available connect_future.result() print("Connected with Prod certs!")
def get_mqtt_connection(cert_path, pri_key_path): client_id = conf.CLIENT_ID + str(uuid.uuid4()) # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=conf.ENDPOINT, cert_filepath=cert_path, pri_key_filepath=pri_key_path, client_bootstrap=client_bootstrap, ca_filepath=conf.ROOT_CERT_PATH, on_connection_interrupted=cb.on_connection_interrupted, on_connection_resumed=cb.on_connection_resumed, client_id=client_id, clean_session=False, keep_alive_secs=6) return mqtt_connection
def connect(self): event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) self.mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=self.endpoint, cert_filepath=self.certificate_path, pri_key_filepath=self.private_key_path, client_bootstrap=client_bootstrap, ca_filepath=self.root_ca_path, client_id=self.thing_name, clean_session=False, keep_alive_secs=6) connected_future = self.mqtt_connection.connect() self.shadow_client = iotshadow.IotShadowClient(self.mqtt_connection) connected_future.result() logging.info("Connected to mqtt server.")
def __enter__(self) -> "CloudClient": # Spin up resources _LOGGER.info("Initialising...") event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) # Create a connection (the shadow needs a started connection) _LOGGER.info("Connecting...") self._mqtt = self._create_mqtt_connection(client_bootstrap) connected_future = self._mqtt.connect() # Create a shadow client _LOGGER.info("Creating shadow client...") self._shadow = IotShadowClient(self._mqtt) # Wait for connection to be fully established. # Note that it's not necessary to wait, commands issued to the # mqtt_connection before its fully connected will simply be queued. # But this sample waits here so it's obvious when a connection # fails or succeeds. connected_future.result() _LOGGER.info("Connected!") self._subscribe_to_update_requests(self._mqtt) return self
def __init__(self, root_ca, key, cert, endpoint): client_id = self.__create_client_id("client_id") event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) self.__mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=endpoint, cert_filepath=cert, pri_key_filepath=key, client_bootstrap=client_bootstrap, ca_filepath=root_ca, client_id=client_id, clean_session=False, keep_alive_secs=6) print(f"Connecting to {endpoint} with client ID '{client_id}'...") connected_future = self.__mqtt_connection.connect() connected_future.result() print("Connected!")
def connect_mqtt(msg): # Define ENDPOINT, CLIENT_ID, PATH_TO_CERT, PATH_TO_KEY, PATH_TO_ROOT, MESSAGE, TOPIC, and RANGE ENDPOINT = "a1sx0mf4p4ad71-ats.iot.us-east-1.amazonaws.com" CLIENT_ID = "testAndroid" PATH_TO_CERT = "certs/phone_certificate.pem.crt" PATH_TO_KEY = "certs/phone_private.pem.key" PATH_TO_ROOT = "certs/root.pem" MESSAGE = "Hello World" TOPIC = "hummel" RANGE = 20 event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=ENDPOINT, cert_filepath=PATH_TO_CERT, pri_key_filepath=PATH_TO_KEY, client_bootstrap=client_bootstrap, ca_filepath=PATH_TO_ROOT, client_id=CLIENT_ID, clean_session=False, keep_alive_secs=6) print("Connecting to {} with client ID '{}'...".format( ENDPOINT, CLIENT_ID)) # Make the connect() call connect_future = mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() print("Connected!") # Publish message to server desired number of times. print('Begin Publish') mqtt_connection.publish(topic=TOPIC, payload=msg, qos=mqtt.QoS.AT_LEAST_ONCE) print("Published: '" + msg + "' to the topic: " + TOPIC) print('Publish End') disconnect_future = mqtt_connection.disconnect() disconnect_future.result()