Example #1
0
    def sendC2DMsg(msg):
        try:

            iothub_messaging = IoTHubMessaging(CONNECTION_STRING)
            #time.sleep(10)

            iothub_messaging.set_feedback_message_callback(
                feedback_received_callback, FEEDBACK_CONTEXT)

            iothub_messaging.open(open_complete_callback, OPEN_CONTEXT)

            message = IoTHubMessage(bytearray(msg, 'utf8'))

            i = 1

            # optional: assign ids
            message.message_id = "message_%d" % i
            message.correlation_id = "correlation_%d" % i
            # optional: assign properties
            prop_map = message.properties()
            prop_text = "PropMsg_%d" % i
            prop_map.add("Property", prop_text)

            iothub_messaging.send_async(DEVICE_ID, message,
                                        send_complete_callback, i)
            MESSAGE_RECEIVED_EVENT.wait(30)
            iothub_messaging.close()
        except IoTHubError as iothub_error:
            print("Unexpected error {0}" % iothub_error)
            return
        except KeyboardInterrupt:
            print("IoTHubMessaging sample stopped")
Example #2
0
def iothub_messaging_sample_run():
    try:
        iothub_messaging = IoTHubMessaging(CONNECTION_STRING)
        iothub_messaging.set_feedback_message_callback(
            feedback_received_callback, FEEDBACK_CONTEXT)

        iothub_messaging.open(open_complete_callback, OPEN_CONTEXT)

        for i in range(0, MESSAGE_COUNT):
            print('Sending message: {0}'.format(i))
            msg_txt_formatted = MSG_TXT % (AVG_WIND_SPEED +
                                           (random.random() * 4 + 2))
            message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))

            # optional: assign ids
            message.message_id = "message_%d" % i
            message.correlation_id = "correlation_%d" % i
            # optional: assign properties
            prop_map = message.properties()
            prop_text = "PropMsg_%d" % i
            prop_map.add("Property", prop_text)

            iothub_messaging.send_async(DEVICE_ID, message,
                                        send_complete_callback, i)

        try:
            # Try Python 2.xx first
            raw_input("Press Enter to continue...\n")
        except:
            pass
            # Use Python 3.xx in the case of exception
            input("Press Enter to continue...\n")

        iothub_messaging.close()

    except IoTHubError as iothub_error:
        print("Unexpected error {0}" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubMessaging sample stopped")
def iothub_messaging_sample_run():
    try:
        iothub_messaging = IoTHubMessaging(CONNECTION_STRING)
        iothub_messaging.set_feedback_message_callback(feedback_received_callback, FEEDBACK_CONTEXT)

        iothub_messaging.open(open_complete_callback, OPEN_CONTEXT)

        for i in range(0, MESSAGE_COUNT):
            print ( 'Sending message: {0}'.format(i) )
            msg_txt_formatted = MSG_TXT % (
                AVG_WIND_SPEED + (random.random() * 4 + 2))
            message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))

            # optional: assign ids
            message.message_id = "message_%d" % i
            message.correlation_id = "correlation_%d" % i
            # optional: assign properties
            prop_map = message.properties()
            prop_text = "PropMsg_%d" % i
            prop_map.add("Property", prop_text)

            iothub_messaging.send_async(DEVICE_ID, message, send_complete_callback, i)

        try:
            # Try Python 2.xx first
            raw_input("Press Enter to continue...\n")
        except:
            pass
            # Use Python 3.xx in the case of exception
            input("Press Enter to continue...\n")

        iothub_messaging.close()

    except IoTHubError as iothub_error:
        print ( "Unexpected error {0}" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubMessaging sample stopped" )
Example #4
0
def iothub_messaging_sample_run():
    try:
        iothub_messaging = IoTHubMessaging(connection_string)

        iothub_messaging.open(open_complete_callback, open_context)
        while True:
            msg_txt_formatted = input("Please enter your message: \t")
            message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))

            iothub_messaging.send_async(device_id, message,
                                        send_complete_callback, 0)

    except IoTHubError as iothub_error:
        print("Unexpected error {0}" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubMessaging sample stopped")
def iothub_cloud_to_device_messaging(MSG_TXT=None, DEVICE_ID=None):
    try:
        iothub_messaging = IoTHubMessaging(CONNECTION_STRING)
        iothub_messaging.open(open_complete_callback, OPEN_CONTEXT)

        message = IoTHubMessage(bytearray(MSG_TXT, 'utf8'))
        iothub_messaging.send_async(DEVICE_ID, message, send_complete_callback,
                                    None)
        time.sleep(4)
        iothub_messaging.close()

        return True

    except IoTHubError as iothub_error:
        print("Unexpected error {0}" % iothub_error)
        return False
    except KeyboardInterrupt:
        print("IoTHubMessaging sample stopped")
def iothub_message_raspberry(command):
    try:
        iothub_messaging = IoTHubMessaging(CONNECTION_STRING)
        iothub_messaging.open(open_complete_callback, OPEN_CONTEXT)

        for i in range(0, MESSAGE_COUNT):
            msg_txt_formatted = command
            LOG.info("      Sending message: [%s]", msg_txt_formatted)
            message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))

            iothub_messaging.send_async(DEVICE_ID, message,
                                        send_complete_callback, i)
            time.sleep(3)
            iothub_messaging.close()

    except IoTHubError as iothub_error:
        LOG.error("IoT Hub error detected")
        LOG.error("Unexpected error %s from IoTHub", iothub_error)
        return
    except KeyboardInterrupt:
        LOG.error("Messaging has stopped")
Example #7
0
def run_e2e_shared_transport(iothub_registry_manager,
                             iothub_service_client_messaging,
                             iothub_device_method, iothub_device_twin,
                             protocol, authMethod):
    global IOTHUB_CONNECTION_STRING
    global IOTHUB_E2E_X509_CERT
    global IOTHUB_E2E_X509_THUMBPRINT
    global IOTHUB_E2E_X509_PRIVATE_KEY
    global CERTIFICATES
    global DEVICE_MESSAGE_TIMEOUT
    global MESSAGING_MESSAGE
    global MESSAGE_RECEIVE_EVENT
    global MESSAGE_RECEIVE_CALLBACK_COUNTER

    print(
        "********************* run_e2e({0}, {1}) E2E test with shared transport started"
        .format(protocol, authMethod))
    try:
        # Process connection string
        host_name_start = IOTHUB_CONNECTION_STRING.find("HostName")
        host_name_end = IOTHUB_CONNECTION_STRING.find(";", host_name_start)
        host_name_equal_sign = IOTHUB_CONNECTION_STRING.find(
            "=", host_name_start)
        host_name_suffix_separator = IOTHUB_CONNECTION_STRING.find(
            ".", host_name_equal_sign)

        iothub_name = IOTHUB_CONNECTION_STRING[host_name_equal_sign +
                                               1:host_name_suffix_separator]
        iothub_suffix = IOTHUB_CONNECTION_STRING[host_name_suffix_separator +
                                                 1:host_name_end]

        # Create transport
        transport = IoTHubTransport(protocol, iothub_name, iothub_suffix)

        # Create first device
        device_id1 = generate_device_name()
        sc_create_device_and_module_if_needed(iothub_registry_manager,
                                              device_id1, authMethod, False)
        iothub_device1 = iothub_registry_manager.get_device(device_id1)
        assert isinstance(iothub_device1,
                          IoTHubDevice), 'Invalid type returned!'
        assert iothub_device1 != None, "iothub_device is NULL"
        device_key1 = iothub_device1.primaryKey
        device_sas_token1 = ""
        protocol_gateway_host_name1 = ""
        config1 = IoTHubConfig(protocol, device_id1, device_key1,
                               device_sas_token1, iothub_name, iothub_suffix,
                               protocol_gateway_host_name1)

        # Create second device
        device_id2 = generate_device_name()
        sc_create_device_and_module_if_needed(iothub_registry_manager,
                                              device_id2, authMethod, False)
        iothub_device2 = iothub_registry_manager.get_device(device_id2)
        assert isinstance(iothub_device2,
                          IoTHubDevice), 'Invalid type returned!'
        assert iothub_device2 != None, "iothub_device is NULL"
        device_key2 = iothub_device2.primaryKey
        device_sas_token2 = ""
        protocol_gateway_host_name3 = ""
        config2 = IoTHubConfig(protocol, device_id2, device_key2,
                               device_sas_token2, iothub_name, iothub_suffix,
                               protocol_gateway_host_name3)

        device_client1 = IoTHubClient(transport, config1)
        device_client2 = IoTHubClient(transport, config2)

        device_client1.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)
        device_client2.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client1.set_message_callback(receive_message_callback,
                                            MESSAGING_CONTEXT)
        device_client2.set_message_callback(receive_message_callback,
                                            MESSAGING_CONTEXT)

        device_client1.set_connection_status_callback(
            connection_status_callback, CONNECTION_STATUS_CONTEXT)
        device_client2.set_connection_status_callback(
            connection_status_callback, CONNECTION_STATUS_CONTEXT)

        ###########################################################################
        # send_event_async

        # prepare
        MESSAGING_MESSAGE = ''.join(
            [random.choice(string.ascii_letters) for n in range(12)])
        message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))
        MESSAGE_RECEIVE_EVENT.clear()
        MESSAGE_RECEIVE_CALLBACK_COUNTER = 0

        # act
        sc_send_message(iothub_service_client_messaging, device_id1, message,
                        False)
        MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

        MESSAGE_RECEIVE_EVENT.clear()
        sc_send_message(iothub_service_client_messaging, device_id2, message,
                        False)
        MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert MESSAGE_RECEIVE_CALLBACK_COUNTER > 1, "Error: message has not been received"
        ###########################################################################

        retval = 0
    except Exception as e:
        print(
            "(********************* run_e2e({0}, {1}) E2E test with shared transport failed with exception: {2}"
            .format(protocol, authMethod, e))
        retval = 1
    finally:
        sc_delete_device(iothub_registry_manager, device_id1)
        sc_delete_device(iothub_registry_manager, device_id2)

    print(
        "********************* run_e2e({0}, {1}) E2E test with shared transport finished"
        .format(protocol, authMethod))
    return retval
Example #8
0
def run_e2e_device_client(iothub_service_client_messaging,
                          iothub_device_method, iothub_device_twin, device_id,
                          device_or_module_connection_string, protocol,
                          authMethod, testing_modules):
    global IOTHUB_E2E_X509_CERT
    global IOTHUB_E2E_X509_THUMBPRINT
    global IOTHUB_E2E_X509_PRIVATE_KEY
    global CERTIFICATES
    global MESSAGING_CONTEXT

    ###########################################################################
    # IoTHubClient

    # prepare
    # act
    if testing_modules == True:
        device_client = IoTHubModuleClient(device_or_module_connection_string,
                                           protocol)
        assert isinstance(device_client,
                          IoTHubModuleClient), 'Error: Invalid type returned!'
    else:
        device_client = IoTHubDeviceClient(device_or_module_connection_string,
                                           protocol)
        assert isinstance(device_client,
                          IoTHubDeviceClient), 'Error: Invalid type returned!'

    # verify

    assert device_client != None, "Error: device_client is NULL"
    ###########################################################################

    ###########################################################################
    # set_option

    # prepare
    # act
    device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

    if authMethod == IoTHubRegistryManagerAuthMethod.X509_THUMBPRINT:
        device_client.set_option("x509certificate", IOTHUB_E2E_X509_CERT)
        device_client.set_option("x509privatekey", IOTHUB_E2E_X509_PRIVATE_KEY)

    if device_client.protocol == IoTHubTransportProvider.HTTP:
        device_client.set_option("timeout", HTTP_TIMEOUT)
        device_client.set_option("MinimumPollingTime",
                                 HTTP_MINIMUM_POLLING_TIME)

    device_client.set_option("TrustedCerts", CERTIFICATES)
    device_client.set_option("logtrace", True)

    # verify
    ###########################################################################

    if testing_modules == False:  ## Modules do not currently support set_message_callback outside context of Edge inputs/outputs
        ###########################################################################
        # set_message_callback

        # prepare
        # act
        device_client.set_message_callback(receive_message_callback,
                                           MESSAGING_CONTEXT)
        ###########################################################################

    ###########################################################################
    # set_connection_status_callback

    # prepare
    # act
    device_client.set_connection_status_callback(connection_status_callback,
                                                 CONNECTION_STATUS_CONTEXT)
    ###########################################################################

    # verify
    ###########################################################################

    if protocol == IoTHubTransportProvider.AMQP \
       or protocol == IoTHubTransportProvider.AMQP_WS \
       or protocol == IoTHubTransportProvider.MQTT \
       or protocol == IoTHubTransportProvider.MQTT_WS:
        ###########################################################################
        # set_device_twin_callback

        # prepare
        # act
        if testing_modules == True:
            device_client.set_module_twin_callback(device_twin_callback,
                                                   MESSAGING_CONTEXT)
        else:
            device_client.set_device_twin_callback(device_twin_callback,
                                                   MESSAGING_CONTEXT)

        # verify
        ###########################################################################

        ###########################################################################
        # set_device_method_callback

        # prepare
        # act
        if testing_modules == True:
            device_client.set_module_method_callback(device_method_callback,
                                                     MESSAGING_CONTEXT)
        else:
            device_client.set_device_method_callback(device_method_callback,
                                                     MESSAGING_CONTEXT)

        # verify
        ###########################################################################

        ###########################################################################
        # update device twin

        # prepare
        global TWIN_CALLBACK_EVENT
        global TWIN_CALLBACK_COUNTER

        TWIN_CALLBACK_EVENT.clear()
        TWIN_CALLBACK_COUNTER = 0

        # act
        sc_update_twin(iothub_device_twin, device_id, testing_modules)
        TWIN_CALLBACK_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert TWIN_CALLBACK_COUNTER > 0, "Error: device_twin_callback callback has not been called"
        ###########################################################################

        ###########################################################################
        # call device method

        # prepare
        global DEVICE_METHOD_EVENT
        global DEVICE_METHOD_CALLBACK_COUNTER

        DEVICE_METHOD_EVENT.clear()
        DEVICE_METHOD_CALLBACK_COUNTER = 0

        method_name = "E2EMethodName"
        payload_json = "{\"method_number\":\"42\"}"

        # act
        sc_invoke_device_method(iothub_device_method, device_id, method_name,
                                payload_json, testing_modules)
        DEVICE_METHOD_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert DEVICE_METHOD_CALLBACK_COUNTER > 0, "Error: device_twin_callback callback has not been called"
        ###########################################################################

        ###########################################################################
        # send_reported_state

        # prepare
        global REPORTED_STATE_EVENT
        global REPORTED_STATE_CALLBACK_COUNTER

        reported_state = "{\"newState\":\"standBy\"}"
        REPORTED_STATE_EVENT.clear()
        REPORTED_STATE_CALLBACK_COUNTER = 0

        # act
        device_client.send_reported_state(reported_state, len(reported_state),
                                          send_reported_state_callback,
                                          REPORTED_STATE_CONTEXT)
        REPORTED_STATE_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert REPORTED_STATE_CALLBACK_COUNTER > 0, "Error: send_reported_state_callback has not been called"
        ###########################################################################

    ###########################################################################
    # set_retry_policy
    # get_retry_policy

    # prepare
    # act
    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    device_client.set_retry_policy(retryPolicy, retryInterval)
    print("SetRetryPolicy to: retryPolicy = %d" % retryPolicy)
    print("SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" % retryInterval)
    # verify
    retryPolicyReturn = device_client.get_retry_policy()
    assert retryPolicyReturn.retryPolicy == IoTHubClientRetryPolicy.RETRY_INTERVAL, "Error: set_retry_policy/get_retry_policy failed"
    assert retryPolicyReturn.retryTimeoutLimitInSeconds == 100, "Error: set_retry_policy/get_retry_policy failed"
    print("GetRetryPolicy returned: retryPolicy = %d" %
          retryPolicyReturn.retryPolicy)
    print("GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %
          retryPolicyReturn.retryTimeoutLimitInSeconds)

    if testing_modules == False:  ## Modules do not currently support set_message_callback outside context of Edge inputs/outputs
        ###########################################################################
        # send_event_async

        # prepare
        global MESSAGING_MESSAGE
        global MESSAGE_RECEIVE_EVENT
        global MESSAGE_RECEIVE_CALLBACK_COUNTER

        MESSAGING_MESSAGE = ''.join(
            [random.choice(string.ascii_letters) for n in range(12)])
        message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))
        MESSAGE_RECEIVE_EVENT.clear()
        MESSAGE_RECEIVE_CALLBACK_COUNTER = 0

        # act
        sc_send_message(iothub_service_client_messaging, device_id, message,
                        testing_modules)
        MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert MESSAGE_RECEIVE_CALLBACK_COUNTER > 0, "Error: message has not been received"
        ###########################################################################

    ###########################################################################
    # get_send_status

    # prepare
    status_counter = 0
    status = -1

    # act
    while status_counter < 1:
        status = device_client.get_send_status()
        print("Send status: {0}".format(status))

        # verify
        assert status == 0, "get_send_status reported status is not IDLE"
        status_counter += 1
    ###########################################################################


    if protocol != IoTHubTransportProvider.AMQP \
       and protocol != IoTHubTransportProvider.AMQP_WS:
        ###########################################################################
        # get_last_message_receive_time

        # prepare
        last_receive_time = -1
        # act
        last_receive_time = device_client.get_last_message_receive_time()

        # verify
        assert last_receive_time > 0, "Error: get_last_message_receive_time failed"
        ###########################################################################

    if testing_modules == False:  ## Modules do not currently support uploadToBlob
        ###########################################################################
        # upload_blob_async

        # prepare
        global BLOB_UPLOAD_CONTEXT
        global BLOB_UPLOAD_EVENT
        global BLOB_UPLOAD_CALLBACK_COUNTER

        destination_file_name = ''.join(
            [random.choice(string.ascii_letters) for n in range(12)])
        source = "Blob content for file upload test!"
        size = 34
        BLOB_UPLOAD_EVENT.clear()
        BLOB_UPLOAD_CALLBACK_COUNTER = 0

        # act
        device_client.upload_blob_async(destination_file_name, source, size,
                                        blob_upload_conf_callback,
                                        BLOB_UPLOAD_CONTEXT)
        BLOB_UPLOAD_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert BLOB_UPLOAD_CALLBACK_COUNTER > 0, "Error: blob_upload_conf_callback callback has not been called"
def run_e2e_device_client(iothub_service_client_messaging, iothub_device_method, iothub_device_twin, device_id, device_connection_string, protocol, authMethod):

    ###########################################################################
    # IoTHubClient

    # prepare
    # act
    device_client = IoTHubClient(device_connection_string, protocol)

    # verify
    assert isinstance(device_client, IoTHubClient), 'Error: Invalid type returned!'
    assert device_client != None, "Error: device_client is NULL"
    ###########################################################################

    ###########################################################################
    # set_option

    # prepare
    # act
    device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

    if authMethod == IoTHubRegistryManagerAuthMethod.X509_THUMBPRINT:
        device_client.set_option("x509certificate", IOTHUB_E2E_X509_CERT)
        device_client.set_option("x509privatekey", IOTHUB_E2E_X509_THUMBPRINT)

    if device_client.protocol == IoTHubTransportProvider.HTTP:
        device_client.set_option("timeout", HTTP_TIMEOUT)
        device_client.set_option("MinimumPollingTime", HTTP_MINIMUM_POLLING_TIME)

    if protocol == IoTHubTransportProvider.MQTT_WS or protocol == IoTHubTransportProvider.AMQP_WS:
        device_client.set_option("TrustedCerts", CERTIFICATES)

    # verify
    ###########################################################################

    ###########################################################################
    # set_message_callback
    
    # prepare
    # act
    device_client.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)

    # verify
    ###########################################################################

    if protocol == IoTHubTransportProvider.MQTT or protocol == IoTHubTransportProvider.MQTT_WS:
        ###########################################################################
        # set_device_twin_callback
    
        # prepare
        # act
        device_client.set_device_twin_callback(device_twin_callback, MESSAGING_CONTEXT)

        # verify
        ###########################################################################

        ###########################################################################
        # set_device_method_callback
    
        # prepare
        # act
        device_client.set_device_method_callback(device_method_callback, MESSAGING_CONTEXT)

        # verify
        ###########################################################################

        ###########################################################################
        # update device twin

        # prepare
        global TWIN_CALLBACK_EVENT
        global TWIN_CALLBACK_COUNTER

        TWIN_CALLBACK_EVENT.clear()
        TWIN_CALLBACK_COUNTER = 0

        # act
        sc_update_twin(iothub_device_twin, device_id)
        TWIN_CALLBACK_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert TWIN_CALLBACK_COUNTER == 1, "Error: device_twin_callback callback has not been called"
        ###########################################################################

        ###########################################################################
        # call device method

        # prepare
        global DEVICE_METHOD_EVENT
        global DEVICE_METHOD_CALLBACK_COUNTER

        DEVICE_METHOD_EVENT.clear()
        DEVICE_METHOD_CALLBACK_COUNTER = 0

        method_name = "E2EMethodName"
        payload_json = "{\"method_number\":\"42\"}"

        # act
        sc_invoke_device_method(iothub_device_method, device_id, method_name, payload_json)
        DEVICE_METHOD_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert DEVICE_METHOD_CALLBACK_COUNTER == 1, "Error: device_twin_callback callback has not been called"
        ###########################################################################

    if protocol != IoTHubTransportProvider.AMQP \
       and protocol != IoTHubTransportProvider.AMQP_WS \
       and protocol != IoTHubTransportProvider.HTTP:
        ###########################################################################
        # send_reported_state
    
        # prepare
        global REPORTED_STATE_EVENT
        global REPORTED_STATE_CALLBACK_COUNTER

        reported_state = "{\"newState\":\"standBy\"}"
        REPORTED_STATE_EVENT.clear()
        REPORTED_STATE_CALLBACK_COUNTER = 0

        # act
        device_client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, REPORTED_STATE_CONTEXT)
        REPORTED_STATE_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert REPORTED_STATE_CALLBACK_COUNTER == 1, "Error: send_reported_state_callback has not been called"
        ###########################################################################


    ###########################################################################
    # send_event_async

    # prepare
    global MESSAGING_MESSAGE
    global MESSAGE_RECEIVE_EVENT
    global MESSAGE_RECEIVE_CALLBACK_COUNTER

    MESSAGING_MESSAGE = ''.join([random.choice(string.ascii_letters) for n in range(12)])
    message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))
    MESSAGE_RECEIVE_EVENT.clear()
    MESSAGE_RECEIVE_CALLBACK_COUNTER = 0

    # act
    sc_send_message(iothub_service_client_messaging, device_id, message)
    MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

    # verify
    assert MESSAGE_RECEIVE_CALLBACK_COUNTER == 1, "Error: message has not been received"
    ###########################################################################


    ###########################################################################
    # get_send_status

    # prepare
    status_counter = 0
    status = -1;

    # act
    while status_counter < 1:
        status = device_client.get_send_status()
        print ( "Send status: {0}".format(status) )

        # verify
        assert status == 0, "get_send_status reported status is not IDLE"
        status_counter += 1
    ###########################################################################


    if protocol != IoTHubTransportProvider.AMQP \
       and protocol != IoTHubTransportProvider.AMQP_WS:
        ###########################################################################
        # get_last_message_receive_time

        # prepare
        last_receive_time = -1
        # act
        last_receive_time = device_client.get_last_message_receive_time()

        # verify
        assert last_receive_time > 0, "Error: get_last_message_receive_time failed"
        ###########################################################################


    ###########################################################################
    # upload_blob_async
    
    # prepare
    global BLOB_UPLOAD_CONTEXT
    global BLOB_UPLOAD_EVENT
    global BLOB_UPLOAD_CALLBACK_COUNTER

    destination_file_name = ''.join([random.choice(string.ascii_letters) for n in range(12)])
    source = "Blob content for file upload test!"
    size = 34
    BLOB_UPLOAD_EVENT.clear()
    BLOB_UPLOAD_CALLBACK_COUNTER = 0

    # act
    device_client.upload_blob_async(destination_file_name, source, size, blob_upload_conf_callback, BLOB_UPLOAD_CONTEXT)
    BLOB_UPLOAD_EVENT.wait(CALLBACK_TIMEOUT)

    # verify
    assert BLOB_UPLOAD_CALLBACK_COUNTER == 1, "Error: blob_upload_conf_callback callback has not been called"
    ###########################################################################

    print ("run_e2e_device_client with protocol: {0}, and authMethod: {1} finished".format(protocol, authMethod))
Example #10
0
def run_e2e_messaging(iothub_connection_string):
    global RECEIVE_CALLBACKS
    global MESSAGING_MESSAGE

    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(
            iothub_connection_string)
        new_device = iothub_registry_manager.create_device(
            device_id, primary_key, secondary_key, auth_method)

        protocol = IoTHubTransportProvider.MQTT

        connection_string = get_connection_string(iothub_registry_manager,
                                                  IOTHUB_CONNECTION_STRING,
                                                  device_id, False)

        device_client = IoTHubClient(connection_string, protocol)
        assert isinstance(device_client,
                          IoTHubClient), 'Invalid type returned!'
        assert device_client != None, "device_client is NULL"

        device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client.set_message_callback(receive_message_callback,
                                           MESSAGING_CONTEXT)

        ###########################################################################
        # IoTHubMessaging

        # prepare
        # act
        iothub_messaging = IoTHubMessaging(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_messaging != None, "iothub_messaging is NULL"
        ###########################################################################

        # Wait before open...
        sleep_before_device_action()

        ############################################################################
        # open

        # act
        iothub_messaging.open(open_complete_callback, None)
        ############################################################################

        ############################################################################
        # invoke

        # prepare
        MESSAGING_MESSAGE = ''.join(
            [random.choice(string.ascii_letters) for n in range(12)])
        message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))

        iothub_messaging.send_async(device_id, message, send_complete_callback,
                                    MESSAGING_CONTEXT)
        MESSAGE_RECEIVED_EVENT.wait(MESSAGE_RECEIVE_CALLBACK_TIMEOUT)

        # verify
        assert RECEIVE_CALLBACKS == 1, "message has not been received"
        ############################################################################

        print("")
        retval = 0
    except Exception as e:
        print("")
        print("run_e2e_messaging() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_messaging.close()
        iothub_registry_manager.delete_device(device_id)

    return retval