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): 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): 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, 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 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) # 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) # 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 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 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, 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 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)
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=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)
def iothub_client_init(self): protocol = IoTHubTransportProvider.MQTT client = IoTHubModuleClient() client.create_from_environment(protocol) if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS: client.set_module_twin_callback(device_twin_callback, self.TWIN_CONTEXT) return client
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) # 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)
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, protocol=IoTHubTransportProvider.MQTT): print("\nPython %s\n" % sys.version) print("IoT Hub Client for Python") print("Starting the IoT Hub Python sample using protocol %s..." % 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)
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.")
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): self.client_protocol = protocol self.client = IoTHubModuleClient() self.client.create_from_environment(protocol) # set to increase logging level # self.client.set_option("logtrace", 1) # Invokes a method on a module running on same device. def invoke_module(self): # Edge indicates its deviceId by setting the environment variable IOTEDGE_DEVICEID in its container. deviceId = os.environ['IOTEDGE_DEVICEID'] self.client.invoke_method_async(deviceId, TARGET_MODULE, TARGET_METHOD_NAME, TARGET_METHOD_PAYLOAD, TIMEOUT, invoke_method_callback, RECEIVE_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 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 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")
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 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)