-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExampleIoTHubFunctions.cs
More file actions
47 lines (41 loc) · 1.92 KB
/
ExampleIoTHubFunctions.cs
File metadata and controls
47 lines (41 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using Microsoft.Azure.WebJobs;
using System.Text;
using Microsoft.Extensions.Logging;
using System.Linq;
using CaseOnline.Azure.WebJobs.Extensions.Mqtt.Messaging;
using CaseOnline.Azure.WebJobs.Extensions.Mqtt;
namespace ExampleFunctions
{
public static class ExampleIoTHubFunctions
{
// Attention: this function is disabled because it requires an Azure IoT Hub and a corresponding connectionstring
// To get it working, remove the [Disable] attribute on the trigger and a the "IoTHubConnectionString" to the settings
// More on IoT Hub: https://github.com/keesschollaart81/CaseOnline.Azure.WebJobs.Extensions.Mqtt/wiki/Azure-IoT-Hub
[FunctionName("CloudToDeviceMessages")]
public static void CloudToDeviceMessages(
[MqttTrigger("devices/testdevice/messages/devicebound/#", "$iothub/methods/POST/#", ConnectionString = "IoTHubConnectionString"), Disable]IMqttMessage message,
[Mqtt(ConnectionString = "IoTHubConnectionString"), Disable] out IMqttMessage response,
ILogger logger)
{
var body = message.GetMessage();
var bodyString = Encoding.UTF8.GetString(body);
logger.LogInformation($"{DateTime.Now:g} Message for topic {message.Topic}: {bodyString}");
if (message.Topic.Contains("methods"))
{
response = CloudToDeviceMethodCall(message.Topic);
}
else
{
response = null;
}
}
private static IMqttMessage CloudToDeviceMethodCall(string topic)
{
var requestId = topic.Split('=').Last();
var responseBodyString = "{}";
var responseBodyBytes = Encoding.UTF8.GetBytes(responseBodyString);
return new MqttMessage($"$iothub/methods/res/200/?$rid={requestId}", responseBodyBytes, MqttQualityOfServiceLevel.AtLeastOnce, true);
}
}
}