from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.protocol.models import QuerySpecification from azure.iot.hub.models import CloudToDeviceMethod, CloudToDeviceMethodResult from dotenv import load_dotenv import json import os load_dotenv() module_id = "thingspro-agent" method_name = "thingspro-api-v1" payload = '{"method":"GET", "path":"/device/general"}' # Install the Azure IoT Hub SDK: # pip install azure-iot-hub # Authenticate to your Azure account CONNECTION_STRING = str(os.getenv("CONNECTION_STRING_SAFT_PROD")) # CONNECTION_STRING = str(os.getenv("CONNECTION_STRING_INOX_PROD")) if CONNECTION_STRING == "": print("Provide a connection string for the Iot Hub before running the script!") exit(13) registry_manager = IoTHubRegistryManager.from_connection_string(CONNECTION_STRING) query_spec = QuerySpecification(query="SELECT * FROM devices WHERE IS_DEFINED(tags.site) AND capabilities.iotEdge = true") query_result = registry_manager.query_iot_hub(query_spec) devices = [] for item in query_result.items: number = int(-1) deviceId = "null" site = "null" if item.tagss['number']: number = int(item.tags['number']) if item.tags['deviceId']: deviceId = item.tags['deviceId'] if item.tags['site']: site = item.tags['site'] devices.append([int(item.tags['number']), item.tags['deviceId'], item.tags['site']]) ordered_devices = sorted(devices, key = lambda x: (x[2], x[0])) for i in ordered_devices: current_device_modules = registry_manager.get_modules(i[1]) for module in current_device_modules: if module.module_id == module_id: thingspro_module = module if thingspro_module: #print("Found thingspro-agent for " + i[1] + " (" + i[2] + ")") try: direct_method = CloudToDeviceMethod(method_name=method_name, payload=json.loads(payload)) response = registry_manager.invoke_device_module_method(device_id=i[1], module_id=module_id, direct_method_request=direct_method) #print(response.payload) if str(i[1]) == str(response.payload['data']['hostName']): print(str(i[2]), str(i[0]), str(i[1]), response.payload['data']['description'], response.payload['data']['firmwareVersion'], sep=";") else: print(str(i[2]), str(i[0]), str(i[1]), response.payload['data']['description'], response.payload['data']['hostName'], response.payload['data']['firmwareVersion'], sep=";") except: print(str(i[2]), str(i[0]), str(i[1]), "UNREACHABLE",sep=";") else: print("No thingspro-agent available for " + i[1] + " (" + i[2] + ")")