示例#1
0
def iothub_client_prov_hsm_sample_run():
    client = IoTHubClient(IOTHUB_URI, DEVICE_ID, SECURITY_TYPE, PROTOCOL)

    print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT )

    for message_counter in range(0, MESSAGE_COUNT):
        message = create_message(message_counter)

        client.send_event_async(message, send_confirmation_callback, message_counter)
        print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % message_counter )

    # Wait for Commands or exit
    print ( "IoTHubClient waiting for commands, press Ctrl-C to exit" )

    status_counter = 0
    while status_counter <= MESSAGE_COUNT:
        status = client.get_send_status()
        print ( "Send status: %s" % status )
        time.sleep(10)
        status_counter += 1
def run_e2e_device_client(iothub_service_client_messaging, iothub_device_method, iothub_device_twin, device_id, device_connection_string, protocol, authMethod):
    global IOTHUB_E2E_X509_CERT
    global IOTHUB_E2E_X509_THUMBPRINT
    global IOTHUB_E2E_X509_PRIVATE_KEY
    global CERTIFICATES
    global MESSAGING_CONTEXT

    ###########################################################################
    # 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_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
    ###########################################################################

    ###########################################################################
    # 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.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 > 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)
        DEVICE_METHOD_EVENT.wait(CALLBACK_TIMEOUT)

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

    if protocol == IoTHubTransportProvider.AMQP \
       or protocol == IoTHubTransportProvider.AMQP_WS \
       or protocol == IoTHubTransportProvider.MQTT \
       or protocol == IoTHubTransportProvider.MQTT_WS:
        ###########################################################################
        # 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)

    ###########################################################################
    # 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 > 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"
        ###########################################################################


    ###########################################################################
    # 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))
示例#4
0
class IotHub:
    def __init__(self, hardware, queue):
        self.method_callbacks = 0
        self.hardware = hardware
        self.queue = queue
        self._init_client()

    def _init_client(self):
        # Connect to iot-hub
        self.client = IoTHubClient(IOTHUB_CONNECTION,
                                   IoTHubTransportProvider.AMQP)
        # Settings
        self.client.set_option("messageTimeout", IOTHUB_MESSAGE_TIMEOUT)
        self.client.set_device_method_callback(self.device_method_callback, 0)

    def send_confirmation_callback(self, message, result, user_context):
        print(
            "Confirmation received for message with result {}".format(result))
        print("    message_id: %s" % message.message_id)
        print("    correlation_id: %s" % message.correlation_id)

    def send_message(self, payload):
        message_id = uuid4()
        message = IoTHubMessage(bytearray(payload, 'utf8'))
        self.client.send_event_async(message, self.send_confirmation_callback,
                                     message_id)
        print("Message {} accepted for transmission to IoT Hub.".format(
            message_id))
        return self.client.get_send_status()

    # Gets invoked by message from the cloud
    def device_method_callback(self, method_name, payload, user_context):
        print(
            "Method callback called with: methodName = {}, payload = {}, context = {}"
            .format(method_name, payload, user_context))

        msg = json.loads(payload)

        try:
            if method_name == 'list':
                response = self.hardware.list_methods()
            elif method_name == 'cancel':
                self.queue.cancel()
                response = "ok"
            else:
                method_payload = msg['payload'] if 'payload' in msg else {}
                self.queue.append("invoke_method", {
                    "method": method_name,
                    "payload": method_payload,
                })
                response = "ok"

            status = 200

        except NotImplementedError:
            response = 'Method not defined'
            status = 404

        except ValueError as inst:
            response = inst.args
            status = 400

        except queue.Full:
            response = "Too many items in queue"
            status = 503

        except Exception as inst:
            response = inst.args
            status = 500

        return_value = DeviceMethodReturnValue()
        return_value.status = status
        return_value.response = json_dumps({'Response': response})

        return return_value