Skip to content

Subscribe via trigger

Kees Schollaart edited this page Apr 15, 2018 · 5 revisions

Trigger Binding

  • Add the MqttTriggerAttribute to one of your functions parameters
  • Use one of the constructor overloads to configure
    • The first/simple constructor only requires one or more topic-names (eg: "my/topic/#")
    • The second (more advanced) constructor requires a Type which you then have to implement more on this
  • Make sure the type of the parameter is IMqttMessage

Example

This an example of a Function triggered by messages published on the "testtopic/in" topic using the simple constructor:

[FunctionName("SimpleFunction")]
public static void SimpleFunction(
        [MqttTrigger("testtopic/in")]IMqttMessage message,
        ILogger logger)
    {
        var body = message.GetMessage();
        var bodyString = Encoding.UTF8.GetString(body);
        logger.LogInformation($"{DateTime.Now:g} Message for topic {message.Topic}: {bodyString}");
    }

Connection

The connection to the MQTT broker is made when the function boots. Internally this is implemented using MQTTNet's Managed Client which manages the connections state.