-
Notifications
You must be signed in to change notification settings - Fork 7
IoT Hub Direct Methods
Code example, working with Direct Methods
- Set ID Scope
- Set Allowed connections
- Set DeviceAuthentication
Direct method response code
typedef enum
{
DX_METHOD_SUCCEEDED = 200,
DX_METHOD_FAILED = 500,
DX_METHOD_NOT_FOUND = 404
} DX_DIRECT_METHOD_RESPONSE_CODE;
void dx_directMethodUnsubscribe(void);
void dx_directMethodSubscribe(DX_DIRECT_METHOD_BINDING* directMethods[], size_t directMethodCount);
Direct method context structure.
typedef struct _directMethodBinding {
const char *methodName;
DX_DIRECT_METHOD_RESPONSE_CODE (*handler)(JSON_Value *json, struct _directMethodBinding *peripheral, char **responseMsg);
void *context;
} DX_DIRECT_METHOD_BINDING;
DX_DIRECT_METHOD_HANDLER(name, json, directMethodBinding, responseMsg)
DX_DIRECT_METHOD_HANDLER_END
DX_DECLARE_DIRECT_METHOD_HANDLER(name)
Azure IoT Hub and IoT Central use direct method commands to invoke an action on a device. Commands are often used for interactive control of devices, such as turning on a fan, a light, or in the case of this unit, to restart the Azure Sphere.
IoT Hub direct methods represent a request-reply interaction with a device similar to an HTTP call in that they succeed or fail immediately (after a user-specified timeout). This approach is useful for scenarios where the course of immediate action is different depending on whether the device was able to respond.
There are a number of reasons why you might need to remote restart a Azure Sphere. Device certificates, OS updates, and application updates are done on a 24 hour cycle or after the device has been restarted. You may have an operational reason why you need to restart the device to force an update.
From the IoT Explorer, or your own application, you can invoke a direct method command to restart the device. You need to set the number of seconds the device will wait before restarting. Azure IoT Hub sends a direct method message with an optional payload to the device. The device responds with a status code and optionally a message indicating if the command succeeded or failed.
The following steps outline how Azure IoT Explorer and Azure IoT Hub direct methods are used for cloud-to-device control.
- From Azure IoT Explorer you can invoke the Restart Device IoT Hub direct method command.
- Azure IoT Hub then sends the direct method command message to the device.
- On the Azure Sphere, the RestartDeviceHandler function is called.
- Next the device sends a device twin ReportedRestartUTC message to Azure IoT to record the time the device was restarted.
- The direct method responds with an HTTP status code and a response message.
- The Azure Sphere is then restarted.
- Azure IoT Explorer queries and displays the device ReportedRestartUTC property.
A direct method binding maps an IoT Hub direct method command name with a handler function that will be called to implement the action.
The following example declares a Direct Method Binding to restart the Azure Sphere. This declaration maps the Azure IoT Hub RestartDevice
direct method command with a handler function named RestartDeviceHandler
.
// Forward declaration of Direct Method handler
static DX_DECLARE_DIRECT_METHOD_HANDLER(RestartDeviceHandler);
static DX_DIRECT_METHOD_BINDING dm_restartDevice = {
.methodName = "RestartDevice",
.handler = RestartDeviceHandler };
The following is the implementation of the handler function RestartDeviceHandler
. The handler function is called when the device receives a direct method message named RestartDevice
from Azure IoT Hub.
/// <summary>
/// Start Device Power Restart Direct Method 'ResetMethod' integer seconds eg 5
/// </summary>
static DX_DIRECT_METHOD_HANDLER(RestartDeviceHandler, json, directMethodBinding, responseMsg)
{
// Allocate and initialize a response message buffer. The
// calling function is responsible for the freeing memory
const size_t responseLen = 100;
static struct timespec period;
*responseMsg = (char *)malloc(responseLen);
memset(*responseMsg, 0, responseLen);
if (json_value_get_type(json) != JSONNumber) {
return DX_METHOD_FAILED;
}
int seconds = (int)json_value_get_number(json);
// leave enough time for the device twin dt_reportedRestartUtc
// to update before restarting the device
if (seconds > 2 && seconds < 10) {
// Create Direct Method Response
snprintf(*responseMsg, responseLen, "%s called. Restart in %d seconds",
directMethodBinding->methodName, seconds);
// Set One Shot DX_TIMER_BINDING
period = (struct timespec){.tv_sec = seconds, .tv_nsec = 0};
dx_timerOneShotSet(&restart_device_oneshot_timer, &period);
return DX_METHOD_SUCCEEDED;
} else {
snprintf(*responseMsg, responseLen, "%s called. Restart Failed. Seconds out of range: %d",
directMethodBinding->methodName, seconds);
return DX_METHOD_FAILED;
}
}
DX_DIRECT_METHOD_HANDLER_END
The RestartDeviceHandler function sets up a one-shot timer that invokes the DelayRestartDeviceTimerHandler function after the specified restart period measured in seconds. In the DelayRestartDeviceTimerHandler function a call is made to the PowerManagement_ForceSystemReboot API. The PowerManagement_ForceSystemReboot API requires the PowerControls capability to be declared in the app_manifest.json file.
"PowerControls": [
"ForceReboot"
]
All declared direct method bindings must be added by reference to the directMethodBindingSet array. When a direct method message is received by the device from Azure IoT Hub, it is checked for a matching methodName name in the directMethodBindingSet array. When a match is found, the corresponding handler function is called.
DX_DIRECT_METHOD_BINDING *direct_method_bindings[] = {&dm_restart_device };
The direct method binding set is initialized in the InitPeripheralsAndHandlers function in main.c.
dx_directMethodSubscribe(direct_method_bindings, NELEMS(direct_method_bindings));
The direct method bindings set is closed in the ClosePeripheralsAndHandlers function in main.c.
dx_directMethodUnsubscribe();
AzureSphereDevX Examples Wiki
- Home
- Build Tools
- Adding the DevX library
- Azure IoT Hub Messaging
- Azure IoT Hub Device Twins
- Azure IoT Hub Direct Methods
- Avnet IoT Connect messaging
- Handling multithreaded async events
- Working with GPIO
- Working with UARTS
- Working with PWM
- Working with Event Timers
- Intercore Messaging
- Application termination
- Deferring updates
- Utility functions
- Tools and scripts
- Hardware Definitions