public async Task SyncWithTwinAsync(string devicePrimaryConnString) { Console.WriteLine("Before reading IoT Hub twin file."); try { // dispose the previous object before creating the new one deviceClient?.Dispose(); deviceClient = DeviceClient.CreateFromConnectionString(devicePrimaryConnString, TransportType.Mqtt_WebSocket_Only); var twin = await deviceClient.GetTwinAsync().ConfigureAwait(false); AvailableDriverSizeInMbThreshold = twin.Properties.Desired[InstrumentNode][AvailableDriverSizeThresholdNode]; Console.WriteLine($"Read value from IoT Hub twin file, AvailableDriverSizeInMbThreshold={AvailableDriverSizeInMbThreshold}."); } catch (Exception exception) { Console.WriteLine($"Failed to sync with IoT Hub twin, please check the connection string or if there is desired property '{InstrumentNode}/{AvailableDriverSizeThresholdNode}' for the device."); AvailableDriverSizeInMbThreshold = DefaultAvaialbeDriverSizeThreshold; } // register a callback to get the updated value. if (deviceClient != null) { await deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChangedAsync, null).ConfigureAwait(false); } }
private async Task DoNotReceiveMessagesSentBeforeSubscriptionAsync(TestDeviceType type, ITransportSettings[] settings) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false); DeviceClient deviceClient = testDevice.CreateDeviceClient(settings); var testDeviceCallbackHandler = new TestDeviceCallbackHandler(deviceClient, testDevice, Logger); using var serviceClient = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString); (Message msg, string payload, string p1Value) = ComposeC2dTestMessage(Logger); // Subscribe to receive C2D messages over the callback. await testDeviceCallbackHandler.SetMessageReceiveCallbackHandlerAsync().ConfigureAwait(false); // Now dispose and reinitialize the client instance. deviceClient.Dispose(); deviceClient = null; testDeviceCallbackHandler.Dispose(); testDeviceCallbackHandler = null; deviceClient = testDevice.CreateDeviceClient(settings); testDeviceCallbackHandler = new TestDeviceCallbackHandler(deviceClient, testDevice, Logger); // Open the device client - for MQTT, this will connect the device with CleanSession flag set to true. // This will ensure that messages sent before the device had subscribed to c2d topic are not delivered. await deviceClient.OpenAsync().ConfigureAwait(false); // Send the message from service. Logger.Trace($"Sending C2D message from service, messageId={msg.MessageId}"); await serviceClient.SendAsync(testDevice.Id, msg).ConfigureAwait(false); // Subscribe to receive C2D messages over the callback. testDeviceCallbackHandler.ExpectedMessageSentByService = msg; await testDeviceCallbackHandler.SetMessageReceiveCallbackHandlerAsync().ConfigureAwait(false); // Wait to ensure that the message was not received. using var cts = new CancellationTokenSource(s_tenSeconds); Func <Task> receiveMessageOverCallback = async() => { await testDeviceCallbackHandler.WaitForReceiveMessageCallbackAsync(cts.Token).ConfigureAwait(false); }; receiveMessageOverCallback.Should().Throw <OperationCanceledException>(); await serviceClient.CloseAsync().ConfigureAwait(false); deviceClient.Dispose(); testDeviceCallbackHandler.Dispose(); }
private void InitializeClient() { // If the client reports Connected status, it is already in operational state. if (s_connectionStatus != ConnectionStatus.Connected && _deviceConnectionStrings.Any()) { lock (_initLock) { _logger.LogDebug($"Attempting to initialize the client instance, current status={s_connectionStatus}"); // If the device client instance has been previously initialized, then dispose it. // The s_wasEverConnected variable is required to store if the client ever reported Connected status. if (s_wasEverConnected && s_connectionStatus == ConnectionStatus.Disconnected) { _deviceClient?.Dispose(); s_wasEverConnected = false; } _deviceClient = DeviceClient.CreateFromConnectionString(_deviceConnectionStrings.First(), TransportType.Mqtt); _deviceClient.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler); _deviceClient.OperationTimeoutInMilliseconds = (uint)s_operationTimeout.TotalMilliseconds; } try { // Force connection now _deviceClient.OpenAsync().GetAwaiter().GetResult(); _logger.LogDebug($"Initialized the client instance."); } catch (UnauthorizedException) { // Handled by the ConnectionStatusChangeHandler } } }
private static async Task Main(string[] args) { Console.WriteLine("Starting Simulated device."); using IHost host = CreateHostBuilder(args).Build(); // Application code should start here. // Connect to the IoT hub using the MQTT protocol _deviceClient = DeviceClient.CreateFromConnectionString(_connectionString, _transportType); // Set up a condition to quit the sample Console.WriteLine("Press control-C to exit."); using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; cts.Cancel(); Console.WriteLine("Exiting..."); }; // Run the telemetry loop await SendDeviceToCloudMessagesAsync(cts.Token); _deviceClient.Dispose(); Console.WriteLine("Device simulator finished."); await host.RunAsync(); }
private static TimeSpan s_telemetryInterval = TimeSpan.FromSeconds(1); // Seconds private static async Task Main(string[] args) { Console.WriteLine("IoT Hub Quickstarts #1 - Simulated device."); // This sample accepts the device connection string as a parameter, if present ValidateConnectionString(args); // Connect to the IoT hub using the MQTT protocol s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, s_transportType); // Create a handler for the direct method call await s_deviceClient.SetMethodHandlerAsync("SetTelemetryInterval", SetTelemetryInterval, null); // Set up a condition to quit the sample Console.WriteLine("Press control-C to exit."); using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; cts.Cancel(); Console.WriteLine("Exiting..."); }; // Run the telemetry loop await SendDeviceToCloudMessagesAsync(cts.Token); s_deviceClient.Dispose(); Console.WriteLine("Device simulator finished."); }
static async Task DeviceToCloudMessage(string deviceId, string deviceConnectionString, DeviceClient deviceClient) { var currentDataValue = 0; var messageTemplate = setting.Message; if (string.IsNullOrEmpty(messageTemplate)) { messageTemplate = "{\"DeviceData\": %value%,\"DeviceUtcDatetime\": \"%datetime%\"}"; } var stopWatch = Stopwatch.StartNew(); long lastCheckpoint; long interval = 60000 / setting.MessagePerMin; // in miliseconds long expectedNumofMessage = setting.MessagePerMin * setting.DurationInMin; long count = 0; Random rnd = new Random(); while (stopWatch.Elapsed.TotalMinutes <= setting.DurationInMin) { lastCheckpoint = stopWatch.ElapsedMilliseconds; currentDataValue = rnd.Next(-20, 20); string messageString = messageTemplate; messageString = messageString.Replace("%deviceId%", deviceId); messageString = messageString.Replace("%value%", currentDataValue.ToString()); messageString = messageString.Replace("%datetime%", DateTime.UtcNow.ToString()); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(messageString)); for (int i = 0; i < 10; i++) { try { await deviceClient.SendEventAsync(message); } catch (Exception ex) { Console.WriteLine($"{stopWatch.Elapsed}: {deviceId} send message failed: {ex}"); await Task.Delay(1000); deviceClient.Dispose(); deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, transport); continue; } count++; break; } // add 200ms var delayTime = interval - (stopWatch.ElapsedMilliseconds - lastCheckpoint) - 200; if (delayTime > 0) { await Task.Delay(TimeSpan.FromMilliseconds(delayTime)); } } Console.WriteLine($"{stopWatch.Elapsed}: {deviceId} - Finish sending {count} message (expected: {expectedNumofMessage})"); }
void Setup() { try { if (!IsConnected) { if (s_deviceClient != null) { s_deviceClient.Dispose(); } // Connect to the IoT hub using the MQTT protocol s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt); s_deviceClient.SetMethodHandlerAsync("DoAction", DoAction, null).Wait(); //SendDeviceToCloudMessagesAsync(); display.SetBacklightRgb(0, 200, 100); display.SetText("Device is Ready"); IsConnected = true; } } catch (Exception ex) { Debug.WriteLine(ex.Message + "_" + ex.StackTrace); } }
private static async Task SendDeviceToCloudMessagesAsync(DeviceConfiguration device, CancellationToken ct) { DeviceClient deviceClient = null; if (!string.IsNullOrWhiteSpace(device.ConnectionString)) { var cs = IotHubConnectionStringBuilder.Create(device.ConnectionString); deviceClient = DeviceClient.CreateFromConnectionString(cs.ToString(), TransportType.Mqtt); } var temperatureGenerator = TelemetryGeneratorFactory.Create(device.TemperatureGenerator); var humidityGenerator = TelemetryGeneratorFactory.Create(device.HumidityGenerator); var startupDelay = rand.Next(0, 10000); await Task.Delay(startupDelay, ct); while (!ct.IsCancellationRequested) { var telemetry = new DeviceTelemetry() { DeviceId = device.Id, DeviceName = device.Name, Timestamp = DateTimeOffset.Now, Data = new DeviceData() { Humidity = await humidityGenerator.GenerateNextValueAsync(ct), Temperature = await temperatureGenerator.GenerateNextValueAsync(ct) } }; string messageBody = JsonSerializer.Serialize(telemetry); using var message = new Message(Encoding.ASCII.GetBytes(messageBody)) { ContentType = "application/json", ContentEncoding = "utf-8", }; // Send the telemetry message (if the connectionstring for device is configured) if (deviceClient != null) { await deviceClient.SendEventAsync(message); } Console.WriteLine($"{DateTime.Now} > Sending message: {messageBody}"); try { await Task.Delay(device.PollingIntervalInSec * 1000, ct); } catch (TaskCanceledException) { break; } } if (deviceClient != null) { deviceClient.Dispose(); } }
public void Dispose() { if (deviceClient != null) { try { deviceClient.Dispose(); } catch (Exception ex) { Console.WriteLine($"Device Client disposing error: {ex.Message}"); } } }
public void Dispose() { if (udpClient != null) { if (udpClient.Client != null && udpClient.Client.Connected) { try { udpClient.Client.Disconnect(false); } catch (Exception ex) { Console.WriteLine($"Udp Client socket disconnecting error: {ex.Message}"); } try { udpClient.Client.Close(); } catch (Exception ex) { Console.WriteLine($"Udp Client socket closing error: {ex.Message}"); } try { udpClient.Client.Dispose(); } catch (Exception ex) { Console.WriteLine($"Udp Client socket disposing error: {ex.Message}"); } } try { udpClient.Close(); } catch (Exception ex) { Console.WriteLine($"Udp Client closing error: {ex.Message}"); } try { udpClient.Dispose(); } catch (Exception ex) { Console.WriteLine($"Udp Client disposing error: {ex.Message}"); } } if (ioTHubModuleClient != null) { try { ioTHubModuleClient.CloseAsync().Wait(); } catch (Exception ex) { Console.WriteLine($"IoTHub Module Client closing error: {ex.Message}"); } try { ioTHubModuleClient.Dispose(); } catch (Exception ex) { Console.WriteLine($"IoTHub Module Client disposing error: {ex.Message}"); } } if (messageProcessor != null) { try { messageProcessor.Dispose(); } catch (Exception ex) { Console.WriteLine($"Message Processor disposing error: {ex.Message}"); } } }
public Task <bool> Stop() { bool returnValue = false; try { // *** // *** Unsubscribe from the events // *** if (_temperatureChangedEventToken != null) { this.EventAggregator.GetEvent <Events.TemperatureChangedEvent>().Unsubscribe(_temperatureChangedEventToken); _temperatureChangedEventToken.Dispose(); _temperatureChangedEventToken = null; } // *** // *** Dispose the device client instance. // *** if (_deviceClient != null) { _deviceClient.Dispose(); _deviceClient = null; } returnValue = true; } catch (Exception ex) { this.EventAggregator.GetEvent <Events.DebugEvent>().Publish(new DebugEventArgs(ex)); returnValue = false; } return(Task <bool> .FromResult(returnValue)); }
public static async Task DisconnectFromIoTHub() { // Azure IoT Hub connection await _deviceClient.CloseAsync().ConfigureAwait(true); _deviceClient.Dispose(); }
private async Task ReuseAuthenticationMethod_SingleDevice(Client.TransportType transport) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); var authenticationMethod = new DeviceAuthenticationSasToken(testDevice.ConnectionString, disposeWithClient: false); // Create an instance of the device client, send a test message and then close and dispose it. DeviceClient deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); using var message1 = new Client.Message(); await deviceClient.SendEventAsync(message1).ConfigureAwait(false); await deviceClient.CloseAsync(); deviceClient.Dispose(); Logger.Trace("Test with instance 1 completed"); // Perform the same steps again, reusing the previously created authentication method instance to ensure // that the sdk did not dispose the user supplied authentication method instance. DeviceClient deviceClient2 = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); using var message2 = new Client.Message(); await deviceClient2.SendEventAsync(message2).ConfigureAwait(false); await deviceClient2.CloseAsync(); deviceClient2.Dispose(); Logger.Trace("Test with instance 2 completed, reused the previously created authentication method instance for the device client."); authenticationMethod.Dispose(); }
private async Task AuthenticationMethodDisposesTokenRefresher(Client.TransportType transport) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); var authenticationMethod = new DeviceAuthenticationSasToken(testDevice.ConnectionString, disposeWithClient: true); // Create an instance of the device client, send a test message and then close and dispose it. DeviceClient deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); using var message1 = new Client.Message(); await deviceClient.SendEventAsync(message1).ConfigureAwait(false); await deviceClient.CloseAsync(); deviceClient.Dispose(); Logger.Trace("Test with instance 1 completed"); // Perform the same steps again, reusing the previously created authentication method instance. // Since the default behavior is to dispose AuthenticationWithTokenRefresh authentication method on DeviceClient disposal, // this should now throw an ObjectDisposedException. DeviceClient deviceClient2 = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); using var message2 = new Client.Message(); Func <Task> act = async() => await deviceClient2.SendEventAsync(message2).ConfigureAwait(false); await act.Should().ThrowAsync <ObjectDisposedException>(); }
static void Setup() { try { if (!IsConnected) { if (s_deviceClient != null) { s_deviceClient.Dispose(); } var ConStr = ConfigurationManager.AppSettings["DeviceConStr"]; // Connect to the IoT hub using the MQTT protocol s_deviceClient = DeviceClient.CreateFromConnectionString(ConStr, Microsoft.Azure.Devices.Client.TransportType.Mqtt); s_deviceClient.SetMethodHandlerAsync("DoAction", DoAction, null).Wait(); //SendDeviceToCloudMessagesAsync(); IsConnected = true; } } catch { } }
private static async Task Main(string[] args) { Console.WriteLine("IoT Hub Quickstarts #1 - Simulated device."); // This sample accepts the device connection string as a parameter, if present ValidateConnectionString(args); // Connect to the IoT hub using the MQTT protocol s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, s_transportType); // Set up a condition to quit the sample Console.WriteLine("Press control-C to exit."); using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; cts.Cancel(); Console.WriteLine("Exiting..."); }; // Run the telemetry loop await SendDeviceToCloudMessagesAsync(cts.Token); // SendDeviceToCloudMessagesAsync is designed to run until cancellation has been explicitly requested by Console.CancelKeyPress. // As a result, by the time the control reaches the call to close the device client, the cancellation token source would // have already had cancellation requested. // Hence, if you want to pass a cancellation token to any subsequent calls, a new token needs to be generated. // For device client APIs, you can also call them without a cancellation token, which will set a default // cancellation timeout of 4 minutes: https://github.com/Azure/azure-iot-sdk-csharp/blob/64f6e9f24371bc40ab3ec7a8b8accbfb537f0fe1/iothub/device/src/InternalClient.cs#L1922 await s_deviceClient.CloseAsync(); s_deviceClient.Dispose(); Console.WriteLine("Device simulator finished."); }
private async Task InitializeAndSetupClientAsync(CancellationToken cancellationToken) { if (ShouldClientBeInitialized(s_connectionStatus)) { // Allow a single thread to dispose and initialize the client instance. await _initSemaphore.WaitAsync(cancellationToken); try { if (ShouldClientBeInitialized(s_connectionStatus)) { _logger.LogDebug($"Attempting to initialize the client instance, current status={s_connectionStatus}"); // If the device client instance has been previously initialized, close and dispose it. if (s_deviceClient != null) { try { await s_deviceClient.CloseAsync(cancellationToken); } catch (UnauthorizedException) { } // if the previous token is now invalid, this call may fail s_deviceClient.Dispose(); } s_deviceClient = DeviceClient.CreateFromConnectionString(_deviceConnectionStrings.First(), _transportType, _clientOptions); s_deviceClient.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler); _logger.LogDebug("Initialized the client instance."); } } finally { _initSemaphore.Release(); } // Force connection now. // We have set the "shouldExecuteOperation" function to always try to open the connection. // OpenAsync() is an idempotent call, it has the same effect if called once or multiple times on the same client. await RetryOperationHelper.RetryTransientExceptionsAsync( operationName : "OpenConnection", asyncOperation : async() => await s_deviceClient.OpenAsync(cancellationToken), shouldExecuteOperation : () => true, logger : _logger, exceptionsToBeIgnored : _exceptionsToBeIgnored, cancellationToken : cancellationToken); _logger.LogDebug($"The client instance has been opened."); // You will need to subscribe to the client callbacks any time the client is initialized. await RetryOperationHelper.RetryTransientExceptionsAsync( operationName : "SubscribeTwinUpdates", asyncOperation : async() => await s_deviceClient.SetDesiredPropertyUpdateCallbackAsync(HandleTwinUpdateNotificationsAsync, cancellationToken), shouldExecuteOperation : () => IsDeviceConnected, logger : _logger, exceptionsToBeIgnored : _exceptionsToBeIgnored, cancellationToken : cancellationToken); _logger.LogDebug("The client has subscribed to desired property update notifications."); } }
public void Disconnect() { stopPublishData(); s_deviceClient.Dispose(); view.ConnectStatusLabel = "Disconnected"; view.PublishMessageText = "Azure IoT Hub Disconnected"; s_deviceClient = null; }
private void DeviceSimulatorForm_FormClosing(object sender, FormClosingEventArgs e) { if (deviceClient != null) { deviceClient.Dispose(); deviceClient = null; } }
public async void stop() { ((MainWindow)System.Windows.Application.Current.MainWindow).list.IsEnabled = true; kill = true; worker.Dispose(); await deviceClient.CloseAsync(); deviceClient.Dispose(); }
public async Task DisconnectAsync() { switch (Model.DefaultTransport.Value) { /*case TransportTypes.AMQP: * ConnectButtonVisible = true; * break;*/ case TransportTypes.AzureIoTHub: #if IOTHUB if (_azureIoTHubClient != null) { await _azureIoTHubClient.CloseAsync(); _azureIoTHubClient.Dispose(); _azureIoTHubClient = null; } #endif ConnectButtonVisible = true; break; case TransportTypes.MQTT: if (_mqttClient != null) { _mqttClient.Disconnect(); _mqttClient = null; } ConnectButtonVisible = true; break; case TransportTypes.TCP: if (_tcpClient != null) { await _tcpClient.DisconnectAsync(); _tcpClient.Dispose(); } ConnectButtonVisible = true; break; case TransportTypes.UDP: if (_udpClient != null) { await _udpClient.DisconnectAsync(); _udpClient.Dispose(); } ConnectButtonVisible = true; break; } SetDisconnectedState();; RightMenuIcon = Client.Core.ViewModels.RightMenuIcon.None; }
public async Task Dispose() { if (client != null) { await client.CloseAsync(); client?.Dispose(); } }
public void Dispose() { if (_deviceClient != null) { _deviceClient.Dispose(); _deviceClient = null; Connected = false; } }
private async Task ReceiveMessagesSentBeforeSubscriptionAsync(TestDeviceType type, Client.TransportType transport) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false); DeviceClient deviceClient = testDevice.CreateDeviceClient(transport); var testDeviceCallbackHandler = new TestDeviceCallbackHandler(deviceClient, testDevice, Logger); using var serviceClient = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString); (Message msg, string payload, string p1Value) = ComposeC2dTestMessage(Logger); // Subscribe to receive C2D messages over the callback. await testDeviceCallbackHandler.SetMessageReceiveCallbackHandlerAsync().ConfigureAwait(false); // Now dispose and reinitialize the client instance. deviceClient.Dispose(); deviceClient = null; testDeviceCallbackHandler.Dispose(); testDeviceCallbackHandler = null; deviceClient = testDevice.CreateDeviceClient(transport); testDeviceCallbackHandler = new TestDeviceCallbackHandler(deviceClient, testDevice, Logger); // Open the device client - for MQTT, this will connect the device with CleanSession flag set to false. await deviceClient.OpenAsync().ConfigureAwait(false); // Send the message from service. Logger.Trace($"Sending C2D message from service, messageId={msg.MessageId}"); await serviceClient.SendAsync(testDevice.Id, msg).ConfigureAwait(false); // Subscribe to receive C2D messages over the callback. testDeviceCallbackHandler.ExpectedMessageSentByService = msg; await testDeviceCallbackHandler.SetMessageReceiveCallbackHandlerAsync().ConfigureAwait(false); // Wait to ensure that the message was received. using var cts = new CancellationTokenSource(s_tenSeconds); await testDeviceCallbackHandler.WaitForReceiveMessageCallbackAsync(cts.Token).ConfigureAwait(false); await serviceClient.CloseAsync().ConfigureAwait(false); deviceClient.Dispose(); testDeviceCallbackHandler.Dispose(); }
public async void SendTelemetry() { bool run = true; while (run) { try { litersInTank = litersInTank < 0.5 ? 15.0 : litersInTank - 0.1; var vehicleData = new VehicleData() { LitersInTank = litersInTank, AvgSpeed = random.NextDouble() + 15 * 2, Timestamp = DateTime.Now.ToString() }; var jsonPayload = JsonConvert.SerializeObject(vehicleData); var message = new Message(Encoding.UTF8.GetBytes(jsonPayload)); await deviceClient.SendEventAsync(message); Console.WriteLine("Send: " + jsonPayload); } catch (System.Exception ex) { try { await deviceClient.CloseAsync(); deviceClient.Dispose(); } catch (System.Exception deviceException) { Console.WriteLine(deviceException.Message); } await InitDevice(); run = false; Console.WriteLine(ex.Message); } await Task.Delay(10000); } }
public async Task Dispose() { cancelationTokenSource.Cancel(); if (client != null) { await client.CloseAsync(); client?.Dispose(); deviceSemaphore?.Dispose(); } }
private void DeviceSimulatorForm_FormClosing(object sender, FormClosingEventArgs e) { sendLoopChecked = false; receiveLoopChecked = false; Thread.Sleep(500); if (deviceClient != null) { deviceClient.Dispose(); deviceClient = null; } }
/// <summary> /// Dispose method. /// </summary> public void Dispose() { // Dispose the connection with Azure IoT Hub. _deviceClient?.Dispose(); _deviceClient = null; // Dispose the Raspberry Pi controller. _gpioController?.Dispose(); _gpioController = null; // Dispose temperature sensor. _temperatureSensor?.Dispose(); _temperatureSensor = null; }
public async Task <bool> DisconnectAsync() { if (_deviceClient != null) { await _deviceClient.CloseAsync(); _deviceClient.Dispose(); _deviceClient = null; } return(true); }
public async Task Method_ServiceInvokeDeviceMethodWithNullPayload_DoesNotThrow() { // arrange DeviceClient deviceClient = null; TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, "NullMethodPayloadTest").ConfigureAwait(false); try { const string commandName = "Reboot"; bool deviceMethodCalledSuccessfully = false; deviceClient = testDevice.CreateDeviceClient(Client.TransportType.Mqtt); await deviceClient.OpenAsync().ConfigureAwait(false); await deviceClient .SetMethodDefaultHandlerAsync( (methodRequest, userContext) => { methodRequest.Name.Should().Be(commandName); deviceMethodCalledSuccessfully = true; return(Task.FromResult(new MethodResponse(200))); }, null) .ConfigureAwait(false); using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); CloudToDeviceMethod c2dMethod = new CloudToDeviceMethod(commandName, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)).SetPayloadJson(null); // act CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync(testDevice.Id, c2dMethod).ConfigureAwait(false); // assert deviceMethodCalledSuccessfully.Should().BeTrue(); } finally { // clean up await deviceClient.SetMethodDefaultHandlerAsync(null, null).ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); deviceClient.Dispose(); await testDevice.RemoveDeviceAsync().ConfigureAwait(false); } }