restazure-iot-hubazure-iot-central

Sending commands to an IoT device via REST and IoT Central


Microsoft describes very well how to send a command to an IoT device using a REST call. (https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-direct-methods)

This also works as described with an IoT Hub.

In the Microsoft example, a command is sent via

az iot hub generate-sas-token -n <iothubName> --du <duration>

a corresponding SAS token is generated. Unfortunately, this does not work with IoT Central, as the host name of the IoT Hub on which it is based is not known.

I have now been able to determine the IoT Hub via the DPS and have also generated a corresponding SAS token for my device. With this, it is also possible to send data to the device.

In the Microsoft example, however, the SAS token looks different:

  https://<iothubName>.azure-devices.net/twins/<deviceId>/methods?api-version=2021-04-12\
  -H 'Authorization: SharedAccessSignature sr=iothubname.azure-devices.net&sig=x&se=x&skn=iothubowner' \
  -H 'Content-Type: application/json' \
  -d '{
    }, "methodName": "reboot",
    "responseTimeoutInSeconds": 200,
    "payload": {
        "input1": "someInput",
        "input2": "anotherInput"
    }
}'

If I compare this with my SAS tokens, I notice that they are completely different. What is the reason for this and where can I get the SAS token with which I can initiate commands?


Solution

  • Azure IoT Central didn't allow full REST APIs access to the underlying IoT Hub, just only for sending an event (telemetry data).

    You should use the Azure IoT Central REST Devices - Run Command for that. For Authorization header can be used the IoT Central ApiToken.

    Note, that this Run Command also can be used for sending a C2D message to the device via the IoT Central based on the device model, see the Offline commands.