Пример #1
0
class IotHubManager(object):
    def __init__(self, protocol=IOT_HUB_PROTOCOL):
        print("Creating IoT Hub manager")
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)

        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)

    def subscribe_to_events(self):
        print("Subscribing to method calls")
        self.client.set_module_method_callback(method_callback, 0)

        print("Subscribing to module twin updates")
        self.client.set_module_twin_callback(module_twin_callback,
                                             MODULE_TWIN_UPDATE_CONTEXT)

    # sends a messager to the "ToUpstream" queue to be sent to hub
    def send_message_to_upstream(self, message):
        try:
            message = IoTHubMessage(message)
            self.client.send_event_async(TO_UPSTREAM_MESSAGE_QUEUE_NAME,
                                         message, send_confirmation_callback,
                                         0)
            # logging.info("finished sending message...")
        except Exception as ex:
            print("Exception in send_message_to_upstream: %s" % ex)
            pass
Пример #2
0
class HubManager(object):
    def __init__(self, protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)

        # sets the callback when a message arrives on "input1" queue. Messages sent to other inputs or to the default will be silently discarded.
        self.client.set_message_callback("input1", blink_callback, self)
        self.client.set_module_method_callback(module_method_callback, None)
Пример #3
0
class HubManager(object):
    def __init__(self, protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)

        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        self.client.set_module_twin_callback(module_twin_callback, self)
        self.client.set_module_method_callback(method_callback, 0)
class HubManager(object):
    def __init__(self):
        # Defines settings of the IoT SDK
        protocol = IoTHubTransportProvider.MQTT
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)
        self.client.set_option("logtrace", 1)  #enables MQTT logging
        self.client.set_option("messageTimeout", 10000)

        # sets the callback when a message arrives on "input1" queue.  Messages sent to
        # other inputs or to the default will be silently discarded.
        self.client.set_message_callback("input1", receive_message_callback,
                                         self)
        print("Module is now waiting for messages in the input1 queue.")
        self.client.set_module_method_callback(method_callback, self)
Пример #5
0
class HubManager(object):
    def __init__(self, protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)
        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)

        # sets the callback when a message arrives on "input1" queue.  Messages sent to
        # other inputs or to the default will be silently discarded.
        self.client.set_message_callback("input1", receive_message_callback,
                                         self)
        print('subscribing to method calls')
        # Register the callback with the client
        self.client.set_module_method_callback(method_callback, 0)

    # Forwards the message received onto the next stage in the process.
    def forward_event_to_output(self, outputQueueName, event, send_context):
        self.client.send_event_async(outputQueueName, event,
                                     send_confirmation_callback, send_context)
Пример #6
0
class HubManager(object):
    def __init__(self, protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)

        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)

        # sets the callback when a message arrives on "input1" queue.  Messages sent to
        # other inputs or to the default will be silently discarded.
        self.client.set_message_callback("input1", receive_message_callback,
                                         self)

        # items added to show the complete functionality
        self.client.set_module_twin_callback(module_twin_callback, self)
        self.client.set_module_method_callback(module_method_callback, self)

        # updating the Module TWIN with a started time
        reported_state = "{\"started\":\"" + str(
            datetime.datetime.now()) + "\"}"
        self.client.send_reported_state(reported_state, len(reported_state),
                                        send_reported_state_callback, self)

    def updateReportedTWIN(self):
        reported_state = {}
        reported_state["RESTTargetURL"] = RESTTargetURL
        reported_state["RESTTargetLocation"] = RESTTargetLocation
        reported_state["POLINGInterval"] = POLINGInterval
        reported_statestr = json.dumps(reported_state)
        self.client.send_reported_state(reported_statestr,
                                        len(reported_statestr),
                                        send_reported_state_callback, self)

    # Forwards the message received onto the next stage in the process.
    def forward_event_to_output(self, outputQueueName, event, send_context):
        self.client.send_event_async(outputQueueName, event,
                                     send_confirmation_callback, send_context)
Пример #7
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"
Пример #8
0
class IotHubManager(object):
    def __init__(self, protocol, camera_client: CameraClient, properties: Properties):
        print("Creating IoT Hub manager")
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)
        self.camera_client = camera_client
        self.properties = properties

        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)

    def subscribe_to_events(self):
        print("Subscribing to method calls")
        self.client.set_module_method_callback(self.__method_callback_handler, 0)

        print("Subscribing to module twin updates")
        self.client.set_module_twin_callback(
            self.__module_twin_callback, MODULE_TWIN_UPDATE_CONTEXT)

    # sends a messager to the "ToUpstream" queue to be sent to hub
    def send_message_to_upstream(self, message):
        try:
            message = IoTHubMessage(message)
            self.client.send_event_async(
                TO_UPSTREAM_MESSAGE_QUEUE_NAME,
                message,
                self.__send_confirmation_callback,
                0)
            # logging.info("finished sending message...")
        except Exception as ex:
            print("Exception in send_message_to_upstream: %s" % ex)
            pass

    # Callback received when the message that we're forwarding is processed.
    def __send_confirmation_callback(self, message, result, user_context):
        global send_callbacks
        print("Confirmation[%d] received for message with result = %s" % (
            user_context, result))
        map_properties = message.properties()
        key_value_pair = map_properties.get_internals()
        print("\tProperties: %s" % key_value_pair)
        send_callbacks += 1
        print("\tTotal calls confirmed: %d" % send_callbacks)

    def __method_callback_handler(self, method_name, payload, user_context):
        """
        Private method to handle the callbacks from the IoT Hub by calling the
        callback matching `method_name`
        """
        retval = {
            TURN_CAMERA_ON_METHOD_NAME:
                lambda payload, user_context: self.__turn_camera_on_callback(
                    payload, user_context),
            TURN_CAMERA_OFF_METHOD_NAME:
                lambda payload, user_context: self.__turn_camera_off_callback(
                    payload, user_context)
        }[method_name](payload, user_context)

        return retval

    def __turn_camera_on_callback(self, payload, user_context):
        retval = DeviceMethodReturnValue()
        try:
            self.camera_client.set_preview_state(SETTING_ON)
            # TODO: restart analytics
            retval.status = 200
            retval.response = "{\"Response\":\"Successfully started camera\"}"
            return retval
        except Exception:
            retval.status = 500
            retval.response = "{\"Response\":\"Failed to start camera\"}"
            return retval

    def __turn_camera_off_callback(self, payload, user_context):
        retval = DeviceMethodReturnValue()
        try:
            self.camera_client.set_overlay_state(SETTING_OFF)
            self.camera_client.set_analytics_state(SETTING_OFF)
            self.camera_client.set_preview_state(SETTING_OFF)
            retval.status = 200
            retval.response = "{\"Response\":\"Successfully stopped camera\"}"
            return retval
        except Exception:
            retval.status = 500
            retval.response = "{\"Response\":\"Failed to stop camera\"}"
            return retval

    def __module_twin_callback(self, update_state, payload, user_context):
        print("Received twin callback")
        self.properties.handle_twin_update(payload)
        self.__update_model_and_config()

    def __update_model_and_config(self):
        model_props = self.properties.model_properties
        camera_props = self.properties.camera_properties
        if not self.camera_client:
            print("Handle updates aborting")
            print("\tcamera_client is %s" % self.camera_client)
            return
        try:
            is_model_changed = model_props.update_inference_model()
            camera_props.configure_camera_client(self.camera_client, is_model_changed)
            self.properties.report_properties_to_hub(self)
        except Exception as ex:
            log_unknown_exception(
                "Error raised while handling update callback: %s" % ex,
                self)
            raise ex