Updated access to Iot Hub using Python SDK

without sensitive information this time
This commit is contained in:
Quentin WEPHRE
2024-06-21 08:28:48 +02:00
parent fe82b3962f
commit 24e471f633

View File

@@ -1,37 +1,24 @@
from azure.iot.hub import IoTHubRegistryManager
from azure.iot.hub.models import QuerySpecification
from azure.iot.hub.protocol.models.device_py3 import Device
from azure.iot.hub.protocol.models import QueryResult, QuerySpecification
import json
# Install the Azure IoT Hub SDK:
# pip install azure-iot-hub
# Authenticate to your Azure account
CONNECTION_STRING = ""
CONNECTION_STRING = "HostName=IotHub-CUBE-PROD.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey= ..."
if CONNECTION_STRING == "":
print("Provide a connection string for the Iot Hub before running the script!")
exit(13)
registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
registry_manager = IoTHubRegistryManager.from_connection_string(CONNECTION_STRING)
query_spec = QuerySpecification(query="SELECT * FROM devices WHERE tags.site = 'SASK'")
sorted_list = []
query_result = registry_manager.query_iot_hub(query_spec)
ordered_devices = []
for item in query_result.items:
ordered_devices.append([int(item.tags['number']), item.tags['deviceId']])
def custom_sort(item):
return (item[1], int(item[2]))
ordered_devices.sort()
for i in registry_manager.get_devices():
if "DIGIT" in i.device_id:
twin = registry_manager.get_twin(i.device_id)
site = twin.tags['site']
number = twin.tags['number']
status = i.connection_state
time = twin.last_activity_time
if "RUAKAKA" in site:
sorted_list.append((i.device_id, site, number, status, time))
sorted_list = sorted(sorted_list, key=custom_sort)
column_sizes = (15, 5, 25, 15, 25)
# Print the sorted list in a tabular format
for item in sorted_list:
print("{:<{}} #{:<{}} {:<{}} {:<{}} {:<{}}".format(item[1], column_sizes[0], item[2], column_sizes[1], item[0], column_sizes[2], item[3], column_sizes[3], item[4], column_sizes[4]))
for i in ordered_devices:
print(i)