from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import CloudToDeviceMethod, CloudToDeviceMethodResult CONNECTION_STRING = "HostName=AgriHub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=v0auIwbmqfBDz3BY8aZtbnOzg8+6119LWylk1Jq1G0A=" DEVICE_ID = "Guard_Node_00001" METHOD_PAYLOAD = "server_to_device_message" def send_to_device(request_name): try: # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(CONNECTION_STRING) # Call the direct method. deviceMethod = CloudToDeviceMethod(method_name=request_name, payload=METHOD_PAYLOAD) print ( "Device Method called" ) print ( "Device Method name : {0}".format(request_name) ) print ( "Device Method payload : {0}".format(METHOD_PAYLOAD) ) response = registry_manager.invoke_device_method(DEVICE_ID, deviceMethod) print ( "Response status : {0}".format(response.status) ) print ( "Response payload : {0}".format(response.payload) ) except Exception as ex: print ( "Unexpected error {0}".format(ex) ) return except KeyboardInterrupt: print ( "IoTHubDeviceMethod sample stopped" )