-
Notifications
You must be signed in to change notification settings - Fork 496
/
IotHub.cs
498 lines (426 loc) · 21.3 KB
/
IotHub.cs
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using Mash.Logging;
using Microsoft.Azure.Devices.Client;
using static Microsoft.Azure.Devices.LongHaul.Device.LoggingConstants;
namespace Microsoft.Azure.Devices.LongHaul.Device
{
internal sealed class IotHub : IIotHub, IAsyncDisposable
{
private readonly string _deviceConnectionString;
private readonly IotHubClientOptions _clientOptions;
private readonly Logger _logger;
private SemaphoreSlim _lifetimeControl = new(1, 1);
private volatile int _connectionStatusChangeCount = 0;
private readonly Stopwatch _disconnectedTimer = new();
private ConnectionStatus _disconnectedStatus;
private ConnectionStatusChangeReason _disconnectedReason;
private RecommendedAction _disconnectedRecommendedAction;
private volatile IotHubDeviceClient _deviceClient;
private static readonly TimeSpan s_messageLoopSleepTime = TimeSpan.FromSeconds(10);
private static readonly TimeSpan s_deviceTwinUpdateInterval = TimeSpan.FromSeconds(3);
private static readonly TimeSpan s_fileUploadInterval = TimeSpan.FromSeconds(5);
private readonly ConcurrentQueue<TelemetryMessage> _messagesToSend = new();
private long _totalTelemetryMessagesSent = 0;
private long _totalTwinUpdatesReported = 0;
private long _totalTwinCallbacksHandled = 0;
private long _totalDesiredPropertiesHandled = 0;
private long _totalC2dMessagesCompleted = 0;
private long _totalC2dMessagesRejected = 0;
public IotHub(Logger logger, Parameters parameters)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_deviceConnectionString = parameters.ConnectionString;
_clientOptions = new IotHubClientOptions(parameters.GetTransportSettings())
{
PayloadConvention = parameters.GetPayloadConvention(),
SdkAssignsMessageId = SdkAssignsMessageId.WhenUnset,
};
_deviceClient = null;
}
public bool IsConnected => _deviceClient.ConnectionStatusInfo.Status == ConnectionStatus.Connected;
public Dictionary<string, string> TelemetryUserProperties { get; } = new();
/// <summary>
/// Initializes the connection to IoT Hub.
/// </summary>
public async Task InitializeAsync()
{
await _lifetimeControl.WaitAsync().ConfigureAwait(false);
try
{
if (_deviceClient == null)
{
_deviceClient = new IotHubDeviceClient(_deviceConnectionString, _clientOptions)
{
ConnectionStatusChangeCallback = ConnectionStatusChangesHandlerAsync
};
}
else
{
await _deviceClient.CloseAsync().ConfigureAwait(false);
}
await _deviceClient.OpenAsync().ConfigureAwait(false);
await _deviceClient.SetDirectMethodCallbackAsync(DirectMethodCallback).ConfigureAwait(false);
await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallbackAsync).ConfigureAwait(false);
await _deviceClient.SetIncomingMessageCallbackAsync(OnC2dMessageReceivedAsync).ConfigureAwait(false);
}
finally
{
_lifetimeControl.Release();
}
}
/// <summary>
/// Frequently send telemetry messages to the hub.
/// </summary>
/// <param name="ct">The cancellation token</param>
public async Task SendTelemetryMessagesAsync(Logger logger, CancellationToken ct)
{
// AMQP supports bulk telemetry sending, so we'll configure how many to send at a time.
int maxBulkMessages = _clientOptions.TransportSettings is IotHubClientAmqpSettings
? 10
: 1;
// We want to test both paths for AMQP so we'll use a boolean to alternate between bulk and single.
bool sendSingle = true;
var pendingMessages = new List<TelemetryMessage>(maxBulkMessages);
bool loggedDisconnection = false;
logger.LoggerContext.Add(OperationName, LoggingConstants.TelemetryMessage);
Stopwatch sw = new();
while (!ct.IsCancellationRequested)
{
logger.Metric(MessageBacklog, _messagesToSend.Count);
// Wait when there are no messages to send, or if not connected
if (!IsConnected
|| !_messagesToSend.Any())
{
try
{
await Task.Delay(s_messageLoopSleepTime, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// App is signalled to exit
_logger.Trace($"Exit signal encountered. Terminating telemetry message pump.", TraceSeverity.Verbose);
return;
}
}
// If not connected, skip the work below this round.
if (!IsConnected)
{
if (!loggedDisconnection)
{
loggedDisconnection = true;
logger.Trace($"Waiting for connection before sending telemetry", TraceSeverity.Warning);
}
continue;
}
// Get messages to send, unless we're retrying a previous set of messages.
if (!pendingMessages.Any())
{
// Pull some number of messages from the queue, or until empty.
for (int i = 0; i < maxBulkMessages; ++i)
{
if (sendSingle && pendingMessages.Count == 1)
{
break;
}
_messagesToSend.TryDequeue(out TelemetryMessage pendingMessage);
if (pendingMessage == null)
{
break;
}
pendingMessages.Add(pendingMessage);
}
}
// Send any message prepped to send.
if (pendingMessages.Any())
{
if (pendingMessages.Count > 1)
{
logger.Trace($"Sending {pendingMessages.Count} telemetry messages in bulk.", TraceSeverity.Information);
sw.Restart();
await _deviceClient.SendTelemetryAsync(pendingMessages, ct).ConfigureAwait(false);
}
else
{
logger.Trace("Sending a telemetry message.", TraceSeverity.Information);
sw.Restart();
await _deviceClient.SendTelemetryAsync(pendingMessages.First(), ct).ConfigureAwait(false);
}
sw.Stop();
_totalTelemetryMessagesSent += pendingMessages.Count;
_logger.Metric(TotalTelemetryMessagesSent, _totalTelemetryMessagesSent);
_logger.Metric(TelemetryMessageDelaySeconds, sw.Elapsed.TotalSeconds);
pendingMessages.Clear();
// Alternate sending between single and in bulk.
sendSingle = !sendSingle;
}
}
}
public async Task ReportReadOnlyPropertiesAsync(Logger logger, CancellationToken ct)
{
bool loggedDisconnection = false;
logger.LoggerContext.Add(OperationName, ReportTwinProperties);
Stopwatch sw = new();
while (!ct.IsCancellationRequested)
{
// If not connected, skip the work below this round
if (IsConnected)
{
var reported = new ReportedProperties
{
{ "TotalTelemetryMessagesSent", _totalTelemetryMessagesSent },
};
logger.Trace($"Updating reported properties.", TraceSeverity.Information);
sw.Restart();
await _deviceClient.UpdateReportedPropertiesAsync(reported, ct).ConfigureAwait(false);
sw.Stop();
++_totalTwinUpdatesReported;
logger.Metric(TotalTwinUpdatesReported, _totalTwinUpdatesReported);
logger.Metric(ReportedTwinUpdateOperationSeconds, sw.Elapsed.TotalSeconds);
}
else if (!loggedDisconnection)
{
loggedDisconnection = true;
logger.Trace($"Waiting for connection before any other operations.", TraceSeverity.Warning);
}
await Task.Delay(s_deviceTwinUpdateInterval, ct).ConfigureAwait(false);
}
}
public void AddTelemetry(
TelemetryBase telemetryObject,
IDictionary<string, string> extraProperties = null)
{
Debug.Assert(_deviceClient != null);
Debug.Assert(telemetryObject != null);
var iotMessage = new TelemetryMessage(telemetryObject)
{
// Add the event time to the system property
CreatedOnUtc = telemetryObject.EventDateTimeUtc ?? DateTime.UtcNow,
};
foreach (KeyValuePair<string, string> prop in TelemetryUserProperties)
{
iotMessage.Properties.TryAdd(prop.Key, prop.Value);
}
if (extraProperties != null)
{
foreach (KeyValuePair<string, string> prop in extraProperties)
{
// Use TryAdd to ensure the attempt does not fail with an exception
// in the event that this key already exists in this dictionary,
// in which case it'll log an error.
if (!iotMessage.Properties.TryAdd(prop.Key, prop.Value))
{
_logger.Trace($"Could not add telemetry property {prop.Key} due to conflict.", TraceSeverity.Error);
}
}
}
// Worker feeding off this queue will dispose the messages when they are sent
_messagesToSend.Enqueue(iotMessage);
}
public async Task SetPropertiesAsync(string keyName, object properties, CancellationToken cancellationToken)
{
Debug.Assert(_deviceClient != null);
Debug.Assert(properties != null);
var reportedProperties = new ReportedProperties
{
{ keyName, properties },
};
await _deviceClient
.UpdateReportedPropertiesAsync(reportedProperties, cancellationToken)
.ConfigureAwait(false);
_logger.Trace($"Set the reported property with name [{keyName}] in device twin.", TraceSeverity.Information);
}
public async Task UploadFilesAsync(Logger logger, CancellationToken ct)
{
logger.LoggerContext.Add(OperationName, UploadFiles);
Stopwatch sw = new();
while (!ct.IsCancellationRequested)
{
string fileName = $"TestPayload-{Guid.NewGuid()}.txt";
using var ms = new MemoryStream(Encoding.UTF8.GetBytes("TestPayload"));
var fileUploadSasUriRequest = new FileUploadSasUriRequest(fileName);
FileUploadSasUriResponse sasUri = await _deviceClient
.GetFileUploadSasUriAsync(fileUploadSasUriRequest, ct)
.ConfigureAwait(false);
Uri uploadUri = sasUri.GetBlobUri();
try
{
logger.Trace($"Attempting to upload {fileName}...", TraceSeverity.Information);
var blockBlobClient = new BlockBlobClient(uploadUri);
await blockBlobClient.UploadAsync(ms, new BlobUploadOptions(), ct).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.Trace($"Exception occurred while using Azure Storage SDK to upload file: {ex}", TraceSeverity.Warning);
var failedFileUploadCompletionNotification = new FileUploadCompletionNotification(sasUri.CorrelationId, false)
{
StatusCode = 500,
};
await _deviceClient.CompleteFileUploadAsync(failedFileUploadCompletionNotification, ct).ConfigureAwait(false);
return;
}
logger.Trace("File uploaded to Azure Storage was a success", TraceSeverity.Information);
var successfulFileUploadCompletionNotification = new FileUploadCompletionNotification(sasUri.CorrelationId, true)
{
StatusCode = 200,
};
sw.Restart();
await _deviceClient.CompleteFileUploadAsync(successfulFileUploadCompletionNotification, ct).ConfigureAwait(false);
sw.Stop();
logger.Metric(FileUploadOperationSeconds, sw.Elapsed.Seconds);
await Task.Delay(s_fileUploadInterval, ct).ConfigureAwait(false);
}
}
public async ValueTask DisposeAsync()
{
_logger.Trace("Disposing", TraceSeverity.Verbose);
if (_lifetimeControl != null)
{
_lifetimeControl.Dispose();
_lifetimeControl = null;
}
await _deviceClient.DisposeAsync().ConfigureAwait(false);
_logger.Trace($"IoT Hub client instance disposed", TraceSeverity.Verbose);
}
private async void ConnectionStatusChangesHandlerAsync(ConnectionStatusInfo connectionInfo)
{
ConnectionStatus status = connectionInfo.Status;
ConnectionStatusChangeReason reason = connectionInfo.ChangeReason;
RecommendedAction recommendedAction = connectionInfo.RecommendedAction;
string eventName = status == ConnectionStatus.Connected
? ConnectedEvent
: DiscconnectedEvent;
_logger.Event(
eventName,
new Dictionary<string, string>
{
{ ConnectionReason, reason.ToString() },
{ ConnectionRecommendedAction, recommendedAction.ToString() },
});
_logger.Trace(
$"Connection status changed ({++_connectionStatusChangeCount}): status=[{status}], reason=[{reason}], recommendation=[{recommendedAction}]",
TraceSeverity.Information);
if (IsConnected)
{
// The device client has connected.
if (_disconnectedTimer.IsRunning)
{
_disconnectedTimer.Stop();
_logger.Metric(
DisconnectedDurationSeconds,
_disconnectedTimer.Elapsed.TotalSeconds,
new Dictionary<string, string>
{
{ DisconnectedStatus, _disconnectedStatus.ToString() },
{ DisconnectedReason, _disconnectedReason.ToString() },
{ DisconnectedRecommendedAction, _disconnectedRecommendedAction.ToString() },
{ ConnectionStatusChangeCount, _connectionStatusChangeCount.ToString() },
});
}
}
else if (!IsConnected
&& !_disconnectedTimer.IsRunning)
{
_disconnectedTimer.Restart();
_disconnectedStatus = status;
_disconnectedReason = reason;
_disconnectedRecommendedAction = recommendedAction;
}
switch (connectionInfo.RecommendedAction)
{
case RecommendedAction.OpenConnection:
_logger.Trace($"Following recommended action of reinitializing the client.", TraceSeverity.Information);
await InitializeAsync().ConfigureAwait(false);
break;
case RecommendedAction.PerformNormally:
_logger.Trace("The client has retrieved twin values after the connection status changes into CONNECTED.", TraceSeverity.Information);
break;
case RecommendedAction.WaitForRetryPolicy:
_logger.Trace("Letting the client retry.", TraceSeverity.Information);
break;
case RecommendedAction.Quit:
_logger.Trace("Quitting.", TraceSeverity.Information);
break;
}
}
private Task<DirectMethodResponse> DirectMethodCallback(DirectMethodRequest methodRequest)
{
_logger.Trace($"Received direct method [{methodRequest.MethodName}] with payload [{methodRequest.GetPayloadAsJsonString()}].", TraceSeverity.Information);
switch (methodRequest.MethodName)
{
case "EchoPayload":
try
{
if (methodRequest.TryGetPayload(out CustomDirectMethodPayload methodPayload))
{
_logger.Trace($"Echoing back the payload of direct method.", TraceSeverity.Information);
_logger.Metric(
C2dDirectMethodDelaySeconds,
(DateTimeOffset.UtcNow - methodPayload.CurrentTimeUtc).TotalSeconds);
// Log the current time again and send the response back to the service app.
methodPayload.CurrentTimeUtc = DateTimeOffset.UtcNow;
return Task.FromResult(new DirectMethodResponse(200) { Payload = methodPayload });
}
}
catch (Exception ex)
{
_logger.Trace($"Failed to parse the payload for direct method {methodRequest.MethodName} due to {ex}.", TraceSeverity.Error);
return Task.FromResult(new DirectMethodResponse(400) { Payload = ex.Message });
}
break;
}
string unsupportedMessage = $"The direct method [{methodRequest.MethodName}] is not supported.";
_logger.Trace(unsupportedMessage, TraceSeverity.Warning);
return Task.FromResult(new DirectMethodResponse(400) { Payload = unsupportedMessage });
}
private async Task DesiredPropertyUpdateCallbackAsync(DesiredProperties properties)
{
var reported = new ReportedProperties();
foreach (KeyValuePair<string, object> prop in properties)
{
// Assume all values are strings.
if (!properties.TryGetValue(prop.Key, out string propertyValue))
{
_logger.Trace($"Got request for {prop.Key} with non-string [{prop.Value}]", TraceSeverity.Warning);
continue;
}
_logger.Trace($"Got request for {prop.Key} with [{propertyValue}]", TraceSeverity.Information);
reported.Add(prop.Key, propertyValue);
}
if (reported.Any())
{
await _deviceClient.UpdateReportedPropertiesAsync(reported).ConfigureAwait(false);
_totalDesiredPropertiesHandled += reported.Count();
_logger.Metric(TotalDesiredPropertiesHandled, _totalDesiredPropertiesHandled);
}
++_totalTwinCallbacksHandled;
_logger.Metric(TotalTwinCallbacksHandled, _totalTwinCallbacksHandled);
}
private Task<MessageAcknowledgement> OnC2dMessageReceivedAsync(IncomingMessage receivedMessage)
{
_logger.Trace($"Received the C2D message with Id {receivedMessage.MessageId}", TraceSeverity.Information);
if (receivedMessage.TryGetPayload(out CustomC2dMessagePayload customC2dMessagePayload))
{
_logger.Metric(TotalC2dMessagesCompleted, ++_totalC2dMessagesCompleted);
TimeSpan delay = DateTimeOffset.UtcNow - customC2dMessagePayload.CurrentTimeUtc;
_logger.Metric(C2dMessageOperationSeconds, delay.TotalSeconds);
return Task.FromResult(MessageAcknowledgement.Complete);
}
_logger.Trace("The message payload is received in an unknown type.", TraceSeverity.Verbose);
_logger.Metric(TotalC2dMessagesRejected, ++_totalC2dMessagesRejected);
return Task.FromResult(MessageAcknowledgement.Reject);
}
}
}