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
def connect_from_environment(self, transport_type): print("connecting from environment") auth_provider = auth.from_environment() self.client = IoTHubModuleClient.from_authentication_provider( auth_provider, transport_type ) async_helper.run_coroutine_sync(self.client.connect())
async def main(): IOT_DEVICE_CONNSTR = "HostName=mythicaledge1.azure-devices.net;DeviceId=macbook;SharedAccessKey=8BcwaCRkstEkyFBwwV5zTpWnLkro0uUWGR2tSrjW3kg=" module_client = IoTHubModuleClient.create_from_connection_string( IOT_DEVICE_CONNSTR) method_name = "method1" named_tuple = time.localtime() # get struct_time time_string = time.strftime("%m/%d/%Y, %H:%M:%S", named_tuple) payload = json.dumps( dict({ 'msg': 'Welcome to Digital Display', 'DtTm:': time_string })) method_params = dict({ 'method_name': method_name, 'payload': time_string, 'connect_timeout_in_seconds': 10 }) methodResponse = await module_client.invoke_method(method_params, 'macbook', 'PySendModule') print("ResponseId:", methodResponse.status) print("Payload:", methodResponse.payload) module_client.disconnect()
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(): # The "Authentication Provider" is the object in charge of creating authentication "tokens" for the device client. auth_provider = auth.from_environment() # For now, the SDK only supports MQTT as a protocol. the client object is used to interact with your Azure IoT hub. # It needs an Authentication Provider to secure the communication with the hub, using either tokens or x509 certificates device_client = IoTHubModuleClient.from_authentication_provider( auth_provider, "mqtt") # Connect the client. await device_client.connect() async def send_test_message(i): 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 device_client.send_event(msg) print("done sending message #" + str(i)) # send `messages_to_send` messages in parallel await asyncio.gather( *[send_test_message(i) for i in range(1, messages_to_send + 1)]) # finally, disconnect await device_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 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 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() # 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(): 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(): # The "Authentication Provider" is the object in charge of creating authentication "tokens" for the module client. auth_provider = auth.from_environment() # For now, the SDK only supports MQTT as a protocol. # Inputs/Ouputs are only supported in the context of Azure IoT Edge and module client # The module client object acts as an Azure IoT Edge module and interacts with an Azure IoT Edge hub # It needs an Authentication Provider to secure the communication with the Edge hub. # This authentication provider is created from environment & delegates token generation to iotedged. module_client = IoTHubModuleClient.from_authentication_provider(auth_provider, "mqtt") # Connect the client. await module_client.connect() # Send a filled out Message object async def send_test_message(i): 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_to_output(msg, "twister") print("done sending message #" + str(i)) await asyncio.gather(*[send_test_message(i) for i in range(1, messages_to_send)]) # finally, disconnect module_client.disconnect()
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(): hostname = os.getenv("HOSTNAME") # The device having a certain module that has been created on the portal # using X509 CA signing or Self signing capabilities device_id = os.getenv("DEVICE_ID") module_id = os.getenv("MODULE_ID") x509 = X509( cert_file=os.getenv("X509_CERT_FILE"), key_file=os.getenv("X509_KEY_FILE"), pass_phrase=os.getenv("PASS_PHRASE"), ) module_client = IoTHubModuleClient.create_from_x509_certificate( hostname=hostname, x509=x509, device_id=device_id, module_id=module_id ) # Connect the client. await module_client.connect() async def send_test_message(i): 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_d2c_message(msg) print("done sending message #" + str(i)) await asyncio.gather(*[send_test_message(i) for i in range(1, messages_to_send + 1)]) # finally, disconnect 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() # 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 connect(self, transport_type, connection_string, cert): print("connecting using " + transport_type) auth_provider = auth.from_connection_string(connection_string) if "GatewayHostName" in connection_string: auth_provider.ca_cert = cert self.client = IoTHubModuleClient.from_authentication_provider( auth_provider, transport_type ) async_helper.run_coroutine_sync(self.client.connect())
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))
async def main(): # The "Authentication Provider" is the object in charge of creating authentication "tokens" for the device client. auth_provider = auth.from_environment() # For now, the SDK only supports MQTT as a protocol. the client object is used to interact with your Azure IoT hub. # It needs an Authentication Provider to secure the communication with the hub, using either tokens or x509 certificates module_client = IoTHubModuleClient.from_authentication_provider( auth_provider, "mqtt") # 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_input_message( "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_input_message( "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 C2D Listener 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()
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()
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 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()