public async Task FailingInitClosesModuleClient() { // Arrange ConnectionStatusChangesHandler connectionStatusChangesHandler = (status, reason) => { }; DesiredPropertyUpdateCallback desiredPropertyUpdateCallback = (properties, context) => Task.CompletedTask; var milestone = new SemaphoreSlim(0, 1); var moduleClient = new Mock <IModuleClient>(); moduleClient.Setup(m => m.SetDefaultMethodHandlerAsync(It.IsAny <MethodCallback>())).Callback(() => milestone.Release()).Throws <TimeoutException>(); var moduleClientProvider = new Mock <IModuleClientProvider>(); moduleClientProvider.Setup(m => m.Create(connectionStatusChangesHandler)).ReturnsAsync(moduleClient.Object); var requestManager = new Mock <IRequestManager>(); bool enableSubscriptions = true; // Act var moduleConnection = new ModuleConnection(moduleClientProvider.Object, requestManager.Object, connectionStatusChangesHandler, desiredPropertyUpdateCallback, enableSubscriptions); await milestone.WaitAsync(TimeSpan.FromSeconds(10)); await Task.Delay(TimeSpan.FromSeconds(0.5)); // the milestone is hit a bit earlier than the exception, so wait a tiny bit // Assert moduleClient.Verify(m => m.CloseAsync(), Times.Once); }
public async Task EnableTwinAsync(string connectionId) { Console.WriteLine("EnableTwinAsync received for " + connectionId); var client = objectMap[connectionId]; DesiredPropertyUpdateCallback handler = async(props, context) => { Console.WriteLine("patch received"); lastDesiredProps = props; if (desiredPropMutex == null) { Console.WriteLine("No mutex to release. nobody is listening for this patch."); } else { Console.WriteLine("releasing patch mutex"); desiredPropMutex.Release(); desiredPropMutex = null; } }; Console.WriteLine("setting patch handler"); await client.SetDesiredPropertyUpdateCallbackAsync(handler, null).ConfigureAwait(false); Console.WriteLine("Done enabling twin"); }
public async Task DeviceClientCallbackAsyncIsCalledWhenPatchIsReceived() { // arrange var innerHandler = Substitute.For <IDelegatingHandler>(); var client = DeviceClient.CreateFromConnectionString(fakeConnectionString); client.InnerHandler = innerHandler; var myPatch = new TwinCollection(); int callCount = 0; TwinCollection receivedPatch = null; DesiredPropertyUpdateCallback myCallback = (p, c) => { callCount++; receivedPatch = p; return(TaskHelpers.CompletedTask); }; await client.SetDesiredPropertyUpdateCallbackAsync(myCallback, null).ConfigureAwait(false); // act client.InternalClient.OnReportedStatePatchReceived(myPatch); //assert Assert.AreEqual(callCount, 1); Assert.ReferenceEquals(myPatch, receivedPatch); }
// collects the various handlers public async void RegisterDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback callbackHandler) { // add the new handler desiredCallbacks.Add(callbackHandler); // Method must be flagged async due to interface signature, this line eliminates code warning await Task.Run(() => { }); }
/// <inheritdoc /> public Task SetDesiredPropertyUpdateCallbackAsync( DesiredPropertyUpdateCallback callback, object userContext) { if (!IsClosed) { _properties.Add((callback, userContext)); } return(Task.CompletedTask); }
// this method lets you add a new desired property callback method to the internal array public async void RegisterDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback callbackHandler) { // if we haven't already registerd a handler, set up our method to handle it. if (desiredCallbacks.Count < 1) { await deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChangedAsync, null); } // add the new handler desiredCallbacks.Add(callbackHandler); }
public async Task SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback callback, object userContext) { if (client == null) { await mockClient.SetDesiredPropertyUpdateCallbackAsync(callback, userContext); } else { await client.SetDesiredPropertyUpdateCallbackAsync(callback, userContext); } }
public async Task SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback onDesiredPropertyChanged) { try { this.inactivityTimer.Reset(); await this.inner.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertyChanged); } catch (Exception e) { await this.HandleException(e); throw; } }
public ModuleConnection( IModuleClientProvider moduleClientProvider, IRequestManager requestManager, ConnectionStatusChangesHandler connectionStatusChangesHandler, DesiredPropertyUpdateCallback desiredPropertyUpdateCallback, bool enableSubscriptions) { this.moduleClientProvider = Preconditions.CheckNotNull(moduleClientProvider, nameof(moduleClientProvider)); this.requestManager = Preconditions.CheckNotNull(requestManager, nameof(requestManager)); this.connectionStatusChangesHandler = Preconditions.CheckNotNull(connectionStatusChangesHandler, nameof(connectionStatusChangesHandler)); this.desiredPropertyUpdateCallback = Preconditions.CheckNotNull(desiredPropertyUpdateCallback, nameof(desiredPropertyUpdateCallback)); this.enableSubscriptions = enableSubscriptions; // Run initialize module client to create the module client. But we don't need to wait for the result. // The subsequent calls will automatically wait because of the lock Task.Run(this.InitModuleClient); }
public async Task TestExceptionInSetDesiredPropertyUpdateCallbackTest(Type thrownException, Type expectedException) { // Arrange var client = new Mock <IClient>(); client.Setup(c => c.SetDesiredPropertyUpdateCallbackAsync(It.IsAny <DesiredPropertyUpdateCallback>(), It.IsAny <object>())).ThrowsAsync(Activator.CreateInstance(thrownException, "msg str") as Exception); var deviceConnectivityManager = new Mock <IDeviceConnectivityManager>(); deviceConnectivityManager.Setup(d => d.CallTimedOut()); var connectivityAwareClient = new ConnectivityAwareClient(client.Object, deviceConnectivityManager.Object, Mock.Of <IIdentity>(i => i.Id == "d1")); DesiredPropertyUpdateCallback callback = (_, __) => Task.CompletedTask; // Act / Assert await Assert.ThrowsAsync(expectedException, () => connectivityAwareClient.SetDesiredPropertyUpdateCallbackAsync(callback, null)); deviceConnectivityManager.Verify(d => d.CallTimedOut(), Times.Never); }
public async Task InitAsync( string host, int port, string iotHubDeviceConnStr, DesiredPropertyUpdateCallback desiredPropertyUpdateCallback) { modbusClient = new ModbusClient(host, port); try { modbusClient.Init(); modbusClientAlive = true; } catch (Exception ex) { Misc.LogException($"Exception while instantiating Modbus client: {ex.Message}"); } deviceClient = DeviceClient.CreateFromConnectionString(iotHubDeviceConnStr); Twin twin = new Twin(); try { twin = await deviceClient.GetTwinAsync(); if (twin.Properties.Desired["pollingInterval"] != PollingInterval) { Misc.LogDebug("Setting new pollingInterval: " + $"{twin.Properties.Desired["pollingInterval"]} seconds"); try { PollingInterval = twin.Properties.Desired["pollingInterval"]; } catch (Exception ex) { Misc.LogException($"Unable to set pollingInterval: {ex.Message}"); } } await deviceClient.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback, null); } catch (Exception ex) { Misc.LogException(ex.Message); } }
public Task SetDesiredPropertyUpdateCallback(DesiredPropertyUpdateCallback callback, object userContext) { _userDesiredPropertyUpdateCallback = callback; DesiredPropertyUpdateCallback callbackWrapper = (desiredProperties, context) => { return(Task.Run(() => { if (_diagnosticProvider.GetSamplingRateSource() == SamplingRateSource.Server) { ((BaseDiagnosticProvider)_diagnosticProvider).OnDesiredPropertyChange(desiredProperties, context); } _userDesiredPropertyUpdateCallback(desiredProperties, context); })); }; this.callbackWrapper = callbackWrapper; return(_deviceClient.SetDesiredPropertyUpdateCallback(callbackWrapper, userContext)); }
public async Task DeviceClientSetDesiredPropertyUpdateCallbackAsyncRegistersForPatchesOnFirstCall() { // arrange var innerHandler = Substitute.For <IDelegatingHandler>(); var client = DeviceClient.CreateFromConnectionString(fakeConnectionString); client.InnerHandler = innerHandler; DesiredPropertyUpdateCallback myCallback = (p, c) => TaskHelpers.CompletedTask; var context = new object(); // act await client.SetDesiredPropertyUpdateCallbackAsync(myCallback, context).ConfigureAwait(false); // assert await innerHandler. Received(1). EnableTwinPatchAsync(Arg.Any <CancellationToken>()).ConfigureAwait(false); Assert.AreEqual(client.InternalClient._desiredPropertyUpdateCallback, myCallback); }
public async Task DeviceClientDesiredPropertyUpdateCallbackUnsubscribes() { // arrange var innerHandler = Substitute.For <IDelegatingHandler>(); var client = DeviceClient.CreateFromConnectionString(fakeConnectionString); client.InnerHandler = innerHandler; DesiredPropertyUpdateCallback myCallback = (p, c) => TaskHelpers.CompletedTask; var context = new object(); // act await client.SetDesiredPropertyUpdateCallbackAsync(myCallback, context).ConfigureAwait(false); await client.SetDesiredPropertyUpdateCallbackAsync(null, null).ConfigureAwait(false); // assert await innerHandler .Received(1) .DisableTwinPatchAsync(Arg.Any <CancellationToken>()) .ConfigureAwait(false); }
public async Task DeviceClientSetDesiredPropertyUpdateCallbackAsyncDoesNotRegisterForPatchesAfterFirstCall() { // arrange var innerHandler = Substitute.For <IDelegatingHandler>(); var client = DeviceClient.CreateFromConnectionString(fakeConnectionString); client.InnerHandler = innerHandler; DesiredPropertyUpdateCallback myCallback = (p, c) => TaskHelpers.CompletedTask; // act await client.SetDesiredPropertyUpdateCallbackAsync(myCallback, null).ConfigureAwait(false); await client.SetDesiredPropertyUpdateCallbackAsync(myCallback, null).ConfigureAwait(false); await client.SetDesiredPropertyUpdateCallbackAsync(myCallback, null).ConfigureAwait(false); // assert await innerHandler. Received(1). EnableTwinPatchAsync(Arg.Any <CancellationToken>()).ConfigureAwait(false); }
public async Task CreateAndInitTest() { // Arrange ConnectionStatusChangesHandler connectionStatusChangesHandler = (status, reason) => { }; DesiredPropertyUpdateCallback desiredPropertyUpdateCallback = (properties, context) => Task.CompletedTask; var moduleClient = new Mock <IModuleClient>(); moduleClient.Setup(m => m.IsActive).Returns(true); var moduleClientProvider = new Mock <IModuleClientProvider>(); moduleClientProvider.Setup(m => m.Create(connectionStatusChangesHandler)) .ReturnsAsync(moduleClient.Object); var requestManager = new Mock <IRequestManager>(); bool enableSubscriptions = true; // Act var moduleConnection = new ModuleConnection(moduleClientProvider.Object, requestManager.Object, connectionStatusChangesHandler, desiredPropertyUpdateCallback, enableSubscriptions); await Task.Delay(TimeSpan.FromSeconds(5)); Option <IModuleClient> resultModuleClientOption = moduleConnection.GetModuleClient(); // Assert Assert.True(resultModuleClientOption.HasValue); Assert.Equal(moduleClient.Object, resultModuleClientOption.OrDefault()); moduleClientProvider.Verify(m => m.Create(connectionStatusChangesHandler), Times.Once); moduleClient.Verify(m => m.SetDefaultMethodHandlerAsync(It.IsAny <MethodCallback>()), Times.Once); moduleClient.Verify(m => m.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback), Times.Once); // Act IModuleClient resultModuleClient = await moduleConnection.GetOrCreateModuleClient(); // Assert Assert.NotNull(resultModuleClient); Assert.Equal(moduleClient.Object, resultModuleClient); moduleClientProvider.Verify(m => m.Create(connectionStatusChangesHandler), Times.Once); moduleClient.Verify(m => m.SetDefaultMethodHandlerAsync(It.IsAny <MethodCallback>()), Times.Once); moduleClient.Verify(m => m.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback), Times.Once); }
public async Task InitAsync(string host, int port, string deviceConnStr, DesiredPropertyUpdateCallback desiredPropertyUpdateCallback, string currentDeviceid = "modbusdevice") { modbusClient = new ModbusClient(host, port); deviceId = currentDeviceid; try { modbusClient.Init(); modbusClientAlive = true; } catch (Exception ex) { Console.WriteLine($"[EXCEPTION] Exception while instantiating Modbus client: {ex.Message}"); Environment.Exit(-1); } deviceClient = DeviceClient.CreateFromConnectionString(deviceConnStr); var twin = await deviceClient.GetTwinAsync(); if (twin.Properties.Desired["pollingInterval"] != PoolingInterval) { Console.WriteLine("[DEBUG] Setting new pollingInterval: " + $"{twin.Properties.Desired["pollingInterval"]} seconds"); try { PoolingInterval = twin.Properties.Desired["pollingInterval"]; } catch (Exception ex) { Console.WriteLine($"[EXCEPTION] Unable to set pollingInterval: {ex.Message}"); } } await deviceClient.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback, null); }
public void UserWillNotReceiveDiagnosticTwinUpdate() { var fakeDiagnosticProvider = Substitute.For <IDiagnosticProvider>(); var deviceClient = DeviceClientWrapper.CreateFromConnectionString(fakeConnectionString, fakeDiagnosticProvider); DesiredPropertyUpdateCallback userCallback = (desiredProperties, context) => { return(Task.Run(() => { if (desiredProperties.Contains("diag_enabled") || desiredProperties.Contains("diag_sample_rate")) { Assert.Fail(); } })); }; deviceClient.SetDesiredPropertyUpdateCallback(userCallback, new object()); var twin = new Twin(); twin.Properties.Desired["diag_enable"] = "true"; twin.Properties.Desired["diag_sample_rate"] = "10"; deviceClient.callbackWrapper(new TwinCollection(), new object()); }
public void SetDesiredPropertyUpdateCallback(DesiredPropertyUpdateCallback callback) { _deviceClient.SetDesiredPropertyUpdateCallback(callback, null); }
/// <summary> /// Set a callback on desired property change /// </summary> /// <param name="callbackDesired">DesiredPropertyUpdateCallback object</param> public void SetDesiredPropertyCallback(DesiredPropertyUpdateCallback callbackDesired) { _callbackDesired = callbackDesired; }
public Task SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback onDesiredPropertyUpdates, object userContext) => this.underlyingDeviceClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertyUpdates, userContext);
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback callback, object userContext) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { DesiredPropertyUpdateCallback = callback; }
public async Task CreateAndCloseTest() { // Arrange ConnectionStatusChangesHandler connectionStatusChangesHandler = (status, reason) => { }; DesiredPropertyUpdateCallback desiredPropertyUpdateCallback = (properties, context) => Task.CompletedTask; Task <IModuleClient> GetModuleClient() => Task.FromResult(Mock.Of <IModuleClient>(m => m.IsActive)); var moduleClientProvider = new Mock <IModuleClientProvider>(); moduleClientProvider.Setup(m => m.Create(connectionStatusChangesHandler)) .Returns(GetModuleClient); var requestManager = new Mock <IRequestManager>(); bool enableSubscriptions = true; // Act var moduleConnection = new ModuleConnection(moduleClientProvider.Object, requestManager.Object, connectionStatusChangesHandler, desiredPropertyUpdateCallback, enableSubscriptions); IModuleClient resultModuleClient = await moduleConnection.GetOrCreateModuleClient(); Option <IModuleClient> optionResultModuleClient = moduleConnection.GetModuleClient(); // Assert Assert.NotNull(resultModuleClient); Assert.True(optionResultModuleClient.HasValue); moduleClientProvider.Verify(m => m.Create(connectionStatusChangesHandler), Times.Once); Mock <IModuleClient> moduleClient = Mock.Get(resultModuleClient); moduleClient.Verify(m => m.SetDefaultMethodHandlerAsync(It.IsAny <MethodCallback>()), Times.Once); moduleClient.Verify(m => m.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback), Times.Once); // Act - Set the client to not active and try to get a Get a module client moduleClient.Setup(m => m.IsActive).Returns(false); optionResultModuleClient = moduleConnection.GetModuleClient(); // Assert Assert.False(optionResultModuleClient.HasValue); // Act resultModuleClient = await moduleConnection.GetOrCreateModuleClient(); optionResultModuleClient = moduleConnection.GetModuleClient(); // Assert Assert.NotNull(resultModuleClient); Assert.True(optionResultModuleClient.HasValue); moduleClient = Mock.Get(resultModuleClient); moduleClientProvider.Verify(m => m.Create(connectionStatusChangesHandler), Times.Exactly(2)); moduleClient.Verify(m => m.SetDefaultMethodHandlerAsync(It.IsAny <MethodCallback>()), Times.Once); moduleClient.Verify(m => m.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback), Times.Once); // Act - Set the client to not active and raise the client closed event moduleClient.Setup(m => m.IsActive).Returns(false); moduleClient.Raise(m => m.Closed += null, new EventArgs()); await Task.Delay(TimeSpan.FromSeconds(3)); optionResultModuleClient = moduleConnection.GetModuleClient(); // Assert Assert.True(optionResultModuleClient.HasValue); moduleClient = Mock.Get(resultModuleClient); moduleClientProvider.Verify(m => m.Create(connectionStatusChangesHandler), Times.Exactly(3)); moduleClient.Verify(m => m.SetDefaultMethodHandlerAsync(It.IsAny <MethodCallback>()), Times.Once); moduleClient.Verify(m => m.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback), Times.Once); // Act resultModuleClient = await moduleConnection.GetOrCreateModuleClient(); // Assert Assert.NotNull(resultModuleClient); moduleClient = Mock.Get(resultModuleClient); moduleClientProvider.Verify(m => m.Create(connectionStatusChangesHandler), Times.Exactly(3)); moduleClient.Verify(m => m.SetDefaultMethodHandlerAsync(It.IsAny <MethodCallback>()), Times.Once); moduleClient.Verify(m => m.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback), Times.Once); }
public void SetDesiredPropertyUpdateCallback(DesiredPropertyUpdateCallback callback) { _deviceClient.SetDesiredPropertyUpdateCallback(callback, null); _savedDesiredpropertyHandler = callback; }
public Task SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback onDesiredPropertyUpdates1, object userContext) => Task.CompletedTask;
public async Task Initialize(ConnectionStatusChangesHandler connectionStatusHander, MessageHandler messageCallback, DesiredPropertyUpdateCallback twinCallback, MethodCallback methodCallback, object context, CancellationToken ct) { if (deviceClient == null) { return; } deviceClient.SetConnectionStatusChangesHandler(connectionStatusHander); await deviceClient.SetDesiredPropertyUpdateCallbackAsync(twinCallback, context); await deviceClient.SetMethodDefaultHandlerAsync(methodCallback, context); this.messageCallback = messageCallback; this.callbackContext = context; this.cancellationToken = ct; ReceiveC2DMessages(); }
public async Task Initialize(ConnectionStatusChangesHandler connectionStatusHander, MessageHandler messageCallback, DesiredPropertyUpdateCallback twinCallback, MethodCallback methodCallback, object context, CancellationToken ct) { var option = new ClientOptions { ModelId = ModuleClientConnector.PnPModelId }; moduleClient = await ModuleClient.CreateFromEnvironmentAsync(envSettings, options : option); Console.WriteLine($"Connected to Edge Hub as Plug and Play Model Id={ModuleClientConnector.PnPModelId}"); await moduleClient.OpenAsync(); moduleClient.SetConnectionStatusChangesHandler(connectionStatusHander); await moduleClient.SetInputMessageHandlerAsync(this.msgInputName, messageCallback, context); await moduleClient.SetDesiredPropertyUpdateCallbackAsync(twinCallback, context); await moduleClient.SetMethodDefaultHandlerAsync(methodCallback, context); }
/// <inheritdoc /> public Task SetDesiredPropertyUpdateCallbackAsync( DesiredPropertyUpdateCallback callback, object userContext) { return(_client.SetDesiredPropertyUpdateCallbackAsync(callback, userContext)); }
// The SDK caches whether DesiredProperty Update callback has been set and returns directly in that case. // So this method is not a good candidate for checking connectivity status. public Task SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback onDesiredPropertyUpdates, object userContext) => this.InvokeFunc(() => this.underlyingClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertyUpdates, userContext), nameof(this.SetDesiredPropertyUpdateCallbackAsync), false);
public Task SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdateCallback onDesiredPropertyChanged) => this.moduleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertyChanged, null);