Azure Internet of Things, Cloud to Device Messaging: Method Calls, Twin Updates, and Messages
I have recently been experimenting with the Adafruit ESP8266 HUZZAH board and DHT22 Temp/Humidity sensor sending messages to and from Azure IoT Hub.
Review the excellent getting started guide here: https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-arduino-huzzah-esp8266-get-started
Using the Arduino sketch from https://github.com/Azure-Samples/iot-hub-feather-huzzah-client-app it was pretty easy to get going.
IoT Hub Callback Methods
If you examine the App.ino main sketch file, you will discover three callbacks which are coded to receive messages from Azure IoT Hub.
- IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, receiveMessageCallback, NULL);
- IoTHubClient_LL_SetDeviceMethodCallback(iotHubClientHandle, deviceMethodCallback, NULL);
- IoTHubClient_LL_SetDeviceTwinCallback(iotHubClientHandle, twinCallback, NULL);
These callbacks map to specific functions in Azure IoT Hub.
Device Twin Changes in Azure and the twinCallback
Device Twin Changes in Azure IoT Hub will invoke the callback to the device
This twinCallback method receives a string and calls the parseTwinMessage function.
parseTwinMessage will take the string, parse it into a JSON object, and look for the property desired/interval or interval. Either one will update the interval variable in the code to change the frequency at which temperature settings are sent to Azure.
This shows the serial output of the received message from Azure and the change in the device interval.
The interval variable is used in the main loop of the Arduino sketch. The interval is in milliseconds. For example, 10000 = 10 seconds.
Azure messages and receiveMessageCallback
The message constructed in Message to Device will be sent to the device.
The receiveMessageCallback will receives a message handle, from which it derives a buffer and size. The buffer is copied into a string called temp and displayed to the serial output.
The serial output shows the message. Obviously, this could be enhanced to use the content of these messages to change how the device performs it's monitoring.
Direct Method Call on the Device with deviceMethodCallback
Azure IoT Hub allows Direct Method call to the device.
The device offers two methods, start and stop. This example shows the stop method being executed. Which changes the variable messageSending to false.
The main loop of the program will not execute while messageSending = false.
The serial output verifies the stop method is called and no further messages are sent to Azure.