async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) print("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() IoTHubModuleClient.create_from_edge_environment() # conn_str = "HostName=AndrewPiProject.azure-devices.net;DeviceId=RPi4;SharedAccessKey=FoUWxLuoWLZxKWN/ytg6qMCk0dWHSiWaysIart2CD/s=" # module_client = IoTHubModuleClient.create_from_connection_string(conn_str) # connect the client. await module_client.connect() # Connect Sensor while True: try: sensor = W1ThermSensor() print("Sensor active") break except: pass data = {} data['temperature'] = 0 tempOld = 0 temp = "" # define behavior for receiving an input message on input1 while True: try: data['temperature'] = sensor.get_temperature() * 9 / 5 + 32 json_body = json.dumps(data) temp = json.loads(json_body) print(temp) except: time.sleep(.5) if temp != "" and tempOld != temp['temperature']: print(temp['temperature']) print("forwarding message to output1 at {0}".format( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) tempOld = temp['temperature'] await module_client.send_message_to_output( json_body, "output1") except Exception as e: print("Unexpected error %s " % e) raise
async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) print("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() IoTHubModuleClient.create_from_edge_environment() # conn_str = "HostName=AndrewPiProject.azure-devices.net;DeviceId=RPi4;SharedAccessKey=FoUWxLuoWLZxKWN/ytg6qMCk0dWHSiWaysIart2CD/s=" # module_client = IoTHubModuleClient.create_from_connection_string(conn_str) GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT, initial=GPIO.HIGH) time.sleep(1) GPIO.setup(21, GPIO.OUT, initial=GPIO.LOW) time.sleep(1) GPIO.setup(21, GPIO.OUT, initial=GPIO.HIGH) # connect the client. print("Trying to connect") await module_client.connect() # define behavior for receiving an input message on input1 input_message = 0 while True: print('Awaiting message') # blocking call input_message = await module_client.receive_message_on_input( "input1") tempData = json.loads(input_message.data) temperature = tempData['temperature'] print("Message received at {0}".format( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) print(temperature) if temperature > 79: GPIO.output(21, GPIO.HIGH) else: GPIO.output(21, GPIO.LOW) time.sleep(1) except Exception as e: print("Unexpected error %s " % e) raise
async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) print("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # define behavior for receiving an input message on input1 async def receive_data(module_client): while True: try: input_message = await module_client.receive_message_on_input( "data_input") # blocking call message = input_message.data size = len(message) message_text = message.decode('utf-8') print(" Data: <<<%s>>> & Size=%d" % (message_text, size)) custom_properties = input_message.custom_properties print(" Properties: %s" % custom_properties) await module_client.send_message_to_output( input_message, "data_output") except Exception as ex: print("Unexpected error in stram analytics module: %s" % ex) def stdin_listener(): while True: try: selection = input("") if selection == "Q" or selection == "q": print("Quitting...") break except: time.sleep(30) # Schedule task for C2D Listener listeners = asyncio.gather(receive_data(module_client)) loop = asyncio.get_event_loop() user_finished = loop.run_in_executor(None, stdin_listener) await user_finished # Cancel listening listeners.cancel() # Finally, disconnect await module_client.disconnect() except Exception as e: print("Unexpected error %s " % e) raise
async def Startup(): print("Starting now") client = IoTHubModuleClient.create_from_edge_environment() print("Created client") await client.connect() print("Connected") return client
async def main(): # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # define behavior for receiving a twin patch async def twin_patch_listener(device_client): while True: patch = await device_client.receive_twin_desired_properties_patch( ) # blocking call print("the data in the desired properties patch was: {}".format( patch)) # define behavior for halting the application def stdin_listener(): while True: selection = input("Press Q to quit\n") if selection == "Q" or selection == "q": print("Quitting...") break # Schedule task for twin patch asyncio.create_task(twin_patch_listener(module_client)) # Run the stdin listener in the event loop loop = asyncio.get_running_loop() user_finished = loop.run_in_executor(None, stdin_listener) # Wait for user to indicate they are done listening for messages await user_finished # Finally, disconnect await module_client.disconnect()
async def main( videoPath, imageProcessingEndpoint="", imageProcessingParams="", showVideo=False, verbose=False, resizeWidth=0, resizeHeight=0, ): ''' Capture a camera feed, send it to processing and forward outputs to EdgeHub :param int videoPath: camera device path such as /dev/video0 or a test video file such as /TestAssets/myvideo.avi. Mandatory. :param str imageProcessingEndpoint: service endpoint to send the frames to for processing. Example: "http://face-detect-service:8080". Leave empty when no external processing is needed (Default). Optional. :param str imageProcessingParams: query parameters to send to the processing service. Example: "'returnLabels': 'true'". Empty by default. Optional. :param bool showVideo: show the video in a windows. False by default. Optional. :param bool verbose: show detailed logs and perf timers. False by default. Optional. :param int resizeWidth: resize frame width before sending to external service for processing. Does not resize by default (0). Optional. :param int resizeHeight: resize frame width before sending to external service for processing. Does not resize by default (0). Optional.ion( ''' try: print("\nPython %s\n" % sys.version) print("Camera Capture Azure IoT Edge Module. Press Ctrl-C to exit.") try: global hubManager hubManager = IoTHubModuleClient.create_from_edge_environment() await hubManager.connect() except: print("Unexpected error IoTHub") return with CameraCapture(videoPath, imageProcessingEndpoint, imageProcessingParams, showVideo, verbose, resizeWidth, resizeHeight, send_to_Hub_callback) as cameraCapture: await cameraCapture.start() except KeyboardInterrupt: print("Camera capture module stopped")
async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) print("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() addr = "*****@*****.**" home_id = os.environ['HOME_ID'] # This is also in an env variable print("Home ID: " + home_id) function_baseurl = "https://falldetectoralertservice.azurewebsites.net/api/httpresponder?code=NZSyiywm5hBcFLhx4AaSalEdHGsgPGeYpqbkmhnMsWOpmlHREs7ZhA==&addr=" function_baseurl += addr + "&homeId=" + home_id with open('scalability_test.csv', mode='x') as time_csv: time_writer = csv.writer(time_csv, delimiter=',') simulate_input(function_baseurl, 10, time_writer) # await module_client.send_message("\{message:\"Output on home " + # str(home_id) + "finished\"\}") # Finally, disconnect await module_client.disconnect() except Exception as e: print("Unexpected error %s " % e) raise
async def main(): """Main method for asyncio. """ # Configuring logging log = logging.getLogger('SimpleSuscriber') log.setLevel(logging.INFO) # Create console logger ch = logging.StreamHandler() ch.setLevel(logging.INFO) # Create logging formatter fmt = logging.Formatter( '[%(asctime)s] %(name)s::%(levelname)s: %(message)s') # Apply all logging pieces ch.setFormatter(fmt) log.addHandler(ch) try: # The client object is used to interact with your Azure IoT hub. log.info('Initializing IoT Hub module client') module_client = IoTHubModuleClient.create_from_edge_environment() await module_client.connect() log.info('Running') while True: msg = await module_client.receive_message_on_input('input1') meta_data = json.loads(msg.data) log.info(f'Received: {json.dumps(meta_data, indent=4)}') except Exception as e: log.error(f'Error receiving messages: {e}') finally: await module_client.disconnect()
async def main(): module_client = IoTHubModuleClient.create_from_edge_environment() await module_client.connect() sensor = Sensor() async def message_listener(module_client): while True: message = await module_client.receive_message_on_input("input1") # blocking call print("the data in the message received was ") print(message.data) print("custom properties are") print(message.custom_properties) asyncio.create_task(message_listener(module_client)) while True: try: telemetry = await sensor.readSensor() if telemetry is not None: print(telemetry) data = json.dumps(telemetry) await module_client.send_message_to_output(data, "output1") await asyncio.sleep(10) except: print("Unexpected error:", sys.exc_info()[0]) await module_client.disconnect()
async def main(): # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # Define behavior for receiving a twin patch # NOTE: this could be a function or a coroutine def twin_patch_handler(patch): print("the data in the desired properties patch was: {}".format(patch)) # set the twin patch handler on the client module_client.on_twin_desired_properties_patch_received = twin_patch_handler # define behavior for halting the application def stdin_listener(): while True: selection = input("Press Q to quit\n") if selection == "Q" or selection == "q": print("Quitting...") break # Run the stdin listener in the event loop loop = asyncio.get_running_loop() user_finished = loop.run_in_executor(None, stdin_listener) # Wait for user to indicate they are done listening for messages await user_finished # Finally, disconnect await module_client.disconnect()
async def main(): try: if not sys.version >= "3.7": raise Exception( "The sample requires python 3.7+. Current version of Python: %s" % sys.version) # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # Get the initial TWIN await getInitialTWIN(module_client) # run the async loops await asyncio.gather(twin_patch_listener(module_client), processImages(module_client)) # Finally, disconnect await module_client.disconnect() except Exception as e: print("Unexpected error %s " % e) raise
async def main(): # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # define behavior for receiving an input message on input1 async def input1_listener(): while True: input_message = await module_client.receive_message_on_input( "input1") # blocking call #print("the data in the message received on input1 was ") print(input_message.data) #print("custom properties are") #print(input_message.custom_properties) # define behavior for receiving an method message on method async def method1_listener(): while True: methodReq = await module_client.receive_method_request( "method1") # blocking call #print("the data in the message received on method1 was ") #print("Request ID:",methodReq.request_id) #print("Name:",methodReq.name) inboundPayload = methodReq.payload #The type of inboundPayload is showing up as String versus a Dict outboundPayload = json.dumps( dict({"status": "Acknowledging Receipt"})) methodResponse = MethodResponse.create_from_method_request( methodReq, 200, outboundPayload) await module_client.send_method_response(methodResponse) await asyncio.sleep(1) global display_message global display_time display_message = inboundPayload # Connect the client. await module_client.connect() async def send_test_message(): #i = 1 while True: #print("sending message #" + str(i)) #msg = Message("test wind speed " + str(i)) #msg.message_id = uuid.uuid4() #msg.correlation_id = "correlation-1234" #msg.custom_properties["tornado-warning"] = "yes" #await module_client.send_message(msg) global display_message print(display_message) await asyncio.sleep(1) #i = i + 1 # send `messages_to_send` messages in parallel await asyncio.gather(send_test_message(), input1_listener(), method1_listener()) # finally, disconnect await module_client.disconnect()
async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) print("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # define behavior for receiving an input message on input1 async def receive_data(module_client): while True: try: input_message = await module_client.receive_message_on_input( "data_input") # blocking call message = input_message.data data = message.decode('utf-8') jsonTelegram = json.loads(data) if (input_message.custom_properties.get("fire") == "yes"): print("Sending alert to telegram_bot") latitud = str(jsonTelegram.get("latitud")) longitud = str(jsonTelegram.get("longitud")) send_position = 'https://api.telegram.org/bot' + token + '/sendlocation?chat_id=' + chatId + '&latitude=' + latitud + '&longitude=' + longitud requests.get(send_position) except Exception as ex: print("Unexpected error in telegarm module: %s" % ex) def stdin_listener(): while True: try: selection = input("") if selection == "Q" or selection == "q": print("Quitting...") break except: time.sleep(30) # Schedule task for C2D Listener listeners = asyncio.gather(receive_data(module_client)) loop = asyncio.get_event_loop() user_finished = loop.run_in_executor(None, stdin_listener) await user_finished # Cancel listening listeners.cancel() # Finally, disconnect await module_client.disconnect() except Exception as e: print("Unexpected error %s " % e) raise
async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) print("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # define behavior for receiving an input message on input1 async def input1_listener(module_client): while True: input_message = await module_client.receive_message_on_input( "input1") # blocking call print("the data in the message received on input1 was ") print(input_message.data) print("custom properties are") print(input_message.custom_properties) print("forwarding mesage to output1") await module_client.send_message_to_output( input_message, "output1") # define behavior for halting the application def stdin_listener(): while True: try: selection = input("Press Q to quit\n") if selection == "Q" or selection == "q": print("Quitting...") break except: time.sleep(10) # Schedule task for C2D Listener listeners = asyncio.gather(input1_listener(module_client)) print("The sample is now waiting for messages. ") # Run the stdin listener in the event loop loop = asyncio.get_event_loop() user_finished = loop.run_in_executor(None, stdin_listener) # Wait for user to indicate they are done listening for messages await user_finished # Cancel listening listeners.cancel() # Finally, disconnect await module_client.disconnect() except Exception as e: print("Unexpected error %s " % e) raise
async def camera(frame_queue): headers = {'Content-Type': 'application/octet-stream'} # get ip adedress of other container tensorflow_container_ip=socket.gethostbyname('model_module') tensorflow_container_ip='http://'+tensorflow_container_ip+':80'+'/image' # get camera frame cap = cv2.VideoCapture(0) module_client = IoTHubModuleClient.create_from_edge_environment() await module_client.connect() while(True): # Capture frame-by-frame ret, frame = cap.read() height, width, channels = frame.shape ret, encodedFrame=cv2.imencode(".jpg",frame) try: response = requests.post(url=tensorflow_container_ip, headers = headers, data = encodedFrame.tostring()) response_json = response.json() response_json = response_json["predictions"] json_output={} for box in response_json: if float(box["probability"]) > 0.6: x1=int(float(box["boundingBox"]["left"])*width) y1=int(float(box["boundingBox"]["top"])*height) x2=int(x1+float(box["boundingBox"]["width"])*width) y2=int(y1+float(box["boundingBox"]["height"])*height) cv2.rectangle(frame,(x1,y1),(x2,y2),(255,0,0),2) text=box["tagName"]+' '+str(round(box["probability"],2)) cv2.putText(frame,text,(x2,y2),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,0,255),2) json_output[box["tagName"]]=box["probability"] ret, encodedFrame2=cv2.imencode(".jpg",frame) frame_byte=encodedFrame2.tobytes() if int(frame_queue.qsize()) > 2: frame_queue.get() frame_queue.put(frame_byte) else: frame_queue.put(frame_byte) if len(json_output) != 0: await module_client.send_message_to_output(json.dumps(json_output), "output") json_output={} except: await module_client.send_message_to_output('something wrong from camera code', "output") time.sleep(2)
def create_from_environment(self, transport_type): kwargs = {} if transport_type == "mqttws": kwargs["websockets"] = True self.client = IoTHubModuleClient.create_from_edge_environment(**kwargs) mqtt_transport.DEFAULT_KEEPALIVE = DEFAULT_KEEPALIVE self._attach_connect_event_watcher()
async def Startup(): print('Starting now') try: client = IoTHubModuleClient.create_from_edge_environment() print('Created client') await client.connect() print('Connected') return client except Exception as ex: print('Startup: Error - {}'.format(ex))
def __init__(self): self.pub = rospy.Publisher('detection', String, queue_size=2) self.module_client = IoTHubModuleClient.create_from_edge_environment() print("Starting ROSConnector Module") print("Connect Client...") rospy.init_node('detection') print("....") # connect the client. print("Client Connected!") self.r = rospy.Rate(10) # 10hz
async def create_from_environment(self, transport_type): kwargs = {} if transport_type == "mqttws": kwargs["websockets"] = True if internal_control_glue.sas_renewal_interval: kwargs["sastoken_ttl"] = internal_control_glue.sas_renewal_interval self.client = IoTHubModuleClient.create_from_edge_environment(**kwargs) mqtt_transport.DEFAULT_KEEPALIVE = DEFAULT_KEEPALIVE self._attach_connect_event_watcher()
async def main(): # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # define behavior for receiving an input message on input1 async def input1_listener(module_client): global LATEST_TAG while True: input_message = await module_client.receive_message_on_input("input1") data = json.loads(input_message.data) highestProbabilityTag = highestProbabilityTagMeetingThreshold(data, 0.6) if highestProbabilityTag == "none": print("Not sending alert to hub => no tag reached probability") elif highestProbabilityTag == "Negative": print("Not sending alert to hub => Negative tag") else: print("Sending alert to hub for: {}".format(highestProbabilityTag)) output_msg = Message("{'tag':'"+highestProbabilityTag+"'}") output_msg.message_id = uuid.uuid4() output_msg.correlation_id = "test-1234" await module_client.send_message_to_output(output_msg,"output1") print("Latest tag: " + LATEST_TAG) # define behavior for halting the application def stdin_listener(): print("Started listening...") while True: ja = True if ja == False: break # Schedule task for listeners listeners = asyncio.gather(input1_listener(module_client)) # Run the stdin listener in the event loop loop = asyncio.get_running_loop() user_finished = loop.run_in_executor(None, stdin_listener) # Wait for user to indicate they are done listening for messages await user_finished # Cancel listening listeners.cancel() # Finally, disconnect await module_client.disconnect()
async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) print("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # define behavior for receiving an input message on input1 async def input1_listener(module_client): while True: input_message = await module_client.receive_message_on_input( "input1") # blocking call print("the data in the message received on input1 was ") print(input_message.data) print("custom properties are") print(input_message.custom_properties) print("forwarding mesage to output1") await module_client.send_message_to_output( input_message, "output1") # Schedule task for C2D Listener listeners = asyncio.gather(input1_listener(module_client)) while True: print(str(datetime.datetime.now()) + " Reading HDD temperature") bashCommand = "hddtemp " + os.environ['DRIVE_PATH'] process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE) output, error = process.communicate() message = "{\"drive\":\"" + os.environ[ 'DRIVE_PATH'] + "\",\"result\":\"" + str(output) + "\"}" print(message) await module_client.send_message_to_output(message, "output1") # wait 10 seconds time.sleep(10) # Cancel listening listeners.cancel() # Finally, disconnect await module_client.disconnect() except Exception as e: print("Unexpected error %s " % e) raise
async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version ) print ("\nPuthon %s\n" % sys.version) print ( "BMP280 Module" ) # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() async def measurments_sender(module_client): global I2C_BUS_NUMBER while True: try: print("reading bmp280") device = BMP280Device(I2C_BUS_NUMBER) (temperature, pressure) = await device.read() msg_txt_formatted = MSG_TXT.format(temperature = temperature, pressure = pressure) print ("bmp280 says " + msg_txt_formatted) message = Message(msg_txt_formatted) message.message_id = uuid.uuid4() message.custom_properties["temperature"] = temperature message.custom_properties["pressure"] = pressure await module_client.send_message_to_output(message, "output1") await asyncio.sleep(30) except Exception as ex: traceback.print_last() print ("Unexpected error %s " % repr(ex) ) async def twin_patch_listener(module_client): global I2C_BUS_NUMBER while True: try: #settings = await module_client.receive_twin_desired_properties_patch() print ("desired properties") #if "I2CBus" in settings: # I2C_BUS_NUMBER = settings["I2CBus"] await asyncio.sleep(5) except Exception as ex: print ("Unexpected error in twin_patch_listener %s " % repr(ex) ) await asyncio.gather(measurments_sender(module_client), twin_patch_listener(module_client)) # Finally, disconnect await module_client.disconnect() except Exception as e: print ( "Unexpected error %s " % repr(e) ) raise
async def main(): # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # define behavior for receiving an input message on input1 async def input1_listener(module_client): while True: input_message = await module_client.receive_message_on_input( "input1") # blocking call print("the data in the message received on input1 was ") print(input_message.data) print("custom properties are") print(input_message.custom_properties) # define behavior for receiving an input message on input2 async def input2_listener(module_client): while True: input_message = await module_client.receive_message_on_input( "input2") # blocking call print("the data in the message received on input2 was ") print(input_message.data) print("custom properties are") print(input_message.custom_properties) # define behavior for halting the application def stdin_listener(): while True: selection = input("Press Q to quit\n") if selection == "Q" or selection == "q": print("Quitting...") break # Schedule task for listeners listeners = asyncio.gather(input1_listener(module_client), input2_listener(module_client)) # Run the stdin listener in the event loop loop = asyncio.get_running_loop() user_finished = loop.run_in_executor(None, stdin_listener) # Wait for user to indicate they are done listening for messages await user_finished # Cancel listening listeners.cancel() # Finally, disconnect await module_client.disconnect()
def create_client(): client = IoTHubModuleClient.create_from_edge_environment() # Define function for handling received messages async def receive_message_handler(message): try: filtered_message = filter_message(message) except KeyError as e: print("Error when filtering message: %s" % e) else: if filtered_message: await client.send_message_to_output(filtered_message, "output1") print("Forwarded message to Hub") def twin_patch_received_handler(twin_patch): """Update the TEMPERATURE THRESHOLD value if its twin property is updated""" global TEMPERATURE_THRESHOLD if TEMP_THRESHOLD_PROPERTY_NAME in twin_patch: TEMPERATURE_THRESHOLD = twin_patch[TEMP_THRESHOLD_PROPERTY_NAME] async def method_request_received_handler(method_request): print("Received method request [{}]".format(method_request.name)) # Send the heart beat message to the corresponding output heart_beat_message = Message("Module [FilterModule] is running") heart_beat_message.custom_properties["MessageType"] = HEART_BEAT await client.send_message_to_output(HEART_BEAT, heart_beat_message) print("Heart beat message sent to heart beat output") # Send the message response response_payload = "{ \"Response\": \"This is the response from the device\" }" method_response = MethodResponse.create_from_method_request( method_request=method_request, status=200, payload=response_payload) await client.send_method_response(method_response) print("Method response to [{}] sent".format(method_request.name)) try: # Attach client handlers client.on_message_received = receive_message_handler client.on_twin_desired_properties_patch_received = twin_patch_received_handler client.on_method_request_received = method_request_received_handler except: # Clean up in the event of failure client.shutdown() raise return client
async def main(): # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # update the reported properties reported_properties = {"temperature": random.randint(320, 800) / 10} print("Setting reported temperature to {}".format( reported_properties["temperature"])) await module_client.patch_twin_reported_properties(reported_properties) # Finally, shut down the client await module_client.shutdown()
async def main(): try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) print("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() async def send_data(): global BATTERY_CAPACITY while BATTERY_CAPACITY > 0: mensaje = { "bateria": BATTERY_CAPACITY, "temperatura": random.randint(35, 100), "humedad": random.randint(0, 100), "latitud": round(random.uniform(40.400000, 40.450000), 6), "longitud": round(random.uniform(-3.800000, -3.700000), 6) } BATTERY_CAPACITY -= 1 msg = Message(json.dumps(mensaje)) msg.message_id = uuid.uuid4() msg.correlation_id = "tfmId" if mensaje.get("temperatura") > 95: msg.custom_properties["fire"] = "yes" else: msg.custom_properties["fire"] = "no" print("Sending data: ", msg) await module_client.send_message_to_output(msg, "data_output") time.sleep(0.5) await asyncio.gather(send_data()) await module_client.disconnect() except Exception as e: print("Unexpected error %s " % e) raise
async def main(): global module_client try: if not sys.version >= '3.6': raise Exception('The object detection business logic module requires python 3.6+. Current version of Python: %s' % sys.version) print("Starting lvaMock edge module") module_client = IoTHubModuleClient.create_from_edge_environment(websockets=True) await module_client.connect() module_client.on_method_request_received = method_request_handler await continuous_loop() await module_client.disconnect() except Exception as ex: print('Unexpected error from IoTHub: %s' % ex) return
def create_client(): # The client object is used to interact with your Azure IoT hub. client = IoTHubModuleClient.create_from_edge_environment() # Define behavior for receiving an input message on input1 and input2 # NOTE: this could be a coroutine or a function def message_handler(message): if message.input_name == "input1": print("Message received on INPUT 1") print("the data in the message received was ") print(message.data) print("custom properties are") print(message.custom_properties) elif message.input_name == "input2": print("Message received on INPUT 2") print("the data in the message received was ") print(message.data) print("custom properties are") print(message.custom_properties) else: print("message received on unknown input") # Define behavior for receiving a twin desired properties patch # NOTE: this could be a coroutine or function def twin_patch_handler(patch): print("the data in the desired properties patch was: {}".format(patch)) # Define behavior for receiving methods async def method_handler(method_request): if method_request.name == "get_data": print("Received request for data") method_response = MethodResponse.create_from_method_request( method_request, 200, "some data") await client.send_method_response(method_response) else: print("Unknown method request received: {}".format( method_request.name)) method_response = MethodResponse.create_from_method_request( method_request, 400, None) await client.send_method_response(method_response) # set the received data handlers on the client client.on_message_received = message_handler client.on_twin_desired_properties_patch_received = twin_patch_handler client.on_method_request_received = method_handler return client
async def main(): # pragma: no cover try: if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version) EdgeLogger().logger.info("IoT Hub Client for Python") # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # define behavior for halting the application def stdin_listener(): while True: try: selection = input() if selection == "Q" or selection == "q": print("Quitting...") break except: time.sleep(10) # Schedule task for C2D Listener listeners = asyncio.gather(input_listener(module_client)) EdgeLogger().logger.info("The module is now waiting for messages.") # Run the stdin listener in the event loop loop = asyncio.get_event_loop() user_finished = loop.run_in_executor(None, stdin_listener) # Wait for user to indicate they are done listening for messages await user_finished # Cancel listening listeners.cancel() # Finally, disconnect await module_client.disconnect() except Exception as e: EdgeLogger().logger.error("Unexpected error %s " % e) raise
async def main(): # The client object is used to interact with your Azure IoT hub. module_client = IoTHubModuleClient.create_from_edge_environment() # connect the client. await module_client.connect() # Define behavior for receiving an input message on input1 # NOTE: this could be a coroutine or a function def message_handler(message): if message.input_name == "input1": print("Message received on INPUT 1") print("the data in the message received was ") print(message.data) print("custom properties are") print(message.custom_properties) elif message.input_name == "input2": print("Message received on INPUT 2") print("the data in the message received was ") print(message.data) print("custom properties are") print(message.custom_properties) else: print("message received on unknown input") # set the message handler on the client module_client.on_message_received = message_handler # define behavior for halting the application def stdin_listener(): while True: selection = input("Press Q to quit\n") if selection == "Q" or selection == "q": print("Quitting...") break # Run the stdin listener in the event loop loop = asyncio.get_running_loop() user_finished = loop.run_in_executor(None, stdin_listener) # Wait for user to indicate they are done listening for messages await user_finished # Finally, shut down the client await module_client.shutdown()