Skip to content

Azure IoT Hub

Kees Schollaart edited this page Apr 16, 2018 · 6 revisions

It is possible to act as an Azure IoT Hub device using an Azure Function. On the device side of IoT Hub, IoT Hub acts as a MQTT Broker. Using this package you can subscribe to Cloud-To-Device messages and publish Device-To-Cloud messages.

To do this, we need a per-device connectionstring which can not be found in the Azure Portal, read here how to do this. During development these tokens can easily be created using the Device Explorer.

How to use IoT Hub as a MQTT Broker is well documented at this page.

This is what a MQTT connectionstring to IoT Hub looks like:

Server=<<iothub-host>>.azure-devices.net;Tls=true;Username=<<iothub-host>>.azure-devices.net/<<deviceid>>/api-version=2016-11-14;Password=SharedAccessSignature sr=<<iothub-host>>.azure-devices.net%2Fdevices%2F<<deviceid>>&sig=<<sig>>&se=<<se>>;ClientId=<<deviceid>>;

Example implementation

This function shows how to process messages and method calls from IoT Hub. They are implemented in the example project

[FunctionName("CloudToDeviceMessages")]
public static void CloudToDeviceMessages(
    [MqttTrigger("devices/testdevice/messages/devicebound/#", "$iothub/methods/POST/#"]IMqttMessage message,
    [Mqtt] out IMqttMessage response,
    ILogger logger)
{
    var body = message.GetMessage();
    var bodyString = Encoding.UTF8.GetString(body);
    logger.LogInformation($"{DateTime.Now:g} Message for topic {message.Topic}: {bodyString}");

    if (message.Topic.Contains("methods"))
    {
        response = CloudToDeviceMethodCall(message.Topic, bodyString);
    }
    else
    {
        response = null;
    }
}

private static IMqttMessage CloudToDeviceMethodCall(string topic, string message)
{
    var requestId = topic.Split('=').Last();

    var responseBodyString = "{}";
    var responseBodyBytes = Encoding.UTF8.GetBytes(responseBodyString);

    return new MqttMessage($"$iothub/methods/res/200/?$rid={requestId}", responseBodyBytes, MqttQualityOfServiceLevel.AtLeastOnce, true);
}