class HubManager(object): def __init__( self, messageTimeout, protocol, verbose): ''' 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-camera-capture") if verbose: self.client.set_option("logtrace", 1) # enables MQTT logging def send_event_to_output(self, outputQueueName, event, send_context): self.client.send_event_async( outputQueueName, event, send_confirmation_callback, send_context)
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)
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)
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)
class HubManager(object): def __init__( self, messageTimeout, protocol ): ''' Communicate with the Edge Hub :param str connectionString: Edge Hub connection string :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. ''' self.messageTimeout = messageTimeout self.protocol = protocol self.client_protocol = self.protocol self.client = IoTHubModuleClient() self.client.create_from_environment(protocol) self.client.set_option("messageTimeout", self.messageTimeout) def send_event_to_output(self, outputQueueName, event, send_context): self.client.send_event_async( outputQueueName, event, send_confirmation_callback, send_context)
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
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 twin's desired properties are updated. self.client.set_module_twin_callback(module_twin_callback, self) # Set the certifications,Steven Lian,2018 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)
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) # register for TWIN updates self.client.set_module_twin_callback(module_twin_callback, self) def updateReportedTWIN(self): reported_state = {} reported_state["POLLINGfrequency"] = POLLINGfrequency reported_state["POLLINGHost"] = POLLINGHost 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)
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
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))
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 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
class HubManager(object): def __init__(self, protocol, message_timeout): 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) # Sends a message to an output queue, to be routed by IoT Edge hub. def send_event_to_output(self, outputQueueName, event, send_context): self.client.send_event_async( outputQueueName, event, send_confirmation_callback, send_context)
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) # 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)
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) def send_telemetry(self, event, send_context): message = IoTHubMessage(bytearray(event, 'utf8')) self.client.send_event_async('TempAndHumidity', message, send_confirmation_callback, send_context)
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)
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))
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)
class HubManager(object): def __init__(self, messageTimeout, protocol, verbose, videoCapture): # Communicate with the Edge Hub 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", "iotedge-jetson-nano-yolov3") self.videoCapture = videoCapture if verbose: self.client.set_option("logtrace", 1) #enables MQTT logging self.client.set_module_twin_callback(module_twin_callback, self) def send_reported_state(self, reported_state, size, user_context): self.client.send_reported_state(reported_state, size, send_reported_state_callback, user_context) def send_event_to_output(self, outputQueueName, event, send_context): self.client.send_event_async(outputQueueName, event, send_confirmation_callback, send_context) def module_twin_send_reported(self): jsonTemplate = "{\"ConfidenceLevel\": \"%s\",\"VerboseMode\": %d,\"Inference\": %d, \"VideoSource\":\"%s\"}" videoCapture = hubManager.videoCapture strUrl = videoCapture.videoPath jsonData = jsonTemplate % (str( videoCapture.confidenceLevel), videoCapture.verbose, videoCapture.runInference, strUrl) logging.info('device_twin_send_reported()') logging.info(' - payload : {}'.format(json.dumps(jsonData, indent=4))) hubManager.send_reported_state(jsonData, len(jsonData), 1002)
class HubManager(object): def __init__( self, messageTimeout, protocol, verbose): 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-camera-capture") if verbose: self.client.set_option("logtrace", 1) # enables MQTT logging def send_event_to_output(self, outputQueueName, event, send_context): self.client.send_event_async( outputQueueName, event, send_confirmation_callback, send_context)
class Sender(object): def __init__(self, protocol=PROTOCOL): 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 send_event_to_output(self, outputQueueName, event, properties, send_context): if not isinstance(event, IoTHubMessage): event = IoTHubMessage(bytearray(event, 'utf8')) if len(properties) > 0: prop_map = event.properties() for key in properties: prop_map.add_or_update(key, properties[key]) self.client.send_event_async(outputQueueName, event, send_confirmation_callback, send_context)
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)
class HubManager(object): def __init__(self, protocol): 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) # set to increase logging level # self.client.set_option("logtrace", 1) # Sends a message to the queue with outputQueueName, "temperatureOutput" in the case of the sample. def send_event_to_output(self, outputQueueName, event, properties, send_context): if not isinstance(event, IoTHubMessage): event = IoTHubMessage(bytearray(event, 'utf8')) if len(properties) > 0: prop_map = event.properties() for key in properties: prop_map.add_or_update(key, properties[key]) self.client.send_event_async(outputQueueName, event, send_confirmation_callback, send_context)
class HubManager(object): def __init__(self): 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) # some embedded platforms need certificate information # 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) 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)
class HubManager(object): def __init__(self, messageTimeout, protocol, verbose): # Communicate with the Edge Hub 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-yolo-capture") if verbose: self.client.set_option("logtrace", 1) #enables MQTT logging self.client.set_module_twin_callback(device_twin_callback, None) def send_reported_state(self, reported_state, size, user_context): self.client.send_reported_state(reported_state, size, send_reported_state_callback, user_context) def send_event_to_output(self, outputQueueName, event, send_context): self.client.send_event_async(outputQueueName, event, send_confirmation_callback, send_context)
class Sender(object): def __init__(self, protocol=PROTOCOL): 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) def send_event_to_output(self, output_queue_name, event, properties, send_context): if not isinstance(event, IoTHubMessage): event = IoTHubMessage(bytearray(event, 'utf8')) if len(properties) > 0: prop_map = event.properties() for key in properties: prop_map.add_or_update(key, properties[key]) self.client.send_event_async(output_queue_name, event, send_confirmation_callback, send_context)
class HubManager(object): def __init__(self, protocol=IoTHubTransportProvider.MQTT): # init Instance Attributes self.MESSAGE_DELAY = 0 # init IoTHubModuleClient 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) # send a message to the next stage in the process. def send_async(self, outputQueueName, event, send_context): self.client.send_event_async(outputQueueName, event, send_confirmation_callback, send_context) #update modules twin reported properties def send_reported_state(self, reported_state, size, user_context): self.client.send_reported_state(reported_state, size, send_reported_state_callback, user_context)
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
class IotHubManager(object): TIMER_COUNT = 2 def __init__(self, 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) self.client.set_module_twin_callback(self.module_twin_callback, self) self.setRestartCamera = False cam_type = "video_file" cam_source = "/sample_video/video.mp4" self.model_dst_folder = "./default_model" self.model_url = None self.ret_flag = None def send_message_to_output(self, message, output_name, last_sent_time=time.time()): try: #delaying message send to IotHub as we have 400+ msg per sec if we send all up we will exhaust IotHub limit #if(time.time() - last_sent_time <= (60/msg_per_minute)): # return last_sent_time message = IoTHubMessage(message) self.client.send_event_async(output_name, message, self.__send_confirmation_callback, 0) print('message sent') last_sent_time = time.time() return last_sent_time # logging.info("finished sending message...") except Exception as ex: print("Exception in send_message_to_output: %s" % ex) pass # sends a messager to the "ToUpstream" queue to be sent to hub def send_message_to_upstream(self, message, last_sent_time=time.time()): try: #delaying message send to IotHub as we have 400+ msg per sec if we send all up we will exhaust IotHub limit if (time.time() - last_sent_time <= (60 / msg_per_minute)): return last_sent_time message = IoTHubMessage(message) self.client.send_event_async(TO_UPSTREAM_MESSAGE_QUEUE_NAME, message, self.__send_confirmation_callback, 0) last_sent_time = time.time() return last_sent_time # 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 send_reported_state_callback(self, status_code, user_context): print("") print("Confirmation for reported state called with:") print(" status_code: %d" % status_code) def send_property(self, prop): try: if self.client.protocol == IoTHubTransportProvider.MQTT: self.client.send_reported_state( prop, len(prop), self.send_reported_state_callback, prop) except Exception as ex: print("Exception in send_property: %s" % ex) def module_twin_callback(self, update_state, payload, user_context): global inference_files_zip_url global msg_per_minute global object_of_interest print("") print("Twin callback called with:") print(" updateStatus: %s" % update_state) print(" payload: %s" % payload) data = json.loads(payload) self.setRestartCamera = False if "desired" in data and "inference_files_zip_url" in data["desired"]: self.model_dst_folder = "default_model" inference_files_zip_url = data["desired"][ "inference_files_zip_url"] if inference_files_zip_url: print( "\n Setting value to %s from :: data[\"desired\"][\"all_inference_files_zip\"]" % inference_files_zip_url) self.setRestartCamera = get_file_zip(inference_files_zip_url, self.model_dst_folder) self.model_url = inference_files_zip_url else: print(inference_files_zip_url) self.model_url = None if "inference_files_zip_url" in data: self.model_dst_folder = "default_model" inference_files_zip_url = data["inference_files_zip_url"] if inference_files_zip_url: print( "\n Setting value to %s from :: data[\"all_inference_files_zip\"]" % inference_files_zip_url) self.ret_flag = get_file_zip(inference_files_zip_url, self.model_dst_folder) #self.setRestartCamera = True self.model_url = inference_files_zip_url else: print(inference_files_zip_url) self.model_url = None if "desired" in data and "cam_type" in data["desired"]: cam_type = data["desired"]["cam_type"] self.cam_type = str(cam_type) print("Setting value to %s from :: data[desired][cam_type]" % cam_type) self.ret_flag = True elif "cam_type" in data: cam_type = data["cam_type"] self.cam_type = str(cam_type) print("Setting value to %s from :: data[cam_type]" % cam_type) self.ret_flag = True if "desired" in data and "cam_source" in data["desired"]: cam_source = data["desired"]["cam_source"] self.cam_source = str(cam_source) print("Setting value to %s from :: data[desired][cam_source]" % cam_source) self.ret_flag = True elif "cam_source" in data: cam_source = data["cam_source"] self.cam_source = str(cam_source) print("Setting value to %s from :: data[cam_source]" % cam_source) self.ret_flag = True if self.cam_source: if self.cam_type == "video_file": print("self.cam_source %s file" % self.cam_source) dst_folder = "sample_video" print( "\n Download and unzip video file to sample dir from %s" % self.cam_source) self.ret_flag = get_file_zip(self.cam_source, dst_folder) #ToDo readfilename and add to dst_folder self.cam_source = "/sample_video/video.mp4" #self.setRestartCamera = True else: print(self.cam_source) 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: object_of_interest = data["object_of_interest"] print("Setting value to %s from :: data[\"object_of_interest\"]" % object_of_interest) if "desired" in data and "msg_per_minute" in data["desired"]: msg_per_minute = data["desired"]["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"] print("Setting value to %s from :: data[\"msg_per_minute\"]" % msg_per_minute) if self.ret_flag: try: print("setting restart inferense to True") self.setRestartCamera = True logger.info("Restarting inferencing") except Exception as e: logger.info("Got an issue during cam ON off after twin update") logger.exception(e) raise
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