Ejemplo n.º 1
0
 public AquariumsController(IAccountService accountService, IAquariumService aquariumService, IDeviceClient deviceService, ILogger <DeviceController> logger)
 {
     _accountService  = accountService;
     _aquariumService = aquariumService;
     _deviceService   = deviceService;
     _logger          = logger;
 }
        async void CloseIotHubConnection()
        {
            if (!this.ConnectedToHub)
            {
                // closure happened before IoT Hub connection was established or it was initiated due to disconnect
                return;
            }

            try
            {
                this.publishProcessor.Complete();
                this.publishPubAckProcessor.Complete();
                this.publishPubRecProcessor.Complete();
                this.pubRelPubCompProcessor.Complete();
                await Task.WhenAll(
                    this.publishProcessor.Completion,
                    this.publishPubAckProcessor.Completion,
                    this.publishPubRecProcessor.Completion,
                    this.pubRelPubCompProcessor.Completion);

                IDeviceClient hub = this.iotHubClient;
                this.iotHubClient = null;
                await hub.DisposeAsync();
            }
            catch (Exception ex)
            {
                MqttIotHubAdapterEventSource.Log.Info("Failed to close IoT Hub Client cleanly.", ex.ToString());
            }
        }
Ejemplo n.º 3
0
 public BugController(IAquariumService aquariumService, IAccountService accountService, IDeviceClient deviceService, ILogger <DeviceController> logger, IEmailerService emailerService)
 {
     _accountService  = accountService;
     _emailerService  = emailerService;
     _aquariumService = aquariumService;
     _deviceService   = deviceService;
     _logger          = logger;
 }
 public AdministrativeService(IConfiguration config, IAquariumDao aquariumDao, IDeviceClient deviceService, ILogger <AdministrativeService> logger, IPhotoManager photoManager)
 {
     _config        = config;
     _aquariumDao   = aquariumDao;
     _logger        = logger;
     _deviceService = deviceService;
     _photoManager  = photoManager;
 }
Ejemplo n.º 5
0
        private static async Task SendTelemetrySendDeviceToCloud(IDeviceClient deviceClient, string messagebody)
        {
            var msg = new Message(Encoding.UTF8.GetBytes(messagebody));

            msg.Properties.Add("message-type", "Fleet");
            msg.Properties.Add("device-type", "Terminal");
            msg.Properties.Add("message-class", "telemetry");
            await deviceClient.SendEventAsync(msg);
        }
 public DeviceInteractionController(IAquariumService aquariumService, IDeviceClient deviceService,
                                    IAccountService accountService,
                                    INotificationService notificationService,
                                    ILogger <DeviceInteractionController> logger)
 {
     _aquariumService     = aquariumService;
     _deviceService       = deviceService;
     _accountService      = accountService;
     _notificationService = notificationService;
     _logger = logger;
 }
Ejemplo n.º 7
0
        public KioskDevice(KioskDeviceConfig deviceConfig, IDeviceClient client, IEventScheduler eventScheduler) : base(deviceConfig, client, eventScheduler)
        {
            this.deviceConfig     = deviceConfig;
            this.TicketStockCount = deviceConfig.InitialStockCount;

            // set up any simulated events for this device
            this._EventScheduler.Add(new TimedSimulatedEvent(5000, 2500, this.SendPurchaseTicketMessageToCloud));

            // register any direct methods we're to recieve
            this._DeviceClient.RegisterDirectMethodAsync(ReceivePurchaseTicketResponse).Wait();
        }
Ejemplo n.º 8
0
 public DeviceRegistrator(ILogger log, IDeviceClient deviceClient, Func <string, IFlurlRequest> registerDeviceRequest,
                          string deviceId, IEnumerable <IDeviceBoundMethodHandler> methodHandlers = null,
                          IEnumerable <TimeSpan> retryIntervals = null)
 {
     _deviceClient          = deviceClient;
     _registerDeviceRequest = registerDeviceRequest;
     _log            = log.ForContext <DeviceRegistrator>();
     _deviceId       = deviceId;
     _macAddress     = MacAddressAccessor.GetMacAddress();
     _methodHandlers = methodHandlers;
     _retryIntervals = retryIntervals ?? Enumerable.Range(0, 10).Select(i => TimeSpan.FromSeconds(i * 3));
 }
Ejemplo n.º 9
0
 public AquariumService(IConfiguration config, ILogger <AquariumService> logger, IAquariumDao aquariumDao, IAccountService accountService,
                        IActivityService activityService, IDeviceClient deviceClient, IPhotoManager photoManager, INotificationService notificationService)
 {
     _config              = config;
     _activityService     = activityService;
     _accountService      = accountService;
     _aquariumDao         = aquariumDao;
     _logger              = logger;
     _deviceClient        = deviceClient;
     _photoManager        = photoManager;
     _notificationService = notificationService;
 }
Ejemplo n.º 10
0
        public BaseDevice(IDeviceConfig deviceConfig, IDeviceClient client, IEventScheduler eventScheduler)
        {
            if (deviceConfig == null || client == null || eventScheduler == null)
            {
                throw new ArgumentNullException("one or more parameters are null. All parameters must be provided");
            }

            this._EventScheduler = eventScheduler;
            this._DeviceClient   = client;     // Connect to the IoT hub using the MQTT protocol

            this._deviceConfig = deviceConfig; // save for later
            this.deviceId      = deviceConfig.DeviceId;
            this.deviceType    = deviceConfig.DeviceType;
            // device status is set during initialization
        }
Ejemplo n.º 11
0
        static async Task SendAlert(IDeviceClient deviceClient)
        {
            var messageBody = new
            {
                value = "ReceiptLowPaper",
                time  = "9/1/2020 8:30:00 AM +01:00"
            };

            var messageBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageBody));
            var message      = new Message(messageBytes);

            message.Properties.Add("device-type", "Terminal");
            message.Properties.Add("message-type", "ReceiptLowPaper");
            message.Properties.Add("message-class", "alert");
            await deviceClient.SendEventAsync(message);
        }
Ejemplo n.º 12
0
        private static async Task BroadcastDeviceRegistration(IDeviceClient deviceClient, string macAddress, IEnumerable <TimeSpan> retryIntervals, ILogger log)
        {
            var policy = Policy <bool>
                         .HandleResult(false)
                         .WaitAndRetryAsync(
                retryIntervals,
                (res, time) => log.Warning("BroadcastDeviceRegistration failed on attempt at {Interval} (Success={Result}).", time, res.Result));

            var result = await policy.ExecuteAsync(async() =>
            {
                try
                {
                    log.Information("Sending device-registration message with mac address: {@macAddress}", macAddress);

                    var message = new Message()
                                  .WithProperties(
                        ("message-type", "device-registration"));

                    if (!string.IsNullOrWhiteSpace(macAddress))
                    {
                        message.Properties.Add("mac-address", macAddress);
                        message.Properties.Add("device-details", "Fleet Service Engine is the gateway for transferring FSC telematry data to Fleed application.");

                        await deviceClient.SendEventAsync(message, CancellationToken.None);
                        log.Information("Device-registration message sent successfully.");

                        return(true);
                    }

                    return(false);
                }
                catch (Exception ex)
                {
                    log.Error(ex, "Failed to send device-registration message.");
                    return(false);
                }
            });

            if (result)
            {
                log.Information("Send device-registration - Success.");
            }
            else
            {
                log.Warning("Send device-registration - Fail.");
            }
        }
Ejemplo n.º 13
0
        private async Task UpdateTwinAsync(Device device, IDeviceClient client, CancellationToken token)
        {
            // Generate some properties using the device model specs
            device.SetReportedProperty("Protocol", this.deviceModel.Protocol.ToString());
            device.SetReportedProperty("SupportedMethods", string.Join(",", this.deviceModel.CloudToDeviceMethods.Keys));
            device.SetReportedProperty("Telemetry", this.deviceModel.GetTelemetryReportedProperty(this.log));

            // Copy all the properties defined in the device model specs
            foreach (KeyValuePair <string, object> p in this.deviceModel.Properties)
            {
                device.SetReportedProperty(p.Key, new JValue(p.Value));
            }

            await client.UpdateTwinAsync(device);

            this.log.Debug("Simulated device properties updated", () => { });
        }
Ejemplo n.º 14
0
        public AccountController(IConfiguration config,
                                 IAquariumService aquariumService,
                                 IDeviceClient deviceService,
                                 IAccountService accountService,
                                 INotificationService notificationService,
                                 ILogger <AccountController> logger,
                                 IPhotoManager photoManager
                                 )

        {
            _config              = config;
            _aquariumService     = aquariumService;
            _accountService      = accountService;
            _notificationService = notificationService;
            _logger              = logger;
            _photoManager        = photoManager;
        }
Ejemplo n.º 15
0
 static async Task PublishTelemetryManifest(IDeviceClient client, CancellationToken cancel)
 {
     try
     {
         logger.LogInformation("Publishing telemetry manifest to IoT Hub.");
         var path          = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configuration", "manifest.json");
         var content       = File.ReadAllText(path);
         var minifyContent = Regex.Replace(content, @"\s", "");
         await client.SendEventAsync(
             new Message(Encoding.UTF8.GetBytes(minifyContent))
             .WithProperties(("message-type", "manifest")));
     }
     catch (Exception ex)
     {
         logger.LogError(ex.Message, "Failed to publish telemetry manifest.");
     }
 }
Ejemplo n.º 16
0
        public async Task OpenConnectionAsync(IDeviceClient deviceClient, IClientWebSocket clientWebSocket, ITcpClient tcpClient, CancellationTokenSource cancellationTokenSource)
        {
            DeviceStreamRequest streamRequest = await deviceClient.WaitForDeviceStreamRequestAsync(cancellationTokenSource.Token).ConfigureAwait(false);

            if (streamRequest != null)
            {
                await deviceClient.AcceptDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false);

                Console.WriteLine($"Device stream accepted from IoT Hub, at {DateTime.UtcNow}");

                clientWebSocket.Options.SetRequestHeader("Authorization", $"Bearer {streamRequest.AuthorizationToken}");

                await clientWebSocket.ConnectAsync(streamRequest.Url, cancellationTokenSource.Token).ConfigureAwait(false);

                Console.WriteLine($"Device stream connected to IoT Hub, at {DateTime.UtcNow}");

                await tcpClient.ConnectAsync(this.HostName, this.Port).ConfigureAwait(false);

                Console.WriteLine($"Device stream connected to local endpoint, at {DateTime.UtcNow}");

                using (var localStream = tcpClient.GetStream())
                {
                    await Task.WhenAny(
                        this.HandleIncomingDataAsync(clientWebSocket, localStream, cancellationTokenSource.Token),
                        this.HandleOutgoingDataAsync(clientWebSocket, localStream, cancellationTokenSource.Token)
                        ).ConfigureAwait(false);

                    localStream.Close();
                    Console.WriteLine($"Device stream closed to local endpoint, at {DateTime.UtcNow}");
                }

                await clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationTokenSource.Token).ConfigureAwait(false);
            }
            else
            {
                await deviceClient.RejectDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false);
            }
        }
        async void ShutdownOnReceiveError(IChannelHandlerContext context, string exception)
        {
            this.publishPubAckProcessor.Abort();
            this.publishProcessor.Abort();
            this.publishPubRecProcessor.Abort();
            this.pubRelPubCompProcessor.Abort();

            IDeviceClient hub = this.iotHubClient;

            if (hub != null)
            {
                this.iotHubClient = null;
                try
                {
                    await hub.DisposeAsync();
                }
                catch (Exception ex)
                {
                    MqttIotHubAdapterEventSource.Log.Info("Failed to close IoT Hub Client cleanly.", ex.ToString());
                }
            }
            ShutdownOnError(context, "Receive", exception);
        }
 /// <summary>
 /// Device class constructor, calls base constructor and starts loading device values.
 /// Accepts a device config, client, and event scheduler. The later 2 are externalized to make
 /// unit testing of the device easier.
 /// </summary>
 public GateReaderDevice(GateReaderDeviceConfig deviceConfig, IDeviceClient client, IEventScheduler eventScheduler)
     : base(deviceConfig, client, eventScheduler)
 {
     // save device configuration
     this.deviceConfig = deviceConfig;
 }
 public SnapshotController(IConfiguration config, IActivityService activityService, IAquariumService aquariumService, IDeviceClient deviceService, ILogger <SnapshotController> logger, IPhotoManager photoManager)
 {
     _config          = config;
     _aquariumService = aquariumService;
     _activityService = activityService;
     _logger          = logger;
     _photoManager    = photoManager;
 }
        /// <summary>
        ///     Performs complete initialization of <see cref="MqttIotHubAdapter" /> based on received CONNECT packet.
        /// </summary>
        /// <param name="context"><see cref="IChannelHandlerContext" /> instance.</param>
        /// <param name="packet">CONNECT packet.</param>
        async void Connect(IChannelHandlerContext context, ConnectPacket packet)
        {
            bool connAckSent = false;

            Exception exception = null;
            try
            {
                if (!this.IsInState(StateFlags.WaitingForConnect))
                {
                    ShutdownOnError(context, "CONNECT has been received in current session already. Only one CONNECT is expected per session.");
                    return;
                }

                this.stateFlags = StateFlags.ProcessingConnect;
                AuthenticationResult authResult = await this.authProvider.AuthenticateAsync(packet.ClientId,
                    packet.Username, packet.Password, context.Channel.RemoteAddress);
                if (!authResult.IsSuccessful)
                {
                    connAckSent = true;
                    await Util.WriteMessageAsync(context, new ConnAckPacket
                    {
                        ReturnCode = ConnectReturnCode.RefusedNotAuthorized
                    });
                    PerformanceCounters.ConnectionFailedAuthPerSecond.Increment();
                    ShutdownOnError(context, "Authentication failed.");
                    return;
                }

                this.deviceId = authResult.DeviceId;

                this.iotHubClient = await this.deviceClientFactory(authResult);

                bool sessionPresent = await this.EstablishSessionStateAsync(this.deviceId, packet.CleanSession);

                this.keepAliveTimeout = this.DeriveKeepAliveTimeout(packet);

                if (packet.HasWill)
                {
                    var will = new PublishPacket(packet.WillQualityOfService, false, packet.WillRetain);
                    will.TopicName = packet.WillTopicName;
                    will.Payload = packet.WillMessage;
                    this.willPacket = will;
                }

                this.sessionContext = new Dictionary<string, string>
                {
                    { DeviceIdParam, this.deviceId }
                };

                this.StartReceiving(context);

                connAckSent = true;
                await Util.WriteMessageAsync(context, new ConnAckPacket
                {
                    SessionPresent = sessionPresent,
                    ReturnCode = ConnectReturnCode.Accepted
                });

                this.CompleteConnect(context);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                if (!connAckSent)
                {
                    try
                    {
                        await Util.WriteMessageAsync(context, new ConnAckPacket
                        {
                            ReturnCode = ConnectReturnCode.RefusedServerUnavailable
                        });
                    }
                    catch (Exception ex)
                    {
                        if (MqttIotHubAdapterEventSource.Log.IsVerboseEnabled)
                        {
                            MqttIotHubAdapterEventSource.Log.Verbose("Error sending 'Server Unavailable' CONNACK.", ex.ToString());
                        }
                    }
                }

                ShutdownOnError(context, "CONNECT", exception);
            }
        }
        async void ShutdownOnReceiveError(IChannelHandlerContext context, string exception)
        {
            this.publishPubAckProcessor.Abort();
            this.publishProcessor.Abort();
            this.publishPubRecProcessor.Abort();
            this.pubRelPubCompProcessor.Abort();

            IDeviceClient hub = this.iotHubClient;
            if (hub != null)
            {
                this.iotHubClient = null;
                try
                {
                    await hub.DisposeAsync();
                }
                catch (Exception ex)
                {
                    MqttIotHubAdapterEventSource.Log.Info("Failed to close IoT Hub Client cleanly.", ex.ToString());
                }
            }
            ShutdownOnError(context, "Receive", exception);
        }
        /// <summary>
        ///     Performs complete initialization of <see cref="MqttIotHubAdapter" /> based on received CONNECT packet.
        /// </summary>
        /// <param name="context"><see cref="IChannelHandlerContext" /> instance.</param>
        /// <param name="packet">CONNECT packet.</param>
        async void Connect(IChannelHandlerContext context, ConnectPacket packet)
        {
            bool connAckSent = false;

            Exception exception = null;

            try
            {
                if (!this.IsInState(StateFlags.WaitingForConnect))
                {
                    ShutdownOnError(context, "CONNECT has been received in current session already. Only one CONNECT is expected per session.");
                    return;
                }

                this.stateFlags = StateFlags.ProcessingConnect;
                AuthenticationResult authResult = await this.authProvider.AuthenticateAsync(packet.ClientId,
                                                                                            packet.Username, packet.Password, context.Channel.RemoteAddress);

                if (authResult == null)
                {
                    connAckSent = true;
                    await Util.WriteMessageAsync(context, new ConnAckPacket
                    {
                        ReturnCode = ConnectReturnCode.RefusedNotAuthorized
                    });

                    PerformanceCounters.ConnectionFailedAuthPerSecond.Increment();
                    ShutdownOnError(context, "Authentication failed.");
                    return;
                }

                this.identity = authResult.Identity;

                this.iotHubClient = await this.deviceClientFactory(authResult);

                bool sessionPresent = await this.EstablishSessionStateAsync(this.identity.ToString(), packet.CleanSession);

                this.keepAliveTimeout = this.DeriveKeepAliveTimeout(packet);

                if (packet.HasWill)
                {
                    var will = new PublishPacket(packet.WillQualityOfService, false, packet.WillRetain);
                    will.TopicName  = packet.WillTopicName;
                    will.Payload    = packet.WillMessage;
                    this.willPacket = will;
                }

                this.sessionContext = new Dictionary <string, string>
                {
                    { DeviceIdParam, this.identity.DeviceId }
                };

                this.StartReceiving(context);

                connAckSent = true;
                await Util.WriteMessageAsync(context, new ConnAckPacket
                {
                    SessionPresent = sessionPresent,
                    ReturnCode     = ConnectReturnCode.Accepted
                });

                this.CompleteConnect(context);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                if (!connAckSent)
                {
                    try
                    {
                        await Util.WriteMessageAsync(context, new ConnAckPacket
                        {
                            ReturnCode = ConnectReturnCode.RefusedServerUnavailable
                        });
                    }
                    catch (Exception ex)
                    {
                        if (MqttIotHubAdapterEventSource.Log.IsVerboseEnabled)
                        {
                            MqttIotHubAdapterEventSource.Log.Verbose("Error sending 'Server Unavailable' CONNACK.", ex.ToString());
                        }
                    }
                }

                ShutdownOnError(context, "CONNECT", exception);
            }
        }
Ejemplo n.º 23
0
 public async Task OpenDeviceConnectionAsync(IStreamingDevice streamingDevice, IDeviceClient deviceClient, IClientWebSocket webSocket, ITcpClient tcpClient, CancellationTokenSource cts)
 {
     // Run a virtual device
     await streamingDevice.OpenConnectionAsync(deviceClient, webSocket, tcpClient, cts).ConfigureAwait(false);
 }
Ejemplo n.º 24
0
 public UpdateReportedPropertiesCommand(IDeviceClient deviceClient)
 {
     _deviceClient = deviceClient;
 }
Ejemplo n.º 25
0
 public QueuedReceiverDeviceClient(string deviceId, IDeviceClient deviceClient)
 {
     this.deviceId         = deviceId ?? throw new ArgumentNullException(nameof(deviceId));
     this.deviceClient     = deviceClient ?? throw new System.ArgumentNullException(nameof(deviceClient));
     this.receiveAsyncLock = new SemaphoreSlim(1, 1);
 }
Ejemplo n.º 26
0
        public async Task Start(CancellationToken cts)
        {
            var           correlationId = Guid.NewGuid().ToString();
            IDeviceClient deviceClient  = null;
            var           stopwatch     = Stopwatch.StartNew();

            try
            {
                deviceClient = CreateDeviceClient();
                deviceClient.SetConnectionStatusChangesHandler(OnConnectionStatusChanged);
                deviceClient.OperationTimeoutInMilliseconds = deviceRunnerConfiguration.DeviceOperationTimeoutInMilliseconds;

                if (deviceRunnerConfiguration.DeviceRetryPolicy)
                {
                    deviceClient.SetRetryPolicy(new ExponentialBackoff(10, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(500)));
                }
                else
                {
                    deviceClient.SetRetryPolicy(new NoRetry());
                }

                await deviceClient.OpenAsync();

                stopwatch.Stop();
                Logger.Log($"{deviceId}: deviceClient created: {stopwatch.ElapsedMilliseconds}ms (retryPolicy={deviceRunnerConfiguration.DeviceRetryPolicy}, operationTimeoutInMilliseconds={deviceClient.OperationTimeoutInMilliseconds})");
            }
            catch (Exception ex)
            {
                Logger.Log($"{deviceId}: deviceClient creation failed: {ex.Message}");
                return;
            }

            var  number           = 0;
            var  maxMsTwinUpdate  = 0L;
            var  numSlowTwin      = 0;
            long maxMsC2D         = 0;
            int  numSlowC2D       = 0;
            long maxMsSendEvent   = 0;
            int  numSlowSendEvent = 0;

            while (!cts.IsCancellationRequested)
            {
                number++;

                // Update Device Twin with increasing "Number"
                if (this.deviceRunnerConfiguration.UpdateTwin)
                {
                    try
                    {
                        var reportedProperties = new TwinCollection();
                        reportedProperties["Number"] = $"{correlationId}-{number}";
                        stopwatch.Restart();
                        Logger.Log($"{deviceId}: begin twins update {number}.");
                        await deviceClient.UpdateReportedPropertiesAsync(reportedProperties);

                        stopwatch.Stop();
                        if (maxMsTwinUpdate < stopwatch.ElapsedMilliseconds)
                        {
                            maxMsTwinUpdate = stopwatch.ElapsedMilliseconds;
                        }
                        if (stopwatch.ElapsedMilliseconds > 4000)
                        {
                            numSlowTwin++;
                        }
                        Logger.Log($"{deviceId}: twins updated {number}: {stopwatch.ElapsedMilliseconds}ms. Max: {maxMsTwinUpdate}ms. Delays: {numSlowTwin}");
                    }
                    catch (IotHubCommunicationException iotHubCommunicationException)
                    {
                        Logger.Log($"{deviceId}: iothub problem, waiting {deviceRunnerConfiguration.DelayAfterIotHubCommunicationError}ms. {iotHubCommunicationException.Message}");
                        await Task.Delay(deviceRunnerConfiguration.DelayAfterIotHubCommunicationError);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log($"{deviceId}: failed to get update twin. {ex.Message}");
                    }
                }


                if (this.deviceRunnerConfiguration.SendEvent)
                {
                    try
                    {
                        var message = new Message(Encoding.UTF8.GetBytes($"{correlationId}-{number}"));
                        message.CorrelationId = correlationId;
                        message.ContentType   = "application/json";
                        stopwatch.Restart();
                        Logger.Log($"{deviceId}: begin send event {number}.");
                        await deviceClient.SendEventAsync(message);

                        stopwatch.Stop();
                        if (maxMsSendEvent < stopwatch.ElapsedMilliseconds)
                        {
                            maxMsSendEvent = stopwatch.ElapsedMilliseconds;
                        }

                        if (stopwatch.ElapsedMilliseconds > 4000)
                        {
                            numSlowSendEvent++;
                        }
                        Logger.Log($"{deviceId}: send event {number}: {stopwatch.ElapsedMilliseconds}ms. Max: {maxMsSendEvent}ms. Delays: {numSlowSendEvent}");
                    }
                    catch (IotHubCommunicationException iotHubCommunicationException)
                    {
                        Logger.Log($"{deviceId}: iothub problem, waiting {deviceRunnerConfiguration.DelayAfterIotHubCommunicationError}ms. {iotHubCommunicationException.Message}");
                        await Task.Delay(deviceRunnerConfiguration.DelayAfterIotHubCommunicationError);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log($"{deviceId}: failed to send event. {ex.Message}");
                    }
                }


                if (this.deviceRunnerConfiguration.CloudToDeviceMessage)
                {
                    try
                    {
                        // Check Cloud-to-Device Message
                        Logger.Log($"{deviceId}: checking c2d message");
                        stopwatch.Restart();
                        Message c2dMsg = await deviceClient.ReceiveAsync(TimeSpan.FromMilliseconds(500));

                        stopwatch.Stop();

                        if (maxMsC2D < stopwatch.ElapsedMilliseconds)
                        {
                            maxMsC2D = stopwatch.ElapsedMilliseconds;
                        }

                        if (stopwatch.ElapsedMilliseconds > 4000)
                        {
                            numSlowC2D++;
                        }

                        Logger.Log($"{deviceId}: done checking c2d message: {stopwatch.ElapsedMilliseconds}ms. Max: {maxMsC2D}ms. Delays: {numSlowC2D}");

                        if (c2dMsg != null)
                        {
                            var c2dMsgBody = c2dMsg.GetBodyAsText();
                            Logger.Log($"{deviceId}: c2d message received '{c2dMsgBody}'");

                            if (deviceRunnerConfiguration.CheckPendingCloudToDeviceMessage)
                            {
                                stopwatch.Restart();
                                var pendingMessage = await deviceClient.ReceiveAsync(TimeSpan.FromMilliseconds(200));

                                stopwatch.Stop();

                                if (maxMsC2D < stopwatch.ElapsedMilliseconds)
                                {
                                    maxMsC2D = stopwatch.ElapsedMilliseconds;
                                }

                                if (stopwatch.ElapsedMilliseconds > 4000)
                                {
                                    numSlowC2D++;
                                }

                                Logger.Log($"{deviceId}: done checking pending c2d message: {stopwatch.ElapsedMilliseconds}ms. Max: {maxMsC2D}ms. Delays: {numSlowC2D}");

                                if (pendingMessage != null)
                                {
                                    var pendingMessageBody = pendingMessage.GetBodyAsText();
                                    Logger.Log($"{deviceId}: abandoning c2d message '{pendingMessageBody}'");
                                    await deviceClient.AbandonAsync(pendingMessage);

                                    Logger.Log($"{deviceId}: done abandoning c2d message '{pendingMessageBody}'");
                                }
                            }

                            if (deviceRunnerConfiguration.CompleteCloudToDeviceMessage)
                            {
                                Logger.Log($"{deviceId}: completing c2d message '{c2dMsgBody}'");
                                await deviceClient.CompleteAsync(c2dMsg);

                                Logger.Log($"{deviceId}: done completing c2d message '{c2dMsgBody}'");
                            }
                        }
                        else
                        {
                            Logger.Log($"{deviceId}: no c2d message received");
                        }
                    }
                    catch (IotHubCommunicationException iotHubCommunicationException)
                    {
                        Logger.Log($"{deviceId}: iothub problem, waiting {deviceRunnerConfiguration.DelayAfterIotHubCommunicationError}ms. {iotHubCommunicationException.Message}");
                        await Task.Delay(deviceRunnerConfiguration.DelayAfterIotHubCommunicationError);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log($"{deviceId}: failed to handle cloud to device message. {ex.Message}");
                    }
                }

                await Task.Delay(this.deviceRunnerConfiguration.DeviceLoopDelay);
            }
        }
Ejemplo n.º 27
0
 public SendEventCommand(IDeviceClient deviceClient)
 {
     _deviceClient = deviceClient;
 }
        async void CloseIotHubConnection()
        {
            if (!this.ConnectedToHub)
            {
                // closure happened before IoT Hub connection was established or it was initiated due to disconnect
                return;
            }

            try
            {
                this.publishProcessor.Complete();
                this.publishPubAckProcessor.Complete();
                this.publishPubRecProcessor.Complete();
                this.pubRelPubCompProcessor.Complete();
                await Task.WhenAll(
                    this.publishProcessor.Completion,
                    this.publishPubAckProcessor.Completion,
                    this.publishPubRecProcessor.Completion,
                    this.pubRelPubCompProcessor.Completion);

                IDeviceClient hub = this.iotHubClient;
                this.iotHubClient = null;
                await hub.DisposeAsync();
            }
            catch (Exception ex)
            {
                MqttIotHubAdapterEventSource.Log.Info("Failed to close IoT Hub Client cleanly.", ex.ToString());
            }
        }