Background: Understand Azure IoT Hub direct methods | Microsoft Docs
Pub/Sub topics
Use the following Signetik API to set Pub, Sub topics
+set,pubtopic:devices/<deviceID>/messages/events/
+set,subtopic1:devices/<deviceID>/messages/devicebound/#
There are two steps:
- Invoke Direct Method from back end app
- Handle and Respond from Device
The particulars of invoking the direct method from back end vary widely. Here we provide examples of how to do that using IoT Hub Web UI, and az CLI.
Invoking Direct Method from IoT Hub
Navigate to Device Page on the IoT Hub, select Direct Method.
- Enter DeviceId
- Enter some string for Method Name
- Enter a valid json to be sent to device
- Select a duration for the attempt to wait for Connection to device. Choose something big for initial testing to avoid timeout.
- Select a duration for the attempt to wait for response from device. Choose something big for initial testing to avoid timeout.
- Click on Invoke Method
When a response is received from device, it will appear in the "Result" window.
Invoking Direct Method from az CLI
az iot hub invoke-device-method --device-id <deviceID> --hub-name <Hub Name> --method-name <SOME STRING> --method-payload <JSON payload>
Example
az iot hub invoke-device-method --device-id sig-test-device-2 --hub-name MyCompanyHub --method-name dm-test-1 --method-payload {\"value\":1}
Reference: Understand Azure IoT Hub direct methods | Microsoft Docs
Handle a direct method on a device using MQTT protocol
Devices receive direct method requests on the MQTT topic: $iothub/methods/POST/{method name}/?$rid={request id}
. The number of subscriptions per device is limited to 5. It is therefore recommended not to subscribe to each direct method individually. Instead consider subscribing to $iothub/methods/POST/#
and then filter the delivered messages based on your desired method names.
Method requests are QoS 0.
Response
The device sends responses to $iothub/methods/res/{status}/?$rid={request id}
, where:
-
The
status
property is the device-supplied status of method execution. -
The
$rid
property is the request ID from the method invocation received from IoT Hub.
The body is set by the device and can be any status.
In the example below: The window on left side shows device receiving a direct method and composing a response with the correct $rid and responding. The window on the right shows a case of direct method response not being sent by device in time, and then a case of a successful response received from the device.
Note that it is important to have the payload in a valid json format.
The following shows a case on device not sending a valid response. In cases like this, you would need to check the device side to ensure the response is created and sent as described above.
Comments
0 comments
Please sign in to leave a comment.