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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
|
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Logging;
namespace Tango.Telemetry.Destinations
{
/// <summary>
/// Represents a telemetry destination that publishes telemetry data to Azure IoT Hub using MQTT transport.
/// Supports batching, source type filtering, and connection status tracking.
/// </summary>
public class TelemetryAzureHubDestination : ExtendedObject, ITelemetryDestination
{
private DeviceClient _hubClient;
private int _batchSize;
private ConcurrentList<Message> _batch;
private class ADXPAckage
{
public String Type { get; set; }
public String Environment { get; set; }
public String MachineType { get; set; }
public String SerialNumber { get; set; }
public String Organization { get; set; }
public String Site { get; set; }
public ITelemetry Telemetry { get; set; }
public DateTime UploadTime { get; set; }
public DateTime CreatedTime { get; set; }
public int Version { get; set; }
public String ToPayload()
{
return JsonConvert.SerializeObject(this, Formatting.None);
}
}
/// <summary>
/// Gets or sets the name of the destination.
/// </summary>
public string Name { get; set; } = "Azure IoT Hub";
/// <summary>
/// Gets the connection string used to connect to Azure IoT Hub.
/// </summary>
public string ConnectionString { get; private set; }
/// <summary>
/// Gets the current connection status of the Azure IoT Hub client.
/// </summary>
public ConnectionStatus HubConnectionStatus { get; private set; }
/// <summary>
/// Gets the source types supported by this destination.
/// </summary>
public IReadOnlyList<TelemetrySourceTypes> SupportedSourceTypes { get; private set; }
/// <summary>
/// Gets or sets the maximum number of messages to send in a single batch.
/// The value is clamped between 1 and 100.
/// </summary>
public int BatchSize { get => _batchSize; set => _batchSize = Math.Min(Math.Max(1, value), 10); }
/// <summary>
/// Prevents a default instance of the <see cref="TelemetryAzureHubDestination"/> class from being created.
/// </summary>
private TelemetryAzureHubDestination()
{
_batch = new ConcurrentList<Message>();
HubConnectionStatus = ConnectionStatus.Connected;
SupportedSourceTypes = new List<TelemetrySourceTypes>()
{
TelemetrySourceTypes.PendingStorage,
TelemetrySourceTypes.Streaming,
TelemetrySourceTypes.ExternalStorage
};
BatchSize = 1;
}
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryAzureHubDestination"/> class with the specified connection string.
/// </summary>
/// <param name="connectionString">The Azure IoT Hub connection string.</param>
public TelemetryAzureHubDestination(string connectionString) : this()
{
ConnectionString = connectionString;
}
/// <summary>
/// Determines whether the destination is currently available for publishing.
/// </summary>
/// <returns>True if the destination is available; otherwise, false.</returns>
public Task<bool> IsAvailable()
{
if (_hubClient == null)
{
return Task.FromResult(true);
}
else
{
return Task.FromResult(HubConnectionStatus == ConnectionStatus.Connected);
}
}
/// <summary>
/// Publishes a telemetry package to Azure IoT Hub.
/// Supports batching when <see cref="BatchSize"/> is greater than 1.
/// </summary>
/// <param name="package">The telemetry package to publish.</param>
/// <param name="properties">A list of properties to include with the message.</param>
public async Task Publish(TelemetryPublishPackage package, List<KeyValuePair<string, string>> properties)
{
if (_hubClient == null)
{
_hubClient = DeviceClient.CreateFromConnectionString(ConnectionString, TransportType.Mqtt);
_hubClient.SetConnectionStatusChangesHandler((status, reason) =>
{
HubConnectionStatus = status;
LogManager.Log($"IoT hub status changed to: {status}, Reason: {reason}.", LogCategory.Info);
});
}
ADXPAckage adxPackage = new ADXPAckage();
adxPackage.Type = package.TelemetryName;
adxPackage.Version = package.TelemetryVersion;
adxPackage.Environment = package.Environment;
adxPackage.MachineType = package.MachineType;
adxPackage.SerialNumber = package.SerialNumber;
adxPackage.Organization = package.Organization;
adxPackage.Site = package.Site;
adxPackage.UploadTime = DateTime.UtcNow;
adxPackage.CreatedTime = package.PendingTelemetry.TelemetryObject.Time;
adxPackage.Telemetry = package.PendingTelemetry.TelemetryObject;
var message = new Message(Encoding.UTF8.GetBytes(adxPackage.ToPayload()))
{
ContentType = "application/json",
ContentEncoding = "utf-8"
};
foreach (var prop in properties)
{
message.Properties.Add(prop.Key, prop.Value);
}
if (BatchSize > 1)
{
_batch.Add(message);
if (_batch.Count >= BatchSize)
{
LogManager.Log($"Sending telemetry batch of {_batch.Count} messages to Azure IoT Hub.", LogCategory.Debug);
await _hubClient.SendEventBatchAsync(_batch.ToList());
_batch.Clear();
}
else
{
LogManager.Log($"Queued telemetry message for batching. {_batch.Count}/{BatchSize} currently queued.", LogCategory.Debug);
}
}
else
{
LogManager.Log("Sending single telemetry message to Azure IoT Hub.", LogCategory.Debug);
await _hubClient.SendEventAsync(message);
}
}
/// <summary>
/// Disposes the destination and ensures any remaining batched messages are sent.
/// </summary>
public void Dispose()
{
if (_hubClient != null && _batch.Count > 0)
{
LogManager.Log($"Flushing {_batch.Count} remaining messages to Azure IoT Hub.", LogCategory.Info);
_hubClient.SendEventBatchAsync(_batch.ToList()).GetAwaiter().GetResult();
_batch.Clear();
}
_hubClient?.Dispose();
}
/// <summary>
/// Returns a string that represents the current destination instance.
/// </summary>
/// <returns>The name of the destination.</returns>
public override string ToString()
{
return Name;
}
}
}
|