示例#1
0
    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(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)
示例#3
0
    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}")
示例#4
0
def set_mqtt_connection(args, client_bootstrap):
    if args.use_websocket:
        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)
        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=on_connection_interrupted,
            on_connection_resumed=on_connection_resumed,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6)

    else:
        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=on_connection_interrupted,
            on_connection_resumed=on_connection_resumed,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6)

    return mqtt_connection
    print("Received message from topic '{}': {}".format(topic, payload))
    global received_count
    received_count += 1
    if received_count == args.count:
        received_all_event.set()

if __name__ == '__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)

    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)
        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=on_connection_interrupted,
            on_connection_resumed=on_connection_resumed,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6)
示例#6
0
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)
    


    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)
        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=on_connection_interrupted,
            on_connection_resumed=on_connection_resumed,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6)

    else:
        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=on_connection_interrupted,
            on_connection_resumed=on_connection_resumed,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6)

    print("Connecting to {} with client ID '{}'...".format(
        args.endpoint, args.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(args.topic))
    subscribe_future, packet_id = mqtt_connection.subscribe(
        topic=args.topic,
        qos=mqtt.QoS.AT_LEAST_ONCE,
        callback=on_message_received)

    subscribe_result = subscribe_future.result()
    print("Subscribed with {}".format(str(subscribe_result['qos'])))

    # Publish message to server From Raspberry Pi.
    # This step Sends Payload each time button is pressed.


    lightPin = 4
    buttonPin = 17

    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)

    lightPin = 4
    buttonPin = 17
    GPIO.setup(lightPin, GPIO.OUT,initial=GPIO.LOW)
    GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    if args.count == 0:
        print ("Sending messages until program killed")
    else:
        print ("Sending {} message(s)".format(args.count))

    def mqttPublishLines(buttonPin):
        publish_count = 1
        filepath = "/home/pi/awsiot/mqtt/data/speeding_data.csv"
        file = open(filepath, "r")
        #line = file.readlines()
        line = file.read().splitlines()
        while (publish_count <= args.count) or (args.count == 0):
            if GPIO.input(buttonPin)==GPIO.LOW:
                payload = {"iottimestamp":str(datetime.utcnow()),
                            "licensePlate":line[publish_count].split(",")[0],
                            "longitude":line[publish_count].split(",")[1],
                            "latitude":line[publish_count].split(",")[2],
                            "city":line[publish_count].split(",")[3],
                            "state":line[publish_count].split(",")[4],
                            "speed":line[publish_count].split(",")[5] }
                message = json.dumps(payload)
                print("Button Pressed", publish_count)
                GPIO.output(lightPin, True)
                mqtt_connection.publish(
                topic=args.topic,
                payload=message,
                qos=mqtt.QoS.AT_LEAST_ONCE)
                time.sleep(1)
                publish_count += 1
            else:
                GPIO.output(lightPin, False)

    GPIO.add_event_detect(buttonPin,GPIO.BOTH,callback=mqttPublishLines,bouncetime=300)


    # Wait for all messages to be received.
    # This waits forever if count was set to 0.
    if args.count != 0 and not received_all_event.is_set():
        print("Waiting for all messages to be received...")

    received_all_event.wait()
    print("{} message(s) received.".format(received_count))

    # Disconnect
    print("Disconnecting...")
    disconnect_future = mqtt_connection.disconnect()
    disconnect_future.result()
    print("Disconnected!")
示例#7
0
    def main(self, args):
        # logging.debug("Spinning up Shadow awsiot resources")
        event_loop_group = io.EventLoopGroup(1)
        host_resolver = io.DefaultHostResolver(event_loop_group)
        client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)
        # logging.debug("Shadow resources up")

        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,
                client_id=args.client_id,
                clean_session=False,
                keep_alive_secs=6)

        else:
            # attrs = vars(args)
            # print(', '.join("%s: %s" % item for item in list(attrs.items())))
            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,
                client_id=args.client_id,
                clean_session=False,
                keep_alive_secs=6)

        print("Connecting to {} with client ID '{}'...".format(
            args.endpoint, args.client_id))
        logging.debug("Connecting to {} with client ID '{}'...".format(
            args.endpoint, args.client_id))

        connected_future = self.mqtt_connection.connect()

        self.shadow_client = iotshadow.IotShadowClient(self.mqtt_connection)

        # 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()
        print("Connected!")
        logging.debug("Connected!")

        try:
            # Subscribe to necessary topics.
            # Note that is **is** important to wait for "accepted/rejected" subscriptions
            # to succeed before publishing the corresponding "request".
            # print("Subscribing to Delta events...")
            delta_subscribed_future, _ = self.shadow_client.subscribe_to_shadow_delta_updated_events(
                request=iotshadow.ShadowDeltaUpdatedSubscriptionRequest(
                    args.thing_name),
                qos=mqtt.QoS.AT_LEAST_ONCE,
                callback=self.on_shadow_delta_updated)

            # Wait for subscription to succeed
            delta_subscribed_future.result()

            # print("Subscribing to Update responses...")
            update_accepted_subscribed_future, _ = self.shadow_client.subscribe_to_update_shadow_accepted(
                request=iotshadow.UpdateShadowSubscriptionRequest(
                    args.thing_name),
                qos=mqtt.QoS.AT_LEAST_ONCE,
                callback=self.on_update_shadow_accepted)

            update_rejected_subscribed_future, _ = self.shadow_client.subscribe_to_update_shadow_rejected(
                request=iotshadow.UpdateShadowSubscriptionRequest(
                    args.thing_name),
                qos=mqtt.QoS.AT_LEAST_ONCE,
                callback=self.on_update_shadow_rejected)

            # Wait for subscriptions to succeed
            update_accepted_subscribed_future.result()
            update_rejected_subscribed_future.result()

            # print("Subscribing to Get responses...")
            get_accepted_subscribed_future, _ = self.shadow_client.subscribe_to_get_shadow_accepted(
                request=iotshadow.GetShadowSubscriptionRequest(
                    args.thing_name),
                qos=mqtt.QoS.AT_LEAST_ONCE,
                callback=self.on_get_shadow_accepted)

            get_rejected_subscribed_future, _ = self.shadow_client.subscribe_to_get_shadow_rejected(
                request=iotshadow.GetShadowSubscriptionRequest(
                    args.thing_name),
                qos=mqtt.QoS.AT_LEAST_ONCE,
                callback=self.on_get_shadow_rejected)

            # Wait for subscriptions to succeed
            get_accepted_subscribed_future.result()
            get_rejected_subscribed_future.result()

            # The rest of the sample runs asyncronously.

            # Issue request for shadow's current state.
            # The response will be received by the on_get_accepted() callback
            # print("Requesting current shadow state...")
            publish_get_future = self.shadow_client.publish_get_shadow(
                request=iotshadow.GetShadowRequest(args.thing_name),
                qos=mqtt.QoS.AT_LEAST_ONCE)

            # Ensure that publish succeeds
            publish_get_future.result()

            # Launch thread to handle user input.
            # A "daemon" thread won't prevent the program from shutting down.
            # print("Launching thread to read user input...")
            # user_input_thread = threading.Thread(target=user_input_thread_fn, name='user_input_thread')
            # user_input_thread.daemon = True
            # user_input_thread.start()

            # Launch thread to send telemetry updates to shadow
            self.telemetry_thread = threading.Thread(
                target=self.get_robot_telemetry,
                name='Robot Telemetry Thread',
                args=(args.robot_url, args.robot_ca))
            # self.telemetry_thread.daemon = True
            self.telemetry_thread.start()

        except Exception as e:
            self.exit(e)

        # Wait for the sample to finish (user types 'quit', or an error occurs)
        self.is_sample_done.wait()
def main():
    event_loop_group = io.EventLoopGroup(1)
    host_resolver = io.DefaultHostResolver(event_loop_group)
    client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)

    #See documentation for arguments used in each mqtt_connection definition here>>https://awslabs.github.io/aws-crt-python/api/mqtt_connection_builder.html
    if args.use_websocket == True: #Logic for this sourced from aws IoT SDK
        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)
        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=handleInterruptedConnection,
            on_connection_resumed=handleResumedConnection,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6)

    else:
        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=handleInterruptedConnection,
            on_connection_resumed=handleResumedConnection,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6)

    handleLoggingRequest("Attempting connection to endpoint {} with client ID {}".format(args.endpoint, args.client_id), logging.info)

    connect_future = mqtt_connection.connect()

    # Future.result() waits until a result is available
    connect_future.result()
    handleLoggingRequest("Connected successfully to endpoint {} with client ID {}".format(args.endpoint, args.client_id), logging.info)

    # Subscribe
    handleLoggingRequest("Subscribing to topic {}".format(args.topic), logging.info)

    subscribe_future, packet_id = mqtt_connection.subscribe(
        topic=args.topic,
        qos=mqtt.QoS.AT_LEAST_ONCE,
        callback=handleMessage)

    subscribe_result = subscribe_future.result()
    handleLoggingRequest("Subscribed with {}".format(str(subscribe_result['qos'])), logging.info)
    
    # Publish message to server desired number of times.
    # This step is skipped if message is blank.
    # This step loops forever if count was set to 0.
    if args.message:
        print()
        if args.count == 0:
            handleLoggingRequest("Message transmission started.  Messages will be sent every {} seconds".format(args.uploadInterval), logging.info)
        else:
            handleLoggingRequest("Manual override by client.  Only sending {} message(s)".format(args.count), logging.info)

        publish_count = 1
        while (publish_count <= args.count) or (args.count == 0):
            with open(args.dataPath) as aircraftDataFile:    
                aircraftMessage = json.load(aircraftDataFile)
            message = "{} [{}]".format(aircraftMessage, publish_count)
            handleLoggingRequest("Publishing message to topic '{}'".format(args.topic), logging.info)
            mqtt_connection.publish(
                topic=args.topic,
                payload=message,
                qos=mqtt.QoS.AT_LEAST_ONCE)
            time.sleep(args.uploadInterval)
            publish_count += 1

    # Wait for all messages to be received.
    # This waits forever if count was set to 0.
    if args.count != 0 and not threadingReceiptQueue.is_set():
        handleLoggingRequest("Messages sent, waiting for all messages to confirm receipt in IoT.  Current queue is '{}'".format(received_count), logging.warning)

    threadingReceiptQueue.wait()
    handleLoggingRequest("{} message(s) received by IoT.".format(received_count), logging.info)

    # Disconnect
    handleLoggingRequest("Disconnecting from MQTT connection", logging.info)

    disconnect_future = mqtt_connection.disconnect()
    disconnect_future.result()

    handleLoggingRequest("Disconnected from MQTT connection", logging.info)