Triggering functions from IoT Hub messages

Function as a Service - Overview

Function as a Service allows developers to run code without the hassle of managing the server/instance running it.

IoT Hub allows messages to be exchanged between devices and business-specific software. Some or all components of this software can be implemented using Function as a Service, and IoT Hub can be configured to trigger these functions to process messages being exchanged on the Hub.

Here is how to do it. We are going to:

  • Create a Serverless Function
  • Create an IoT Hub and add a Device
  • Set up an IoT Hub Route to the Serverless Function
  • Publish messages on the IoT Hub and see the Function being triggered

Create a Serverless Function

First, we need to create a Function we want to be triggered by IoT Hub. You’ll first need to create a Serverless namespace in your Scaleway console. Choose a name for the namespace and leave everything else at their default values.

Once this is done we can create a Function in it. Use inline code editor and python3 runtime, paste the following code in the editor.

def handle(event, context):
        print("Message received (topic={}): {}".format(event["headers"]["X-Mqtt-Topic"], event["body"]))
    except Exception as ex:
        print("An error occured: {}".format(ex))
    return {
        "statusCode": 200,

Then choose a Function name, leave all other settings untouched and create the function.

In the Functions Settings tab of the newly created function, there is a Function Endpoint field, write it down for later.

Create an IoT Hub and add a Device

Now we have the function ready, we need to create an IoT Hub. This will be where our simulated IoT Device will publish messages intended to trigger the function we just created. Please follow this procedure to create an IoT Hub. Choose any name and any plan you wish, and click the Create Hub and Add a Device button.

We now need to add a Device to the IoT Hub to publish the messages which will trigger the Function. We will use the generated credentials to connect to the Hub and publish the messages. Give it the name you want. Please choose the allow insecure connection setting to keep things simple for this tutorial. In a production environment you will most probably want to deny insecure connections. Once done click the Add a Device to your Hub button.

On the next page, write down the Device ID, you will need it to connect your simulated Device. Then click the Close button.

Now go to the Networks tab of your Hub and write down the endpoint to your IoT Hub for later.

Set up an IoT Route to our Serverless Function

Here is where the magic happens, we will instruct our IoT Hub to trigger our Serverless Function when some message is published on the my/super/topic topic. To do so we will use an IoT Hub REST Route. In Scaleway console, head to the Routes tab of your IoT Hub. Create a new route with the following settings:

  • Name: any name you want
  • Topic: my/super/topic
  • Route type: REST Query
  • Method: POST
  • Endpoint: the Function endpoint you got earlier
  • HTTP Headers: leave empty

In a typical use-case, the same Serverless Function will be used for many topics. We can easily achieve that by using MQTT wildcards in the Route topic. You can then rely on the X-Mqtt-Topic HTTP header in your Serverless Function for your topic-based processing. Please see this blog post for more information about MQTT topics.

Trigger the Function

Now we have set up the function, the hub, and the route, let’s try to trigger the Function from an MQTT client.

On the Device page for the Device you added earlier, click the MQTT Webclient button. The client will open and automatically connect. Now let’s publish a message to the my/super/topic topic, in the Publish block:

  • Write my/super/topic as the topic
  • Leave QoS as 0
  • Leave Retain unticked
  • Write Hello World ! as the message
  • Click Publish (no confirmation will be issued)

Now we have published a message, we should see it in the Function logs. In your Scaleway console, head to the Function Logging tab of your Serverless Function.

Here you should see a line containing the following contents: Message received (topic=my/super/topic): Hello World!. Please note there may be a few minutes delay before the logs show up.

Congratulations, your function can now be automagically triggered from an IoT Device!

Going further: replying with a new message

In many cases, your Serverless Function will want to publish a message to react to the received message. This is super easy!

Simply add an X-Mqtt-Topic header to your reply, and a new message will be published on your IoT Hub under this topic. The message’s contents will be the reply’s body. Needless to say, HTTP status code needs to be in the 2xx range.

Going further: using Private Functions

This one is a bit technical as it will have you call the Scaleway API manually.

If you require authentication to protect your Serverless Function, here is how to do it:

  • Go to your Scaleway console, head to your Serverless Function’s settings tab and tick the Private option
  • Generate a token for your function, here is how to do it
  • Re-create your IoT Hub Route with the following HTTP header: SCW_FUNCTIONS_TOKEN: <function token here>

Your Function is now private and still accessible from IoT Hub!

We're done!

We hope you had fun connecting your IoT Hub to your Serverless Function. This is one of the many possibilities the IoT Hub REST Route provides. Stay tuned for more REST Route usage examples.

Learn more about Scaleway IoT Hub, discover how to add Devices to the hub, check the IoT Hub metrics or get started in a few clicks with the IoT Hub Kickstarts.

Discover the Cloud That Makes Sense