blob: 75307f844c5342a83ef18613f308f9d1e12b2c53 (
plain)
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
48
49
50
51
52
53
54
55
56
57
|
using Microsoft.Azure.Devices.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core;
namespace Tango.Telemetry.Destinations
{
public class AzureHubTelemetryDestination : ExtendedObject, ITelemetryDestination
{
private DeviceClient _hubClient;
public string Name { get; private set; } = "Azure IoT Hub";
public bool Enable { get; set; } = true;
public String ConnectionString { get; private set; }
public IReadOnlyList<TelemetrySource> SupportedSources { get; private set; }
public AzureHubTelemetryDestination(String connectionString)
{
ConnectionString = connectionString;
SupportedSources = new List<TelemetrySource>() { TelemetrySource.PendingStorage, TelemetrySource.Streaming, TelemetrySource.ExternalStorage };
}
public async Task Publish(TelemetryPublishPackage package, List<KeyValuePair<String, String>> properties)
{
if (_hubClient == null)
{
_hubClient = DeviceClient.CreateFromConnectionString(ConnectionString, TransportType.Mqtt);
_hubClient.SetConnectionStatusChangesHandler((status, reason) =>
{
LogManager.Log($"IoT hub status changed to: {status}, Reason: {reason}.");
});
}
var message = new Message(Encoding.UTF8.GetBytes(package.ToPayload()))
{
ContentType = "application/json",
ContentEncoding = "utf-8"
};
foreach (var prop in properties)
{
message.Properties.Add(prop.Key, prop.Value);
}
await _hubClient.SendEventAsync(message);
}
public void Dispose()
{
_hubClient?.Dispose();
}
}
}
|