class HubManager(object):
    def __init__(self):
        global TWIN_CONTEXT, application_name
        # 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_twin_callback(module_twin_callback,
                                             TWIN_CONTEXT)
        print("Module is now waiting for device twin updating.")
        if application_name is not None:
            reported = {'application': application_name}
            self.client.patch_twin_reported_properties(reported)

    def send_event_to_output(self, outputQueueName, event, send_context):
        self.client.send_event_async(outputQueueName, event,
                                     send_confirmation_callback, send_context)
Ejemplo n.º 2
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)

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

    def SendTemperatureData(self, msg):
        print("Sending temperature message...")
        message = IoTHubMessage(msg)
        self.client.send_event_async("output1", message,
                                     send_confirmation_callback, 0)
        print("Successfully finished sending temperature message...")
class IoTMessaging:
    timeout = 10000

    def __init__(self,
                 input_queue=None,
                 output_queue=None,
                 receive_msg_callback=None):

        self.client = IoTHubModuleClient()
        self.client.create_from_environment(IoTHubTransportProvider.MQTT)

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

        self.input_queue = input_queue
        self.output_queue = output_queue

        if self.input_queue is not None:
            self.client.set_message_callback(self.input_queue, receive_message,
                                             receive_msg_callback)

    def send_event(self, event, send_context, to_output_queue=True):

        self.client.send_event_async(self.output_queue, event,
                                     send_confirmation_callback, send_context)

    def send_to_output(self, event, output_name, send_context):
        self.client.send_event_async(output_name, event,
                                     send_confirmation_callback, send_context)
Ejemplo n.º 4
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)
        #self.client.set_module_twin_callback(self.module_twin_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)

    def send_msg_to_cloud(self, msg, last_sent_time=time.time()):
        global delay_to_send_to_cloud
        try:
            if (time.time() - last_sent_time <= delay_to_send_to_cloud):
                return last_sent_time
            message = IoTHubMessage(msg)
            self.client.send_event_async("output1", message,
                                         send_confirmation_callback, 0)
            last_sent_time = time.time()
            return last_sent_time
        except Exception:
            print("Exception in SendMsgToCloud")
            traceback.print_exc()
            last_sent_time = time.time()
            return last_sent_time
Ejemplo n.º 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)

        # Sets the callback when a module twin's desired properties are updated.
        self.client.set_module_twin_callback(module_twin_callback, self)

        # Sets callback for module twin reported properties.
        global reported_state
        #self.client.send_reported_state(self.client, reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)

    # 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)
Ejemplo n.º 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)

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

    def SendData(self, msg):
        global MESSAGE_COUNT
        record_time_local = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')
        print("\nsending message %d at %s" %
              (MESSAGE_COUNT, record_time_local))
        print(msg)
        message = IoTHubMessage(msg)
        message.message_id = "message_%d" % MESSAGE_COUNT
        message.correlation_id = "correlation_%d" % MESSAGE_COUNT
        self.client.send_event_async("output1", message,
                                     send_confirmation_callback, 0)
        print("finished sending message %d\n" % (MESSAGE_COUNT))
Ejemplo n.º 7
0
class HubManager(object):

    def __init__(
            self,
            messageTimeout,
            protocol,
            verbose=False):
        '''
        Communicate with the Edge Hub

        :param int messageTimeout: the maximum time in milliseconds until a message times out. The timeout period starts at IoTHubClient.send_event_async. By default, messages do not expire.
        :param IoTHubTransportProvider protocol: Choose HTTP, AMQP or MQTT as transport protocol.  Currently only MQTT is supported.
        :param bool verbose: set to true to get detailed logs on messages
        '''
        self.messageTimeout = messageTimeout
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)
        self.client.set_option("messageTimeout", self.messageTimeout)
        self.client.set_option("product_info","edge-engine-inference")
        if verbose:
            self.client.set_option("logtrace", 1)
        self.client.set_message_callback("output", receive_message,self)

    def send_event_to_output(self, outputQueueName, event, send_context):
        self.client.send_event_async(outputQueueName, event, send_confirmation_callback, send_context)
Ejemplo n.º 8
0
class HubManager(object):

    TIMER_COUNT = 2

    TWIN_CONTEXT = 0
    SEND_REPORTED_STATE_CONTEXT = 0

    def __init__(self, protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)
        #self.iotedgemodule = iotedgemodules()

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

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

    def iothub_client_sample_run(self, message):
        try:
            #client = self.iothub_client_init()
            if self.client.protocol == IoTHubTransportProvider.MQTT:
                print("Sending data as reported property...")
                reported_state = "{\"rtsp_addr\":\"" + message + "\"}"
                self.client.send_reported_state(
                    reported_state, len(reported_state),
                    send_reported_state_callback,
                    self.SEND_REPORTED_STATE_CONTEXT)
                status_counter = 0
                while status_counter <= self.TIMER_COUNT:
                    status = self.client.get_send_status()
                    time.sleep(2)
                    status_counter += 1

        except IoTHubError as iothub_error:
            print("Unexpected error %s from IoTHub" % iothub_error)
            return
        except KeyboardInterrupt:
            print("IoTHubClient sample stopped")

    def SendMsgToCloud(self, msg):
        try:
            #print("sending message...")
            message = IoTHubMessage(msg)
            self.client.send_event_async("output1", message,
                                         send_confirmation_callback, 0)
            #print("finished sending message...")
        except Exception:
            print("Exception in SendMsgToCloud")
            pass
Ejemplo n.º 9
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)
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)
Ejemplo n.º 11
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.")
Ejemplo n.º 12
0
class HubManager(object):
    def __init__(self, messageTimeout, protocol, verbose=False):

        self.messageTimeout = messageTimeout
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)
        self.client.set_option("messageTimeout", self.messageTimeout)
        self.client.set_option("product_info", "edge-engine-inference")
        if verbose:
            self.client.set_option("logtrace", 1)
        self.client.set_message_callback("output", receive_message, self)

    def send_event_to_output(self, outputQueueName, event, send_context):
        self.client.send_event_async(outputQueueName, event,
                                     send_confirmation_callback, send_context)
Ejemplo n.º 13
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_MILLISECONDS)

        self.client.set_message_callback(INPUT_ENDPOINT_NAME,
                                         avro_writer_message_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)
Ejemplo n.º 14
0
class HubManager(object):

    def __init__(
            self,
            protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
    
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)
        self.device_id= os.getenv("IOTEDGE_DEVICEID", "err")
        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        # input for sensor messages
        self.client.set_message_callback("sensor", receive_message_callback, self)
        self._received_measurements = {}

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

    # This method is responsible for everything to do with message contents
    def handle_measurement(self, measurement):
        message_uuid = measurement["message_uuid"]
        device_id = measurement["device_id"]
        if device_id not in self._received_measurements:
            self._received_measurements[device_id] = []
        self._received_measurements[device_id] += [{
            "temperature" : measurement["temperature"],
            "timestamp" : measurement["timestamp"]
            }]
        threshold = 30.0
        if measurement["temperature"] > threshold:
            other_device_ids = [k for k in self._received_measurements if k != device_id]
            other_measurements = [ms[-1] for did in other_device_ids for ms in self._received_measurements[did]]
            if all([m["temperature"] > threshold for m in other_measurements]):
                warn_message_uuid = str(uuid.uuid1())
                contents = {
                    "message_uuid": str(warn_message_uuid),
                    "device_id": self.device_id,
                    "timestamp": datetime.datetime.utcnow().isoformat(),
                    "message_test": "Temperature is too high!!!"
                }
                print("Sending warn message " + str(contents))
                msg = IoTHubMessage(json.dumps(contents))
                self.forward_event_to_output("sensor", msg, str(warn_message_uuid))
Ejemplo n.º 15
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 "postprocessinginput" queue.  Messages sent to
        # other inputs or to the default will be silently discarded.
        self.client.set_message_callback("postprocessinginput",
                                         receive_message_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)
Ejemplo n.º 16
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 module twin's desired properties are updated.
        self.client.set_module_twin_callback(module_twin_callback, self)

        # sets the callback when a message arrives on "ScheduleOutput" queue.
        self.client.set_message_callback("ScheduleInput",
                                         receive_schedule_message_callback,
                                         self)

        # sets the callback when a message arrives on "SensorsOutputInput" queue.
        #self.client.set_message_callback("SensorsInput", receive_sensor_notification_callback, self)
        print("Initialization done.\n")
Ejemplo n.º 17
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.set_certificates()

        # 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)
        # sets the callback when a twin's desired properties are updated.
        self.client.set_module_twin_callback(module_twin_callback, self)

    def set_certificates(self):
        isWindows = sys.platform.lower() in ['windows', 'win32']
        if not isWindows:
            CERT_FILE = os.environ['EdgeModuleCACertificateFile']
            print("Adding TrustedCerts from: {0}".format(CERT_FILE))

            # this brings in x509 privateKey and certificate
            file = open(CERT_FILE)
            try:
                self.client.set_option("TrustedCerts", file.read())
                print("set_option TrustedCerts successful")
            except IoTHubClientError as iothub_client_error:
                print("set_option TrustedCerts failed (%s)" %
                      iothub_client_error)

            file.close()

    # 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)
Ejemplo n.º 18
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)
Ejemplo n.º 19
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"
Ejemplo n.º 20
0
class HubManager(object):

    TIMER_COUNT = 2

    TWIN_CONTEXT = 0
    SEND_REPORTED_STATE_CONTEXT = 0

    def __init__(self, camera_handle, protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubModuleClient()
        self.client.create_from_environment(protocol)
        self.iot_camera_handle = camera_handle
        # 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)
        self.client.set_module_twin_callback(self.module_twin_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)

    def iothub_client_sample_run(self, message):
        try:

            if self.client.protocol == IoTHubTransportProvider.MQTT:
                print("Sending data as reported property...")
                reported_state = "{\"rtsp_addr\":\"" + message + "\"}"
                self.client.send_reported_state(
                    reported_state, len(reported_state),
                    send_reported_state_callback,
                    self.SEND_REPORTED_STATE_CONTEXT)
                status_counter = 0
                while status_counter <= self.TIMER_COUNT:
                    status = self.client.get_send_status()
                    time.sleep(2)
                    status_counter += 1

        except IoTHubError as iothub_error:
            print("Unexpected error %s from IoTHub" % iothub_error)
            return
        except KeyboardInterrupt:
            print("IoTHubClient sample stopped")

    def SendMsgToCloud(self, msg):
        try:
            #logging.info("sending message...")
            message = IoTHubMessage(msg)
            self.client.send_event_async("output1", message,
                                         send_confirmation_callback, 0)
            logging.info("finished sending message...")
        except Exception:
            print("Exception in SendMsgToCloud")
            pass

    def module_twin_callback(self, update_state, payload, user_context):
        global inference_files_zip_url
        global model_url
        global label_url
        global config_url
        global msg_per_minute
        global wait_for_minutes
        global object_of_interest
        print("")
        print("Twin callback called with:")
        print("    updateStatus: %s" % update_state)
        print("    payload: %s" % payload)
        data = json.loads(payload)
        setRestartCamera = False

        if "desired" in data and "inference_files_zip_url" in data["desired"]:
            dst_folder = "twin_provided_model"
            inference_files_zip_url = data["desired"][
                "inference_files_zip_url"]
            if inference_files_zip_url:
                print(
                    "Setting value to %s from ::  data[\"desired\"][\"all_inference_files_zip\"]"
                    % inference_files_zip_url)
                setRestartCamera = get_file_zip(inference_files_zip_url,
                                                dst_folder)
            else:
                print(inference_files_zip_url)
        if "inference_files_zip_url" in data:
            dst_folder = "twin_provided_model"
            inference_files_zip_url = data["inference_files_zip_url"]
            if inference_files_zip_url:
                print(
                    "Setting value to %s from ::  data[\"all_inference_files_zip\"]"
                    % inference_files_zip_url)
                setRestartCamera = get_file_zip(inference_files_zip_url,
                                                dst_folder)
            else:
                print(inference_files_zip_url)

        if "desired" in data and "msg_per_minute" in data["desired"]:

            msg_per_minute = data["desired"]["msg_per_minute"]
            msg_per_minute = 60 / int(msg_per_minute)
            print("Setting value to %s from ::  data[\"msg_per_minute\"]" %
                  msg_per_minute)

        if "msg_per_minute" in data:
            msg_per_minute = data["msg_per_minute"]
            wait_for_minutes = int(60 / int(msg_per_minute))

            print("Setting value to %s from ::  data[\"msg_per_minute\"]" %
                  msg_per_minute)

        if "desired" in data and "object_of_interest" in data["desired"]:
            object_of_interest = data["desired"]["object_of_interest"]
            print("Setting value to %s from ::  data[\"object_of_interest\"]" %
                  object_of_interest)

        if "object_of_interest" in data:
            msg_per_minute = data["object_of_interest"]
            print("Setting value to %s from ::  data[\"object_of_interest\"]" %
                  object_of_interest)

        if setRestartCamera:
            #
            try:
                logger.info("Restarting VAM to apply new model config")
                self.restartInference(self.iot_camera_handle)

            except Exception as e:
                logger.info("Got an issue during vam ON off after twin update")
                logger.exception(e)
                raise

    def restartInference(self, camera_client):
        try:

            logger.debug("Restarting VAM to apply new model config")
            camera_client.set_overlay_state("off")
            if (camera_client.vam_running):
                camera_client.set_analytics_state("off")
            #time.sleep(1)
            camera_client.set_analytics_state("on")
            camera_client.set_overlay_state("on")
            #self.print_and_send_results()

        except Exception as e:
            logger.debug(
                "System got an exception during vam ON off after twin model update!!! "
            )
            logger.exception(e)
            #self.restart_cam(camera_client)
            raise