Using an Azure Function to receive MQTT Messages

The video shows me pressing a button on my Air Quality sensor to trigger the sensor to send a new reading via MQTT. The action then switches to the output of an Azure Function running on my PC which is responding to this. I’m very pleased with this.

MQTT (Message Queuing Telemetry Transport) is a neat way to connect embedded devices together. I’ve used it to talk to the Hull Pixelbot devices over the internet using Azure IOT Hub. Using MQTT in this way has meant that my server applications can send commands to the robots to tell them what to do, and also receive messages back.

Creating a server application is all very well, but it is a bit too much like hard work for me when I’m writing code for the Air Quality sensors. In that situation I don’t really want to have a server application sitting in the cloud twiddling its digital thumbs while it is waiting for incoming messages.

What I really want is a way of connecting a lump of code (ideally a C# method) to the event “Hey out there. I’ve got a new Air Quality Reading”. It turns out that Azure Functions just do this. You deploy the function into the cloud and bind it to the Azure IOT Hub and the endpoint that you want it to listen to. And then, whenever your remote node (which could be anywhere in the world) wants to send a message it posts an MQTT update and your function runs.

This is my function at the moment:

[FunctionName("SensorMQTTReceiver")]
public static void Run([IoTHubTrigger("devices/#",
Connection = "IoTHubConnectionString")]EventData message, ILogger log)
{
    log.LogInformation(
$"C# IoT Hub message: {Encoding.UTF8.GetString(message.Body.Array)}"
}

I stole most of how to do this from a very useful howto here. The next thing to do is add some code to the function that puts the data values from the post into a data store and perhaps add handling of alerts if we see air quality values which are out of range.

The next thing to do is build a similar mechanism to process LoRa updates sent via the things network.