http trigger to mqtt message code example

Example: http trigger to mqtt message

[FunctionName("SendMessageFunction")]
        public static ActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "v1/test/led")] HttpRequest req,
            [Mqtt] out IMqttMessage outMessage,         // hij haald automatisch de default connectionstring 'MqttConnection' uit local.settings.json
            ILogger logger)
        {               
            try
            {
                string requestBody = new StreamReader(req.Body).ReadToEnd();            // niet async want mqtt libary werkt daar niet mee
                outMessage = new MqttMessage("/pc/led", Encoding.ASCII.GetBytes(requestBody), MqttQualityOfServiceLevel.AtLeastOnce, true);
                return new StatusCodeResult(200);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                outMessage = null;
                return new StatusCodeResult(500);
            }
        }

Tags:

Misc Example