async def main(): switch = os.getenv("IOTHUB_DEVICE_SECURITY_TYPE") if switch == "DPS": provisioning_host = (os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT") if os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT") else "global.azure-devices-provisioning.net") id_scope = os.getenv("IOTHUB_DEVICE_DPS_ID_SCOPE") registration_id = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_ID") symmetric_key = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_KEY") registration_result = await provision_device(provisioning_host, id_scope, registration_id, symmetric_key, model_id) if registration_result.status == "assigned": print("Device was assigned") print(registration_result.registration_state.assigned_hub) print(registration_result.registration_state.device_id) device_client = IoTHubDeviceClient.create_from_symmetric_key( symmetric_key=symmetric_key, hostname=registration_result.registration_state.assigned_hub, device_id=registration_result.registration_state.device_id, product_info=model_id, ) else: raise RuntimeError( "Could not provision device. Aborting Plug and Play device connection." ) elif switch == "connectionString": conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") print("Connecting using Connection String " + conn_str) device_client = IoTHubDeviceClient.create_from_connection_string( conn_str, product_info=model_id) else: raise RuntimeError( "At least one choice needs to be made for complete functioning of this sample." ) # Connect the client. await device_client.connect() ################################################ # Update readable properties from various components properties_root = pnp_helper.create_reported_properties( serialNumber=serial_number) properties_thermostat1 = pnp_helper.create_reported_properties( thermostat_1_component_name, maxTempSinceLastReboot=98.34) properties_thermostat2 = pnp_helper.create_reported_properties( thermostat_2_component_name, maxTempSinceLastReboot=48.92) properties_device_info = pnp_helper.create_reported_properties( device_information_component_name, swVersion="5.5", manufacturer="Contoso Device Corporation", model="Contoso 4762B-turbo", osName="Mac Os", processorArchitecture="x86-64", processorManufacturer="Intel", totalStorage=1024, totalMemory=32, ) property_updates = asyncio.gather( device_client.patch_twin_reported_properties(properties_root), device_client.patch_twin_reported_properties(properties_thermostat1), device_client.patch_twin_reported_properties(properties_thermostat2), device_client.patch_twin_reported_properties(properties_device_info), ) ################################################ # Get all the listeners running print("Listening for command requests and property updates") global THERMOSTAT_1 global THERMOSTAT_2 THERMOSTAT_1 = Thermostat(thermostat_1_component_name, 10) THERMOSTAT_2 = Thermostat(thermostat_2_component_name, 10) listeners = asyncio.gather( execute_command_listener(device_client, method_name="reboot", user_command_handler=reboot_handler), execute_command_listener( device_client, thermostat_1_component_name, method_name="getMaxMinReport", user_command_handler=max_min_handler, create_user_response_handler=create_max_min_report_response, ), execute_command_listener( device_client, thermostat_2_component_name, method_name="getMaxMinReport", user_command_handler=max_min_handler, create_user_response_handler=create_max_min_report_response, ), execute_property_listener(device_client), ) ################################################ # Function to send telemetry every 8 seconds async def send_telemetry(): print("Sending telemetry from various components") while True: curr_temp_ext = random.randrange(10, 50) THERMOSTAT_1.record(curr_temp_ext) temperature_msg1 = {"temperature": curr_temp_ext} await send_telemetry_from_temp_controller( device_client, temperature_msg1, thermostat_1_component_name) curr_temp_int = random.randrange( 10, 50) # Current temperature in Celsius THERMOSTAT_2.record(curr_temp_int) temperature_msg2 = {"temperature": curr_temp_int} await send_telemetry_from_temp_controller( device_client, temperature_msg2, thermostat_2_component_name) workingset_msg3 = {"workingSet": random.randrange(1, 100)} await send_telemetry_from_temp_controller(device_client, workingset_msg3) send_telemetry_task = asyncio.ensure_future(send_telemetry()) # 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 if not listeners.done(): listeners.set_result("DONE") if not property_updates.done(): property_updates.set_result("DONE") listeners.cancel() property_updates.cancel() send_telemetry_task.cancel() # Finally, shut down the client await device_client.shutdown()
async def property_update(device_client, os_type, machine): print("[DEBUG] Update System Message") # get IP Address s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ipLocal = s.getsockname()[0] s.close() ipPublic = requests.get('http://ifconfig.me/ip', timeout=1).text.strip() # global root_path if os_type == "Windows": root_path = 'C:/' hostname_str = platform.node() cpuInfo = ' '.join( os.popen('wmic cpu get name').read().splitlines()[2].split()) cpuCores = psutil.cpu_count() biosManufacturer = ' '.join( os.popen('wmic bios get Manufacturer').read().splitlines() [2].split()) biosVersion = ''.join( os.popen('wmic bios get Version').read().splitlines()[2].split()) baseboardManufacturer = ''.join( os.popen('wmic baseboard get Manufacturer').read().splitlines() [2].split()) baseboardSerialNumber = ''.join( os.popen('wmic baseboard get SerialNumber').read().splitlines() [2].split()) baseboardProduct = ''.join( os.popen('wmic baseboard get Product').read().splitlines() [2].split()) osVersion = ''.join( os.popen('wmic os get Version').read().splitlines()[2].split()) osBuildNumber = ''.join( os.popen('wmic os get BuildNumber').read().splitlines()[2].split()) elif os_type == "Linux": root_path = '/' hostname_str = platform.node() osVersion = ' '.join( os.popen('hostnamectl |grep "Operating System"').read().split(':') [1].split()) osBuildNumber = ' '.join( os.popen('hostnamectl |grep "Kernel"').read().split(':') [1].split()) if "x86" in machine: cpuInfo = ' '.join( os.popen('lscpu |grep "Model name"').read().split(':') [1].split()) biosManufacturer = ' '.join( os.popen('cat /sys/class/dmi/id/bios_vendor').read().split()) biosVersion = ' '.join( os.popen('cat /sys/class/dmi/id/bios_version').read().split()) baseboardManufacturer = ' '.join( os.popen('cat /sys/class/dmi/id/board_vendor').read().split()) baseboardSerialNumber = ' '.join( os.popen( 'sudo cat /sys/class/dmi/id/board_serial').read().split()) baseboardProduct = ' '.join( os.popen('cat /sys/class/dmi/id/board_name').read().split()) # Linux Only highTemp = psutil.sensors_temperatures()['coretemp'][0][2] criticalTemp = psutil.sensors_temperatures()['coretemp'][0][3] else: biosManufacturer = 'N/A' biosVersion = 'N/A' baseboardManufacturer = 'N/A' baseboardSerialNumber = 'N/A' baseboardProduct = 'N/A' try: cpuInfo = ' '.join( os.popen('lscpu |grep "Model name"').read().split(':') [1].split()) except: cpuInfo = machine try: highTemp = psutil.sensors_temperatures()['soc-thermal'][0][2] criticalTemp = psutil.sensors_temperatures( )['soc-thermal'][0][3] except: highTemp = 0 criticalTemp = 0 cpuCores = psutil.cpu_count() cpuMaxfreq = psutil.cpu_freq().max logicalDISKtotal = psutil.disk_usage(root_path).total memTotal = psutil.virtual_memory().total # Print Property result print('============================') print('Property List Upodate >>>>>>') print("OS type : {os}".format(os=os_type)) print("OS Version : {osV}".format(osV=osVersion)) print("OS Build/Kernel : {osK}".format(osK=osBuildNumber)) print("Hostname : {host}".format(host=hostname_str)) print("CPU Info : {cpu}".format(cpu=cpuInfo)) print("CPU Core Count : {cpus}".format(cpus=cpuCores)) print("CPU Max Frequency : {cpuMF}".format(cpuMF=cpuMaxfreq)) if os_type == "Linux": print("> CPU High Temp : {cpu_ht} Ce".format(cpu_ht=highTemp)) print("> CPU Critical : {cpu_ct} Ce".format(cpu_ct=criticalTemp)) print("BIOS Manufature : {biosM}".format(biosM=biosManufacturer)) print("BIOS Version : {biosV}".format(biosV=biosVersion)) print("Board Manufature : {boardM}".format(boardM=baseboardManufacturer)) print("Board Product : {boardP}".format(boardP=baseboardProduct)) print( "Board SerialNumber : {boardSN}".format(boardSN=baseboardSerialNumber)) print("System DISK size : {diskSZ}".format(diskSZ=logicalDISKtotal)) print("Memory size : {memSZ}".format(memSZ=memTotal)) print("Local IP Address : {ip}".format(ip=ipLocal)) print("Public IP Address : {ip}".format(ip=ipPublic)) # For Multiple components if os_type == "Windows": properties_device_info = pnp_helper.create_reported_properties( windows_device_info_component_name, hostname=hostname_str, cpuInfo=cpuInfo, cpuCores=cpuCores, cpuMaxfreq=cpuMaxfreq, biosManufacturer=biosManufacturer, biosVersion=biosVersion, baseboardManufacturer=baseboardManufacturer, baseboardSerialNumber=baseboardSerialNumber, baseboardProduct=baseboardProduct, osVersion=osVersion, osBuildNumber=osBuildNumber, memTotal=memTotal, logicalDISKtotal=logicalDISKtotal, ipLocal=ipLocal, ipPublic=ipPublic, ) elif os_type == "Linux": properties_device_info = pnp_helper.create_reported_properties( linux_device_info_component_name, hostname=hostname_str, cpuInfo=cpuInfo, cpuCores=cpuCores, cpuMaxfreq=cpuMaxfreq, biosManufacturer=biosManufacturer, biosVersion=biosVersion, baseboardManufacturer=baseboardManufacturer, baseboardSerialNumber=baseboardSerialNumber, baseboardProduct=baseboardProduct, osVersion=osVersion, osBuildNumber=osBuildNumber, memTotal=memTotal, logicalDISKtotal=logicalDISKtotal, ipLocal=ipLocal, ipPublic=ipPublic, highTemp=highTemp, criticalTemp=criticalTemp, ) global property_updates property_updates = asyncio.gather( device_client.patch_twin_reported_properties(properties_device_info), )
async def main(): switch = os.getenv("IOTHUB_DEVICE_SECURITY_TYPE") if switch == "DPS": provisioning_host = (os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT") if os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT") else "global.azure-devices-provisioning.net") id_scope = os.getenv("DPS_IDSCOPE") registration_id = os.getenv("DPS_DEVICE_ID") symmetric_key = os.getenv("DPS_SYMMETRIC_KEY") registration_result = await provision_device(provisioning_host, id_scope, registration_id, symmetric_key, model_id) if registration_result.status == "assigned": print("Device was assigned") print(registration_result.registration_state.assigned_hub) print(registration_result.registration_state.device_id) device_client = IoTHubDeviceClient.create_from_symmetric_key( symmetric_key=symmetric_key, hostname=registration_result.registration_state.assigned_hub, device_id=registration_result.registration_state.device_id, product_info=model_id, ) else: raise RuntimeError( "Could not provision device. Aborting Plug and Play device connection." ) elif switch == "ConnectionString": conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") print("Connecting using Connection String " + conn_str) device_client = IoTHubDeviceClient.create_from_connection_string( conn_str, product_info=model_id) else: raise RuntimeError( "At least one choice needs to be made for complete functioning of this sample." ) # Connect the client. await device_client.connect() ################################################ # Update readable properties from various components properties_root = pnp_helper.create_reported_properties( manufacturer="Pi Fundation") properties_RaspberryPi = pnp_helper.create_reported_properties( component_name_1, manufacturer="OKdo") properties_SenseHat = pnp_helper.create_reported_properties( component_name_2, manufacturer="Pi Fundation") property_updates = asyncio.gather( device_client.patch_twin_reported_properties(properties_root), device_client.patch_twin_reported_properties(properties_RaspberryPi), device_client.patch_twin_reported_properties(properties_SenseHat), ) ################################################ # Get all the listeners running print("Listening for command requests and property updates") listeners = asyncio.gather( execute_command_listener( device_client, component_name_1, method_name="show_text", user_command_handler=led_text_handler, create_user_response_handler=create_led_text_report_response, ), execute_command_listener( device_client, component_name_2, method_name="reboot", user_command_handler=reboot_handler, create_user_response_handler=create_reboot_report_response, ), execute_property_listener(device_client), ) ################################################ # Function to send telemetry every 8 seconds async def send_telemetry(): print("Sending telemetry from SenseHat") while True: temperature_hts221 = sense.get_temperature() humidity = sense.get_humidity() temperature_lps25h = ( (sense.get_temperature_from_pressure() / 5) * 9) + 32 pressure = sense.get_pressure() orientation_rad = sense.get_orientation_radians() lsm9ds1_accelerometer = sense.get_accelerometer_raw() lsm9ds1_gyroscope = sense.get_gyroscope_raw() lsm9ds1_compass = sense.get_compass_raw() imu_yaw = orientation_rad['yaw'] imu_roll = orientation_rad['roll'] imu_pitch = orientation_rad['pitch'] lsm9ds1_compass_x = lsm9ds1_compass['x'] lsm9ds1_compass_y = lsm9ds1_compass['y'] lsm9ds1_compass_z = lsm9ds1_compass['z'] lsm9ds1_gyroscope_x = lsm9ds1_gyroscope['x'] lsm9ds1_gyroscope_y = lsm9ds1_gyroscope['y'] lsm9ds1_gyroscope_z = lsm9ds1_gyroscope['z'] lsm9ds1_accelerometer_x = lsm9ds1_accelerometer['x'] lsm9ds1_accelerometer_y = lsm9ds1_accelerometer['y'] lsm9ds1_accelerometer_z = lsm9ds1_accelerometer['z'] temperature_cpu = float( os.popen('vcgencmd measure_temp').read()[5:9]) cpu_volt = float(os.popen('vcgencmd measure_volts').read()[5:9]) # telemetry_msg1 = {"temperature_hts221": temperature_hts221,"humidity": humidity,"temperature_lps25h": temperature_lps25h,"pressure": pressure,"imu": orientation_rad,"lsm9ds1_accelerometer": lsm9ds1_accelerometer,"lsm9ds1_gyroscope": lsm9ds1_gyroscope,"lsm9ds1_compass": lsm9ds1_compass} telemetry_msg1 = { "temperature_hts221": temperature_hts221, "humidity": humidity, "temperature_lps25h": temperature_lps25h, "pressure": pressure, "imu_yaw": imu_yaw, "imu_roll": imu_roll, "imu_pitch": imu_pitch, "lsm9ds1_accelerometer_x": lsm9ds1_accelerometer_x, "lsm9ds1_accelerometer_y": lsm9ds1_accelerometer_y, "lsm9ds1_accelerometer_z": lsm9ds1_accelerometer_z, "lsm9ds1_gyroscope_x": lsm9ds1_gyroscope_x, "lsm9ds1_gyroscope_y": lsm9ds1_gyroscope_y, "lsm9ds1_gyroscope_z": lsm9ds1_gyroscope_z, "lsm9ds1_compass_x": lsm9ds1_compass_x, "lsm9ds1_compass_y": lsm9ds1_compass_y, "lsm9ds1_compass_z": lsm9ds1_compass_z } telemetry_msg2 = { "temperature_cpu": temperature_cpu, "voltage_cpu": cpu_volt } await send_telemetry_from_pi_sensehat(device_client, telemetry_msg1, component_name_1) await send_telemetry_from_pi_sensehat(device_client, telemetry_msg2, component_name_2) await device_client.patch_twin_reported_properties( {"manufacturer": "Pi Fundation"}) await asyncio.sleep(8) send_telemetry_task = asyncio.create_task(send_telemetry()) # 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 if not listeners.done(): listeners.set_result("DONE") if not property_updates.done(): property_updates.set_result("DONE") listeners.cancel() property_updates.cancel() send_telemetry_task.cancel() # finally, disconnect await device_client.disconnect()