Jump toUpdate content
Triggering functions from IoT Hub messages
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.
Instruct your IoT Hub to trigger your function when a message is published on the
my/super/topictopic. To do so we will use an IoT Hub REST Route.
Click the Routes tab of your IoT Hub.
Create a new route with the following settings:
- Name: any name you want
- Route type: REST Query
- Endpoint: the Function endpoint you got earlier
- HTTP Headers: leave empty
In a typical use-case, the same Function will be used for many topics. It is possible to achieve this 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.
MQTT Webclientbutton on your device information page. The client will open and automatically connect.
Publish a message to the
my/super/topictopic. In the
my/super/topicas the topic
- Leave QoS as 0
- Leave Retain unticked
Hello World !as the message
Publish(no confirmation will be issued)
You can see your published message in the function logs.Note:
There may be a few minutes delay before the logs show up.
In many cases, your Function will want to publish a message to react to the received message.
To allow this action, add an
X-Mqtt-Topic header to your reply, and a new message will be published on your IoT Hub under the topic.
The content of the message will be the body of the reply.
The HTTP status code needs to be in the 2xx range.
If you require authentication to protect your Serverless Function, here is how to do it:
Click the settings tab of your function settings tab and tick the
Generate a token for your function.
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!