from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.protocol.models import QuerySpecification from azure.iot.hub.models import CloudToDeviceMethod, CloudToDeviceMethodResult import json 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 = "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.from_connection_string(CONNECTION_STRING) query_spec = QuerySpecification(query="SELECT * FROM devices WHERE tags.site = 'MYRTLE' AND tags.number != '0' AND capabilities.iotEdge = true") query_result = registry_manager.query_iot_hub(query_spec) devices = [] for item in query_result.items: 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] + ")")