async def main(): connection_string = os.getenv("DEVICE_CONNECTION_STRING") device_client = IoTHubDeviceClient.create_from_connection_string( connection_string) await device_client.connect() try: values = list(map(float, sys.argv[1:])) or [42] payload = [] for value in values: print("Collecting value:", value) payload.append({ "DeviceId": "microsoft-sphere-device", "ValueId": "Temperature", "Value": value, "TimeStamp": datetime.datetime.now(datetime.timezone.utc) }) await asyncio.sleep(1) message = json.dumps(payload, default=serialize_datetime) print("Sending message:", message) await device_client.send_message(message) finally: await device_client.disconnect()
async def main(): # Scenario based values keep_alive = 15 conn_str = "HostName=localhost;DeviceId=devicemtr;SharedAccessKey=Zm9vYmFy" device_client = IoTHubDeviceClient.create_from_connection_string( conn_str, keep_alive=keep_alive) await device_client.connect() send_message_task = asyncio.create_task(send_test_message(device_client)) # Run the listener in the event loop # This can be a STDIN listener as well for user to indicate quitting. loop = asyncio.get_running_loop() finished_loops = loop.run_in_executor(None, quitting_listener) # Wait for count times to reach a certain number indicative of completion await finished_loops print(elapsed_times) try: send_message_task.cancel() except asyncio.CancelledError: print("send message task is cancelled now") await device_client.disconnect()
async def main(): conn_str = "HostName=5G-IoT-System-For-Emergency-Responders.azure-devices.net;DeviceId=application_device1;SharedAccessKey=x84oYfc8Wm4lL7nfMzNm87X7YmFbC+TtHX4ny+bV8ck=" device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # Connect the device client. await device_client.connect() # Send a few messages count = 0 tempFile = open("/sys/class/thermal/thermal_zone0/temp", "r") while count < 5: cpu_temp = tempFile.read() cpu_temp_float = float(cpu_temp) tempFile.seek(0) print("Sending message to Azure IoT...") msg = Message("Environment sensor") msg.message_id = uuid.uuid4() msg.custom_properties["Temperature"] = cpu_temp_float await device_client.send_message(msg) print("Message successfully sent:") print(msg.custom_properties) count = count + 1 time.sleep(10) # finally, disconnect await device_client.disconnect() sys.exit(0)
async def main(): # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here. conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") # The client object is used to interact with your Azure IoT hub. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # 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" msg.content_encoding = "utf-8" msg.content_type = "application/json" await device_client.send_message(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, shut down the client await device_client.shutdown()
async def main(): device_client = IoTHubDeviceClient.create_from_connection_string( "HostName=YOURAZUREACCOUNT.azure-devices.net;DeviceId=Pi_Envirnoment;SharedAccessKey=YOURSHAREDACCESSKEY" ) await device_client.connect() 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)) def quit_listener(): while True: selection = input("Press Q to quit\n") if selection == "Q" or selection == "q": print("Quitting...") break asyncio.create_task(twin_patch_listener(device_client)) loop = asyncio.get_running_loop() user_finished = loop.run_in_executor(None, quit_listener) await user_finished await device_client.disconnect()
async def main(): with open("private.json", "r") as read_file: config = json.load(read_file) device_client = IoTHubDeviceClient.create_from_connection_string(config["connection-string"]) await device_client.connect() last_temp = "" done = False sample_count = 0 max_samples = 64 while not (done): temp = "{0:0.1f}".format(get_temp()) print("data", temp) if temp != last_temp: last_temp = temp; data = {} data['sample'] = temp json_body = json.dumps(data) print("Sending message: ", json_body) sample_count += 1 await device_client.send_message(json_body) done = (sample_count > max_samples) time.sleep(30) await device_client.disconnect()
async def main(): # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here. conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") # The client object is used to interact with your Azure IoT hub. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # Connect the client. await device_client.connect() node = cellulariot.CellularIoTApp() node.setupGPIO() node.disable() time.sleep(1) node.enable() async def sensor_data(): msg = Message("Acceleration: "+str(node.readAccel())+"; "+"Humidity: " + str(node.readHum())+"; "+"Temperature: " + str(node.readTemp())+"; "+"Lux: " + str(node.readLux())+"; "+"ADC1: " + str(node.readAdc(0))+"; "+"ADC2: " + str(node.readAdc(1))+"; "+"ADC3: " + str(node.readAdc(2))+"; "+"ADC4: " + str(node.readAdc(3))) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" await device_client.send_message(msg) count = 0 while(True): await sensor_data() print("#"+str(count)+" sent data") count = count+1 time.sleep(1)
async def main(): # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here. conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") # The client object is used to interact with your Azure IoT hub. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # connect the client. await device_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 device_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 device_client.disconnect()
async def main(): # Get the data list from our library dataList = fileparser.get_data_list_from_wisdm('WISDM_ar_v1.1\\WISDM_ar_v1.1_raw.txt') # Fetch the connection string from an enviornment variable conn_str = "HostName=berlinHub.azure-devices.net;DeviceId=subject_33;SharedAccessKey=wMVcHCziLXiH6CQRf/uz8uUnHIiQjkF1yAPKQ9t5iHU=" # Create instance of the device client using the connection string device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # Connect the device client. await device_client.connect() # Loop through the data and send to IoT Hub for data in dataList: msg_txt_formatted = MSG_TXT.format(user=data.user, activity=data.activity, timestamp=data.timestamp, x=data.x, y=data.y, z=data.z) message = Message(msg_txt_formatted) print( "Sending message: {}".format(message) ) await device_client.send_message(message) print ( "Message successfully sent" ) time.sleep(MSG_INTERVAL) await device_client.shutdown()
async def receive_cloud_message(): device_client = IoTHubDeviceClient.create_from_connection_string( DEVICE_CONN_STRING) await device_client.connect() async def message_listener(device_client): while True: message = await device_client.receive_message() print("the data in the message received was ") print(message.data) await analyze_msg(message.data) def stdin_listener(): while True: selection = input("Press Q to quit\n") if selection == "Q" or selection == "q": print("Quitting...") break asyncio.create_task(message_listener(device_client)) loop = asyncio.get_running_loop() user_finished = loop.run_in_executor(None, stdin_listener) await user_finished await device_client.disconnect()
async def main(): # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here. # NOTE: connection string must contain ;GatewayHostName=<hostname of your iot edge device> # make sure your IoT Edge box is setup as a 'transparent gateway' per the IOT Edge documentation conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") # path to the root ca cert used on your iot edge device (must copy the pem file to this downstream device) # example: /home/azureuser/edge_certs/azure-iot-test-only.root.ca.cert.pem ca_cert = os.getenv("IOTEDGE_ROOT_CA_CERT_PATH") certfile = open(ca_cert) root_ca_cert = certfile.read() # The client object is used to interact with your Azure IoT Edge device. device_client = IoTHubDeviceClient.create_from_connection_string( connection_string=conn_str, server_verification_cert=root_ca_cert ) # 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_message(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, shut down the client await device_client.shutdown()
async def main(): conn_str = "<Your device connection string goes here>" device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) await device_client.connect() last_temp = "" while True: temp = "{0:0.1f}".format(get_temp()) print("Temperature", temp) if temp != last_temp: last_temp = temp; data = {} data['temperature'] = temp json_body = json.dumps(data) print("Sending message: ", json_body) await device_client.send_message(json_body) twin = await device_client.get_twin() handle_twin(twin) time.sleep(1) await device_client.disconnect()
async def connect(self): deviceClient = IoTHubDeviceClient.create_from_connection_string( self.connectionString) # iz librarya konstruktor await deviceClient.connect( ) # await -> ceka do kad se klijent ne spoji na azure self.device = deviceClient # device klijent spremimo u varijablu da se moze koristiti u cijeloj klasi self.device.on_message_received = self.azureMessageCallback # callback metoda izjednacena s onom iz libraria (kad prime oni poruku, primimo i mi u svojoj)
async def main(): # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here. conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") proxy_opts = ProxyOptions( proxy_type=socks.HTTP, proxy_addr="127.0.0.1", proxy_port=8888 # localhost ) # The client object is used to interact with your Azure IoT hub. device_client = IoTHubDeviceClient.create_from_connection_string( conn_str, websockets=True, proxy_options=proxy_opts) # 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_message(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()
def create_client(): # Create an IoT Hub client client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING) # Define a method request handler async def method_request_handler(method_request): if method_request.name == "SetTelemetryInterval": try: global INTERVAL INTERVAL = int(method_request.payload) except ValueError: response_payload = {"Response": "Invalid parameter"} response_status = 400 else: response_payload = {"Response": "Executed direct method {}".format(method_request.name)} response_status = 200 else: response_payload = {"Response": "Direct method {} not defined".format(method_request.name)} response_status = 404 method_response = MethodResponse.create_from_method_request(method_request, response_status, response_payload) await client.send_method_response(method_response) try: # Attach the method request handler client.on_method_request_received = method_request_handler except: # Clean up in the event of failure client.shutdown() raise return client
async def main(): # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here. conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") # The client object is used to interact with your Azure IoT hub. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # connect the client. await device_client.connect() # Define behavior for handling methods async def method_request_handler(method_request): # Determine how to respond to the method request based on the method name if method_request.name == "method1": payload = { "result": True, "data": "some data" } # set response payload status = 200 # set return status code print("executed method1") elif method_request.name == "method2": payload = {"result": True, "data": 1234} # set response payload status = 200 # set return status code print("executed method2") else: payload = { "result": False, "data": "unknown method" } # set response payload status = 400 # set return status code print("executed unknown method: " + method_request.name) # Send the response method_response = MethodResponse.create_from_method_request( method_request, status, payload) await device_client.send_method_response(method_response) # Set the method request handler on the client device_client.on_method_request_received = method_request_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 method calls await user_finished # Finally, shut down the client await device_client.shutdown()
async def main(): # provision the device async def register_device(): provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key( provisioning_host='global.azure-devices-provisioning.net', registration_id=device_id, id_scope=id_scope, symmetric_key=primary_key, ) return await provisioning_device_client.register() results = await asyncio.gather(register_device()) registration_result = results[0] # build the connection string conn_str='HostName=' + registration_result.registration_state.assigned_hub + \ ';DeviceId=' + device_id + \ ';SharedAccessKey=' + primary_key # The client object is used to interact with your Azure IoT Central. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # connect the client. print('Connecting') await device_client.connect() print('Connected') # listen for commands async def command_listener(device_client): global mode while True: method_request = await device_client.receive_method_request() payload = {'result': True, 'data': method_request.name} method_response = MethodResponse.create_from_method_request( method_request, 200, payload ) await device_client.send_method_response(method_response) # async loop that controls the lights async def main_loop(): while True: telemetry = getTelemetryData() print(telemetry) await device_client.send_message(telemetry) await asyncio.sleep(1) listeners = asyncio.gather(command_listener(device_client)) await main_loop() # Cancel listening listeners.cancel() # Finally, disconnect await device_client.disconnect()
async def InitIoTHubClient(): # Fetch the connection string from an enviornment variable conn_str = "HostName=sameerIOTHub.azure-devices.net;DeviceId=RaspberryPi;SharedAccessKey=UBPpcMu5Hwb79ZfhnLBLz5vAF01NlndzR9OFH+/CfeA=" # Create instance of the device client using the authentication provider global device_client device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # Connect the device client. await device_client.connect()
async def send_single_message(message_body): device_client = IoTHubDeviceClient.create_from_connection_string( DEVICE_CONN_STRING) await device_client.connect() message = Message(json.dumps(message_body), content_type='application/json') await device_client.send_message(message) await device_client.disconnect()
async def write_to_hub(source_path, list_of_files, counter, limit, container_name, dest_folder): conn_str = env.IOT_HUB_CONN_STRING # The client object is used to interact with your Azure IoT hub. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # Connect the client. await device_client.connect() async def send_spectrogram(counter): sleep_interval = 5 while True: for f in list_of_files: payload = json.dumps({ 'capturedate': time.time(), 'filename': f, 'finished': 'False' }) azure_interface = AzureInterface(container_name) azure_interface.send_to_azure(join_paths([source_path, f]), dest_folder, f, media_file=True) msg = build_message(payload) await device_client.send_message(msg) logger.info("done sending file " + str(f)) counter['count'] += 1 logger.info(counter['count']) await asyncio.sleep(sleep_interval) # Define behavior for halting the application def stdin_listener(counter, limit): while True: try: if counter['count'] == limit: logger.info('Quitting...') logger.info('File limit reached %s', str(limit)) break except EOFError as e: time.sleep(10000) tasks = asyncio.gather(send_spectrogram(counter)) # Run the stdin listener in the event loop loop = asyncio.get_running_loop() user_finished = loop.run_in_executor(None, stdin_listener, counter, limit) # Wait for user to indicate they are done listening for method calls await user_finished # Cancel tasks tasks.add_done_callback(lambda r: r.exception()) tasks.cancel() await device_client.disconnect()
async def main(): # Connect to IoT Central and request the connection details for the device provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key( provisioning_host="global.azure-devices-provisioning.net", registration_id=device_id, id_scope=id_scope, symmetric_key=primary_key) registration_result = await provisioning_device_client.register() # Build the connection string - this is used to connect to IoT Central conn_str="HostName=" + registration_result.registration_state.assigned_hub + \ ";DeviceId=" + device_id + \ ";SharedAccessKey=" + primary_key # The client object is used to interact with Azure IoT Central. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # Connect the client. timestamp = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S') print(timestamp, end='') print(" Connecting ...") await device_client.connect() timestamp = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S') print(timestamp, end='') print(" Connected!") # Start the command listener timestamp = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S') print(timestamp, end='') print(" Start Listening ...") listener1 = asyncio.gather(light_listener(device_client)) listener2 = asyncio.gather(temp_listener(device_client)) # async loop async def main_loop(): while True: await asyncio.sleep(60) listener1 = asyncio.gather(light_listener(device_client)) listener2 = asyncio.gather(temp_listener(device_client)) # Run the async main loop forever try: await main_loop() except KeyboardInterrupt: # Cancel listening listener1.cancel() listener2.cancel() finally: # Finally, disconnect await device_client.disconnect() timestamp = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S') print(timestamp, end='') print(" Disconnected!") GPIO.cleanup()
async def main(count, sleep_milliseconds): conn_str = os.getenv("AZURE_IOTHUB_DEVICE1_CONN_STR") device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) await device_client.connect() for i in range(count): await send_message(device_client, i) time.sleep(float(sleep_milliseconds) / 1000.0) await device_client.disconnect()
async def sendMessage(): # Create instance of the device client using the authentication provider device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # Connect the device client. await device_client.connect() # Send a single message print("Sending message...") await device_client.send_message("This is a message that is being sent") print("Message successfully sent!")
async def main(): # Connect to IoT Central and request the connection details for the device provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key( provisioning_host="global.azure-devices-provisioning.net", registration_id=device_id, id_scope=id_scope, symmetric_key=primary_key) registration_result = await provisioning_device_client.register() # Build the connection string - this is used to connect to IoT Central conn_str="HostName=" + registration_result.registration_state.assigned_hub + \ ";DeviceId=" + device_id + \ ";SharedAccessKey=" + primary_key # The client object is used to interact with Azure IoT Central. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # Connect the client. print("Connecting") await device_client.connect() print("Connected") # async loop that sends the telemetry async def main_loop(): while True: # Get the telemetry to send telemetry = await get_telemetry() print("Telemetry:", telemetry) # Send the telemetry to IoT Central await device_client.send_message(telemetry) # Wait for a minute so telemetry is not sent to often await asyncio.sleep(60) # Event handler for a key being releases def on_release(key): global report_high_sound # If the key that was pressed and released is the space bar, # flag that next time a high sound value should be reported if key == keyboard.Key.space: print("Space pressed - will report high sound level next cycle") report_high_sound = True # Listen for keyboard key release events listener = keyboard.Listener(on_release=on_release) listener.start() # Run the async main loop forever await main_loop() # Finally, disconnect await device_client.disconnect()
async def main(): # The connection string for a device conn_str = "" # The client object is used to interact with your Azure IoT hub. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) pi = pigpio.pi() # 各GPIOの初期化 pi.set_mode(BIN1, pigpio.OUTPUT) pi.set_mode(BIN2, pigpio.OUTPUT) # connect the client. await device_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)) # print(patch) command = patch['command'] if command == 'stop': pi.hardware_PWM(BIN1, BIN_FREQUENCY, 0) pi.hardware_PWM(BIN2, BIN_FREQUENCY, 0) elif command == 'forward': pi.hardware_PWM(BIN1, BIN_FREQUENCY, 900000) pi.hardware_PWM(BIN2, BIN_FREQUENCY, 0) # 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 else: print("Input was..." + selection) # Schedule task for twin patch asyncio.create_task(twin_patch_listener(device_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 device_client.disconnect()
async def main(): conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # connect the client. await device_client.connect() # get the twin twin = await device_client.get_twin() print("Reported temperature is {}".format(twin["reported"]["temperature"])) # Finally, disconnect await device_client.disconnect()
async def main(): data = {} data['Temperature'] = 112 data['Personid'] = '13' data['Oximeter'] = final_o data['PulseRate'] = 75 json_body = json.dumps(data) conn_str = "HostName=iotcloudhub.azure-devices.net;DeviceId=TempSensor;SharedAccessKey=A88TxjwPI4InYiGl3HaJaO96EUP5xg1i8vYQz3zkKc4=" device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) await device_client.connect() await device_client.send_message(json_body) await device_client.disconnect() print(data['Temperature'])
async def main(): # The client object is used to interact with your Azure IoT hub. device_client = IoTHubDeviceClient.create_from_connection_string( connection_string) # Connect the client. print("Connecting") await device_client.connect() print("Connected") # Connect to the GPSD daemon gpsd = gps(mode=WATCH_ENABLE | WATCH_NEWSTYLE) # The main loop - loops forever reading GPS values and sending them to IoT Hub async def main_loop(): while True: # Get the next value reported by the GPS device report = gpsd.next() # GPS values can have multiple types, such as: # TPV - Time, position, velocity giving the time signal, current position and current calculated velocity # SKY - the sky view of GPS satellite positions # GST - error ranges # Monitor for the TPV values to get the position. Sometimes this value can come without the properties if # the values aren't available yet, so ignore if the lat and lon are not set if report["class"] == "TPV" and hasattr(report, 'lat') and hasattr( report, 'lon'): # Build the message with GPS location values. message_body = { "latitude": report.lat, "longitude": report.lon } # Convert to an IoT Hub message message = Message(json.dumps(message_body)) # Send the message. print("Sending message:", message) await device_client.send_message(message) print("Message successfully sent") # Wait for a minute so telemetry is not sent to often # Only sleep after receiving TPV values so we don't waste # time sleeping after other values that are ignored await asyncio.sleep(60) # Run the async main loop forever await main_loop() # Finally, disconnect await device_client.disconnect()
async def main(): conn_str = "HostName=5G-IoT-System-For-Emergency-Responders.azure-devices.net;DeviceId=application_device1;SharedAccessKey=x84oYfc8Wm4lL7nfMzNm87X7YmFbC+TtHX4ny+bV8ck=" device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) # Connect the device client. await device_client.connect() # Send a few messages count = 0 enviro = EnviroBoard() threshold_temp = 40.00 threshold_ambient_light = 80.00 file = open("/home/mendel/person_detected.txt","r") while count < 50: current_temp = enviro.temperature current_ambient_light = enviro.ambient_light person_detected = file.read(1) #print(person_detected) message_properties = {"personDetected" : 0} if person_detected == '1': if current_temp > threshold_temp: print("WARNING: Person Detected under high temp conditions!!") message_properties["personDetected"] = 1 if current_ambient_light > threshold_ambient_light: print("WARNING: Person Detected under high ambient light conditions!!") message_properties["personDetected"] = 1 #else: #print("Person detected under normal conditions!") #else: #print("Preson Not Detected") file.seek(0) message_properties["temperature"] = current_temp message_properties["humidity"] = enviro.humidity message_properties["ambientLight"] = current_ambient_light message_properties["pressure"] = enviro.pressure message_properties["deviceId"] = "Google-Coral" message_properties["lat"] = 37.38574713765911 message_properties["long"] = -121.89022121011448 msg = Message(json.dumps(message_properties)) msg.message_id = uuid.uuid4() msg.content_type = 'application/json' await device_client.send_message(msg) print("Message successfully sent:" + str(msg)) print() count = count + 1 time.sleep(5) # finally, disconnect await device_client.disconnect() sys.exit(0)
async def main(): parser = argparse.ArgumentParser( description= "Data collector which sends sensor measurements to Azure IoT HUB") parser.add_argument("--nolcd", action='store_true', help="Skip LCD printout") args = parser.parse_args() if args.nolcd: print("No LCD") try: bme280 = BME280() led = Led() lcd = None if not args.nolcd: lcd = LCD() (chip_id, chip_version) = bme280.readID() print(f"Started, chip_id={chip_id}, chip_version={chip_version}") conn_str = os.getenv("DEV_BME_CONN_STR") device_client = IoTHubDeviceClient.create_from_connection_string( conn_str) await device_client.connect() while True: temperature, pressure, humidity = bme280.readAll() measTime = datetime.now().isoformat() measRow = f'{{"Temperature":{temperature:0.2f},"Pressure":{pressure:0.2f},"Humidity":{humidity:0.2f}}}' print(f"Sending message: {measRow}") await device_client.send_message(measRow) if not args.nolcd: lcdOut = f"T:{temperature:0.1f}C {pressure:0.1f}hPa\nH:{humidity:0.1f}%" lcd.clear() lcd.setCursor(0, 0) lcd.message(lcdOut) led.blinkLed() sleep(2 * 60) except KeyboardInterrupt: print("exiting...") await device_client.disconnect() led.close() if not args.nolcd: lcd.clear() lcd.setCursor(0, 0) lcd.destroy()