Example #1
0
        public async Task GetDeviceListenerTest()
        {
            // Arrange
            IDeviceProxy deviceProxy    = null;
            var          identity       = Mock.Of <IIdentity>(i => i.Id == "d1/m1");
            var          deviceListener = Mock.Of <IDeviceListener>();

            Mock.Get(deviceListener).Setup(d => d.BindDeviceProxy(It.IsAny <IDeviceProxy>()))
            .Callback <IDeviceProxy>(d => deviceProxy = d);

            var connectionProvider = Mock.Of <IConnectionProvider>(c => c.GetDeviceListenerAsync(identity) == Task.FromResult(deviceListener));
            var connectionHandler  = new ClientConnectionHandler(identity, connectionProvider);

            // Act
            var tasks = new List <Task <IDeviceListener> >();

            for (int i = 0; i < 10; i++)
            {
                tasks.Add(connectionHandler.GetDeviceListener());
            }
            IList <IDeviceListener> deviceListeners = (await Task.WhenAll(tasks)).ToList();

            // Assert
            Assert.NotNull(deviceListeners);
            Assert.Equal(10, deviceListeners.Count);
            for (int i = 0; i < 10; i++)
            {
                Assert.Equal(deviceListener, deviceListeners[0]);
            }
            Assert.NotNull(deviceProxy);
            Mock.Get(connectionProvider).Verify(c => c.GetDeviceListenerAsync(It.IsAny <IIdentity>()), Times.Once);
            Mock.Get(deviceListener).Verify(d => d.BindDeviceProxy(It.IsAny <IDeviceProxy>()), Times.Once);
        }
        /// <summary>
        /// Defines and executes the LocalPullPrintExample workflow.
        /// </summary>
        /// <param name="executionData">Information used in the execution of this workflow.</param>
        /// <returns>The result of executing the workflow.</returns>
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            var result = new PluginExecutionResult(PluginResult.Error, "Unknown");

            _data = executionData.GetMetadata <SdkPullPrintExampleActivityData>();

            UpdateStatus("Starting execution");

            // Get a random device from the selected assets and log it
            var device = executionData.Assets.GetRandom() as HP.ScalableTest.Framework.Assets.IDeviceInfo;

            UpdateStatus($"Selecting and connecting to device {device.AssetId} ({device.Address})...");
            IDeviceProxy proxy = DeviceProxyFactory.Create(device.Address, device.AdminPassword);

            // Define the parameters for a device lock token
            var token = new AssetLockToken(device, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));

            // Acquire a lock on the device to prevent other STB activities that require exclusive access
            // Perform the action and capture the result
            ExecutionServices.CriticalSection.Run(token, () =>
            {
                result = PerformPullPrint(executionData, result, device, proxy);
            }
                                                  );

            return(result);
        }
Example #3
0
        async void BindDeviceProxyAsync(IDeviceProxy deviceProxy, Option <Action> initWhenBound)
        {
            this.underlyingProxy = Preconditions.CheckNotNull(deviceProxy);

            try
            {
                await this.connectionManager.AddDeviceConnection(this.Identity, this);
            }
            catch (Exception ex)
            {
                Events.ErrorBindingDeviceProxy(this.Identity, ex);
                return;
            }

            try
            {
                initWhenBound.ForEach(a => a?.Invoke());
            }
            catch (Exception ex)
            {
                Events.ErrorPostBindAction(this.Identity, ex);
                return;
            }

            Events.BindDeviceProxy(this.Identity);
        }
Example #4
0
        public void BindDeviceProxy(IIdentity identity, IDeviceProxy deviceProxy)
        {
            ConnectedDevice device = this.GetOrCreateConnectedDevice(Preconditions.CheckNotNull(identity, nameof(identity)));

            device.UpdateDeviceProxy(Preconditions.CheckNotNull(deviceProxy, nameof(deviceProxy)));
            Events.BindDeviceProxy(identity);
        }
Example #5
0
            public void SetDeviceProxy(IDeviceProxy deviceProxy)
            {
                if (this.DeviceProxy.HasValue)
                {
                    throw new InvalidOperationException("DeviceProxy has already been set");
                }

                this.DeviceProxy = Option.Some(deviceProxy);
            }
Example #6
0
        async Task SendDesiredPropertiesToDeviceProxy(string id, IMessage desired)
        {
            IDeviceProxy deviceProxy = this.connectionManager.GetDeviceConnection(id)
                                       .Expect(() => new InvalidOperationException($"Device proxy unavailable for device {id}"));
            await deviceProxy.OnDesiredPropertyUpdates(desired);

            TwinCollection patch = this.twinCollectionConverter.FromMessage(desired);

            Events.SentDesiredPropertiesToDevice(id, patch.Version);
        }
        public void BindDeviceProxy(IDeviceProxy deviceProxy)
        {
            this.underlyingProxy = Preconditions.CheckNotNull(deviceProxy);
            Option <ICloudProxy> cloudProxy = this.connectionManager.GetCloudConnection(this.Identity.Id);

            cloudProxy.ForEach(c => c.BindCloudListener(new CloudListener(this.edgeHub, this.Identity.Id)));
            // This operation is async, but we cannot await in this sync method.
            // It is fine because the await part of the operation is cleanup and best effort.
            this.connectionManager.AddDeviceConnection(this.Identity, this);
            Events.BindDeviceProxy(this.Identity);
        }
Example #8
0
 public Option <DeviceConnection> AddDeviceConnection(IDeviceProxy deviceProxy)
 {
     Preconditions.CheckNotNull(deviceProxy, nameof(deviceProxy));
     lock (this.deviceProxyLock)
     {
         Option <DeviceConnection> currentValue = this.DeviceConnection;
         IDictionary <DeviceSubscription, bool> subscriptions = this.DeviceConnection.Map(d => d.Subscriptions)
                                                                .GetOrElse(new ConcurrentDictionary <DeviceSubscription, bool>());
         this.DeviceConnection = Option.Some(new DeviceConnection(deviceProxy, subscriptions));
         return(currentValue);
     }
 }
Example #9
0
        public async Task AddDeviceConnection(IIdentity identity, IDeviceProxy deviceProxy)
        {
            ConnectedDevice       device             = this.GetOrCreateConnectedDevice(Preconditions.CheckNotNull(identity, nameof(identity)));
            Option <IDeviceProxy> currentDeviceProxy = device.UpdateDeviceProxy(Preconditions.CheckNotNull(deviceProxy, nameof(deviceProxy)));

            Events.NewDeviceConnection(identity);

            await currentDeviceProxy
            .Filter(dp => dp.IsActive)
            .ForEachAsync(dp => dp.CloseAsync(new MultipleConnectionsException($"Multiple connections detected for device {identity.Id}")));

            this.DeviceConnected?.Invoke(this, identity);
        }
Example #10
0
            public void UpdateDeviceProxy(IDeviceProxy deviceProxy)
            {
                Preconditions.CheckNotNull(deviceProxy, nameof(deviceProxy));
                lock (this.deviceProxyLock)
                {
                    if (!this.DeviceConnection.HasValue)
                    {
                        throw new InvalidOperationException("DeviceConnection not yet created");
                    }

                    this.DeviceConnection.ForEach(d => d.SetDeviceProxy(deviceProxy));
                }
            }
Example #11
0
        private void DeviceView_Load(object sender, System.EventArgs e)
        {
            this.Log.Initialize(typeof(DeviceView));

            this.deviceProxy = this.DeviceLifetimeManager.DeviceProxy;
            this.DeviceLifetimeManager.DeviceEventListener.PropertyChanged += DeviceEventListener_PropertyChanged;

            var deviceName = ApplicationSettings.GetString("DeviceName");
            this.deviceConfiguration = DeviceConfigurationRegistry.Instance.Get(deviceName) as HcsDeviceConfiguration;

            // The size is not correct by this time. Therefore, start a timer for it
            var drawtimer = new System.Windows.Forms.Timer { Interval = 100 };
            drawtimer.Tick += DrawHeaters;
            drawtimer.Start();
        }
Example #12
0
        public async Task <Option <IDeviceProxy> > GetDeviceProxyAsync(IIdentity identity)
        {
            using (await this.guard.LockAsync())
            {
                var container = default(IDeviceListener);
                if (!this.knownConnections.TryGetValue(identity, out container))
                {
                    return(await this.CreateDeviceProxyAsync(identity));
                }

                return(container switch
                {
                    IDeviceProxy proxy => Option.Some(proxy),
                    _ => Option.None <IDeviceProxy>()
                });
Example #13
0
        private IProcessor CreateMessageProcessor(IDeviceProxy deviceProxy)
        {
            IReadOnlyDictionary <DeviceSubscription, bool> deviceSubscriptions =
                new Dictionary <DeviceSubscription, bool>()
            {
                [DeviceSubscription.ModuleMessages] = true
            };

            var connectionManager = new Mock <IConnectionManager>();

            connectionManager.Setup(call => call.GetDeviceConnection(It.IsAny <string>())).Returns(Option.Some(deviceProxy));
            connectionManager.Setup(c => c.GetSubscriptions(It.IsAny <string>())).Returns(Option.Some(deviceSubscriptions));

            var moduleEndpoint = new ModuleEndpoint("device1/module1", "module1", "in1", connectionManager.Object, new RoutingMessageConverter());

            return(moduleEndpoint.CreateProcessor());
        }
Example #14
0
            public Option <IDeviceProxy> UpdateDeviceProxy(IDeviceProxy deviceProxy)
            {
                Preconditions.CheckNotNull(deviceProxy, nameof(deviceProxy));
                Option <IDeviceProxy> currentValue;

                lock (this.deviceProxyLock)
                {
                    currentValue = this.DeviceConnection.Map(d => d.DeviceProxy);
                    // TODO: Here we set the subscriptions to the existing device subscriptions. This is because if the MQTT setting of cleanSession is set to false
                    // the server is expected to "remember" the subscriptions.
                    // This way of keeping subscriptions might cause issues in the unlikely case that to different devices with 2 different set of subscriptions use the same device ID.
                    // The right way to do this, would be to not store the subscriptions, and instead, query the transport layer (MQTT/AMQP) for the current subscriptions.
                    IDictionary <DeviceSubscription, bool> subscriptions = this.DeviceConnection.Map(d => d.Subscriptions)
                                                                           .GetOrElse(new ConcurrentDictionary <DeviceSubscription, bool>());
                    this.DeviceConnection = Option.Some(new DeviceConnection(deviceProxy, subscriptions));
                }
                return(currentValue);
            }
Example #15
0
        public async Task RegisterModuleMessageSenderTest()
        {
            // Arrange
            IDeviceProxy deviceProxy       = null;
            var          identity          = Mock.Of <IIdentity>(i => i.Id == "d1/m1");
            var          clientCredentials = Mock.Of <IClientCredentials>(c => c.Identity == identity);
            var          deviceListener    = Mock.Of <IDeviceListener>();

            Mock.Get(deviceListener).Setup(d => d.BindDeviceProxy(It.IsAny <IDeviceProxy>()))
            .Callback <IDeviceProxy>(d => deviceProxy = d);

            var connectionProvider = Mock.Of <IConnectionProvider>(c => c.GetDeviceListenerAsync(clientCredentials) == Task.FromResult(deviceListener));

            var amqpAuthentication = new AmqpAuthentication(true, Option.Some(clientCredentials));
            var cbsNode            = Mock.Of <ICbsNode>(c => c.GetAmqpAuthentication() == Task.FromResult(amqpAuthentication));
            var amqpConnection     = Mock.Of <IAmqpConnection>(c => c.FindExtension <ICbsNode>() == cbsNode);
            var connectionHandler  = new ConnectionHandler(amqpConnection, connectionProvider);

            IMessage receivedMessage          = null;
            var      moduleMessageLinkHandler = new Mock <ISendingLinkHandler>();

            moduleMessageLinkHandler.Setup(c => c.SendMessage(It.IsAny <IMessage>()))
            .Callback <IMessage>(m => receivedMessage = m)
            .Returns(Task.CompletedTask);
            moduleMessageLinkHandler.SetupGet(c => c.Type)
            .Returns(LinkType.ModuleMessages);

            var systemProperties = new Dictionary <string, string>();
            var messageToSend    = Mock.Of <IMessage>(m => m.SystemProperties == systemProperties);

            // Act
            await connectionHandler.GetDeviceListener();

            await connectionHandler.RegisterLinkHandler(moduleMessageLinkHandler.Object);

            await deviceProxy.SendMessageAsync(messageToSend, "i1");

            // Assert
            Assert.NotNull(receivedMessage);
            Assert.Equal(messageToSend, receivedMessage);
            Assert.Equal(systemProperties[SystemProperties.InputName], "i1");
        }
Example #16
0
        public async Task RegisterMethodInvokerTest()
        {
            // Arrange
            IDeviceProxy deviceProxy       = null;
            var          identity          = Mock.Of <IIdentity>(i => i.Id == "d1/m1");
            var          clientCredentials = Mock.Of <IClientCredentials>(c => c.Identity == identity);
            var          deviceListener    = Mock.Of <IDeviceListener>();

            Mock.Get(deviceListener).Setup(d => d.BindDeviceProxy(It.IsAny <IDeviceProxy>()))
            .Callback <IDeviceProxy>(d => deviceProxy = d);

            var connectionProvider = Mock.Of <IConnectionProvider>(c => c.GetDeviceListenerAsync(clientCredentials) == Task.FromResult(deviceListener));

            var amqpAuthentication = new AmqpAuthentication(true, Option.Some(clientCredentials));
            var cbsNode            = Mock.Of <ICbsNode>(c => c.GetAmqpAuthentication() == Task.FromResult(amqpAuthentication));
            var amqpConnection     = Mock.Of <IAmqpConnection>(c => c.FindExtension <ICbsNode>() == cbsNode);
            var connectionHandler  = new ConnectionHandler(amqpConnection, connectionProvider);

            IMessage receivedMessage          = null;
            var      methodSendingLinkHandler = new Mock <ISendingLinkHandler>();

            methodSendingLinkHandler.Setup(c => c.SendMessage(It.IsAny <IMessage>()))
            .Callback <IMessage>(m => receivedMessage = m)
            .Returns(Task.CompletedTask);
            methodSendingLinkHandler.SetupGet(c => c.Type)
            .Returns(LinkType.MethodSending);

            var sentRequest = new DirectMethodRequest(identity.Id, "poke", new byte[] { 0, 1, 2 }, TimeSpan.FromSeconds(10));

            // Act
            await connectionHandler.GetDeviceListener();

            await connectionHandler.RegisterLinkHandler(methodSendingLinkHandler.Object);

            await deviceProxy.InvokeMethodAsync(sentRequest);

            // Assert
            Assert.NotNull(receivedMessage);
            Assert.Equal(sentRequest.Data, receivedMessage.Body);
            Assert.Equal(sentRequest.CorrelationId, receivedMessage.SystemProperties[SystemProperties.CorrelationId]);
            Assert.Equal(sentRequest.Name, receivedMessage.Properties[Amqp.Constants.MessagePropertiesMethodNameKey]);
        }
Example #17
0
        public async Task RegisterC2DMessageSenderTest()
        {
            // Arrange
            IDeviceProxy deviceProxy    = null;
            var          identity       = Mock.Of <IIdentity>(i => i.Id == "d1");
            var          deviceListener = Mock.Of <IDeviceListener>();

            Mock.Get(deviceListener).Setup(d => d.BindDeviceProxy(It.IsAny <IDeviceProxy>()))
            .Callback <IDeviceProxy>(d => deviceProxy = d);

            var connectionProvider = Mock.Of <IConnectionProvider>(c => c.GetDeviceListenerAsync(identity, Option.None <string>()) == Task.FromResult(deviceListener));
            var amqpConnection     = new AmqpTestConnection();

            var connectionHandler = new ClientConnectionHandler(identity, connectionProvider, amqpConnection);

            IMessage receivedMessage = null;
            var      c2DLinkHandler  = new Mock <ISendingLinkHandler>();

            c2DLinkHandler.Setup(c => c.SendMessage(It.IsAny <IMessage>()))
            .Callback <IMessage>(m => receivedMessage = m)
            .Returns(Task.CompletedTask);
            c2DLinkHandler.SetupGet(c => c.Type)
            .Returns(LinkType.C2D);

            var systemProperties = new Dictionary <string, string>();
            var messageToSend    = Mock.Of <IMessage>(m => m.SystemProperties == systemProperties);

            // Act
            await connectionHandler.GetDeviceListener();

            await connectionHandler.RegisterLinkHandler(c2DLinkHandler.Object);

            await deviceProxy.SendC2DMessageAsync(messageToSend);

            // Assert
            Assert.NotNull(receivedMessage);
            Assert.Equal(messageToSend, receivedMessage);
            Assert.Equal("/devices/d1", systemProperties[SystemProperties.To]);
        }
Example #18
0
        public async Task GetDeviceListenerTest()
        {
            // Arrange
            IDeviceProxy deviceProxy       = null;
            var          identity          = Mock.Of <IIdentity>(i => i.Id == "d1/m1");
            var          clientCredentials = Mock.Of <IClientCredentials>(c => c.Identity == identity);
            var          deviceListener    = Mock.Of <IDeviceListener>();

            Mock.Get(deviceListener).Setup(d => d.BindDeviceProxy(It.IsAny <IDeviceProxy>()))
            .Callback <IDeviceProxy>(d => deviceProxy = d);

            var connectionProvider = Mock.Of <IConnectionProvider>(c => c.GetDeviceListenerAsync(clientCredentials) == Task.FromResult(deviceListener));

            var amqpAuthentication = new AmqpAuthentication(true, Option.Some(clientCredentials));
            var cbsNode            = Mock.Of <ICbsNode>(c => c.GetAmqpAuthentication() == Task.FromResult(amqpAuthentication));
            var amqpConnection     = Mock.Of <IAmqpConnection>(c => c.FindExtension <ICbsNode>() == cbsNode);
            var connectionHandler  = new ConnectionHandler(amqpConnection, connectionProvider);

            // Act
            var tasks = new List <Task <IDeviceListener> >();

            for (int i = 0; i < 10; i++)
            {
                tasks.Add(connectionHandler.GetDeviceListener());
            }
            IList <IDeviceListener> deviceListeners = (await Task.WhenAll(tasks)).ToList();

            // Assert
            Assert.NotNull(deviceListeners);
            Assert.Equal(10, deviceListeners.Count);
            for (int i = 0; i < 10; i++)
            {
                Assert.Equal(deviceListener, deviceListeners[0]);
            }
            Assert.NotNull(deviceProxy);
            Mock.Get(connectionProvider).Verify(c => c.GetDeviceListenerAsync(It.IsAny <IClientCredentials>()), Times.AtMostOnce);
            Mock.Get(deviceListener).Verify(d => d.BindDeviceProxy(It.IsAny <IDeviceProxy>()), Times.AtMostOnce);
        }
Example #19
0
        public async Task RegisterDesiredPropertiesUpdateSenderTest()
        {
            // Arrange
            IDeviceProxy deviceProxy    = null;
            var          identity       = Mock.Of <IIdentity>(i => i.Id == "d1/m1");
            var          deviceListener = Mock.Of <IDeviceListener>();

            Mock.Get(deviceListener).Setup(d => d.BindDeviceProxy(It.IsAny <IDeviceProxy>()))
            .Callback <IDeviceProxy>(d => deviceProxy = d);

            var connectionProvider = Mock.Of <IConnectionProvider>(c => c.GetDeviceListenerAsync(identity, Option.None <string>()) == Task.FromResult(deviceListener));
            var amqpConnection     = new AmqpTestConnection();

            var connectionHandler = new ClientConnectionHandler(identity, connectionProvider, amqpConnection);

            IMessage receivedMessage        = null;
            var      twinSendingLinkHandler = new Mock <ISendingLinkHandler>();

            twinSendingLinkHandler.Setup(c => c.SendMessage(It.IsAny <IMessage>()))
            .Callback <IMessage>(m => receivedMessage = m)
            .Returns(Task.CompletedTask);
            twinSendingLinkHandler.SetupGet(c => c.Type)
            .Returns(LinkType.TwinSending);

            var messageToSend = Mock.Of <IMessage>();

            // Act
            await connectionHandler.GetDeviceListener();

            await connectionHandler.RegisterLinkHandler(twinSendingLinkHandler.Object);

            await deviceProxy.OnDesiredPropertyUpdates(messageToSend);

            // Assert
            Assert.NotNull(receivedMessage);
            Assert.Equal(messageToSend, receivedMessage);
        }
Example #20
0
        public async Task AddDeviceConnection(IIdentity identity, IDeviceProxy deviceProxy)
        {
            Preconditions.CheckNotNull(identity, nameof(identity));
            Preconditions.CheckNotNull(deviceProxy, nameof(deviceProxy));
            ConnectedDevice           device = this.GetOrCreateConnectedDevice(identity);
            Option <DeviceConnection> currentDeviceConnection = device.AddDeviceConnection(deviceProxy);

            currentDeviceConnection.ForEach(async c =>
            {
                // If we add a device connection that already has subscriptions, we will remake the cloud connection.
                // Otherwise the cloud connection won't get established until some other operation does it (i.e. telemetry)
                if (c.Subscriptions.Count > 0)
                {
                    Events.GettingCloudConnectionForDeviceSubscriptions();
                    await this.TryGetCloudConnection(identity.Id);
                }
            });
            Events.NewDeviceConnection(identity);
            await currentDeviceConnection
            .Filter(dc => dc.IsActive)
            .ForEachAsync(dc => dc.CloseAsync(new MultipleConnectionsException($"Multiple connections detected for device {identity.Id}")));

            this.DeviceConnected?.Invoke(this, identity);
        }
Example #21
0
        public async Task UpdateDeviceConnectionTest()
        {
            int receivedConnectedStatusCount = 0;
            ConnectionStatusChangesHandler connectionStatusChangesHandler = null;
            string hostname = "dummy.azure-devices.net";
            string deviceId = "device1";

            IClientCredentials GetClientCredentials(TimeSpan tokenExpiryDuration)
            {
                string token    = TokenHelper.CreateSasToken(hostname, DateTime.UtcNow.AddSeconds(tokenExpiryDuration.TotalSeconds));
                var    identity = new DeviceIdentity(hostname, deviceId);

                return(new TokenCredentials(identity, token, string.Empty));
            }

            IDeviceProxy GetMockDeviceProxy()
            {
                var deviceProxyMock1 = new Mock <IDeviceProxy>();

                deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(true);
                deviceProxyMock1.Setup(dp => dp.CloseAsync(It.IsAny <Exception>()))
                .Callback(() => deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(false))
                .Returns(Task.CompletedTask);
                return(deviceProxyMock1.Object);
            }

            IClient GetMockedDeviceClient()
            {
                var deviceClient = new Mock <IClient>();

                deviceClient.SetupGet(dc => dc.IsActive).Returns(true);
                deviceClient.Setup(dc => dc.CloseAsync())
                .Callback(() => deviceClient.SetupGet(dc => dc.IsActive).Returns(false))
                .Returns(Task.FromResult(true));

                deviceClient.Setup(dc => dc.SetConnectionStatusChangedHandler(It.IsAny <ConnectionStatusChangesHandler>()))
                .Callback <ConnectionStatusChangesHandler>(c => connectionStatusChangesHandler = c);

                deviceClient.Setup(dc => dc.OpenAsync())
                .Callback(() =>
                {
                    int currentCount = receivedConnectedStatusCount;
                    Assert.NotNull(connectionStatusChangesHandler);
                    connectionStatusChangesHandler.Invoke(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok);
                    Assert.Equal(receivedConnectedStatusCount, currentCount);
                })
                .Returns(Task.CompletedTask);
                return(deviceClient.Object);
            }

            IAuthenticationMethod authenticationMethod = null;
            var deviceClientProvider = new Mock <IClientProvider>();

            deviceClientProvider.Setup(dc => dc.Create(It.IsAny <IIdentity>(), It.IsAny <IAuthenticationMethod>(), It.IsAny <ITransportSettings[]>()))
            .Callback <IIdentity, IAuthenticationMethod, ITransportSettings[]>((s, a, t) => authenticationMethod = a)
            .Returns(() => GetMockedDeviceClient());

            var messageConverterProvider = Mock.Of <IMessageConverterProvider>();

            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>(), TokenProvider, DeviceScopeIdentitiesCache, TimeSpan.FromMinutes(60), true);

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            var credentialsCache = Mock.Of <ICredentialsCache>();
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache, deviceId, "$edgeHub");

            IClientCredentials clientCredentials1 = GetClientCredentials(TimeSpan.FromSeconds(10));
            Try <ICloudProxy>  cloudProxyTry1     = await connectionManager.CreateCloudConnectionAsync(clientCredentials1);

            Assert.True(cloudProxyTry1.Success);

            IDeviceProxy deviceProxy1 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials1.Identity, deviceProxy1);

            await Task.Delay(TimeSpan.FromSeconds(10));

            Assert.NotNull(authenticationMethod);
            var deviceTokenRefresher = authenticationMethod as DeviceAuthenticationWithTokenRefresh;

            Assert.NotNull(deviceTokenRefresher);
            Task <string> tokenGetter = deviceTokenRefresher.GetTokenAsync(hostname);

            Assert.False(tokenGetter.IsCompleted);

            IClientCredentials clientCredentials2 = GetClientCredentials(TimeSpan.FromMinutes(2));
            Try <ICloudProxy>  cloudProxyTry2     = await connectionManager.CreateCloudConnectionAsync(clientCredentials2);

            Assert.True(cloudProxyTry2.Success);

            IDeviceProxy deviceProxy2 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials2.Identity, deviceProxy2);

            await Task.Delay(TimeSpan.FromSeconds(3));

            Assert.False(tokenGetter.IsCompleted);

            IClientCredentials clientCredentials3 = GetClientCredentials(TimeSpan.FromMinutes(10));
            Try <ICloudProxy>  cloudProxyTry3     = await connectionManager.CreateCloudConnectionAsync(clientCredentials3);

            Assert.True(cloudProxyTry3.Success);

            IDeviceProxy deviceProxy3 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials3.Identity, deviceProxy3);

            await Task.Delay(TimeSpan.FromSeconds(23));

            Assert.True(tokenGetter.IsCompleted);
            Assert.Equal(tokenGetter.Result, (clientCredentials3 as ITokenCredentials)?.Token);
        }
Example #22
0
 public void BindDeviceProxy(IDeviceProxy deviceProxy, Action initWhenBound)
 {
 }
Example #23
0
 public void BindDeviceProxy(IDeviceProxy deviceProxy)
 {
 }
Example #24
0
 public void BindDeviceProxy(IDeviceProxy deviceProxy, Action initWhenBound)
 {
     this.BindDeviceProxyAsync(deviceProxy, Option.Some(initWhenBound));
 }
Example #25
0
 public void BindDeviceProxy(IDeviceProxy deviceProxy)
 {
     this.BindDeviceProxyAsync(deviceProxy, Option.None <Action>());
 }
 public RetryConnectionHandler(IDeviceProxy deviceProxy)
 {
     this.deviceProxy = deviceProxy;
 }
Example #27
0
            async Task <ISinkResult> ProcessAsync(ICollection <IRoutingMessage> routingMessages, IDeviceProxy dp, CancellationToken token)
            {
                // TODO - figure out if we can use cancellation token to cancel send
                var succeeded = new List <IRoutingMessage>();
                var failed    = new List <IRoutingMessage>();
                var invalid   = new List <InvalidDetails <IRoutingMessage> >();
                SendFailureDetails sendFailureDetails = null;

                foreach (IRoutingMessage routingMessage in routingMessages)
                {
                    IMessage message = this.moduleEndpoint.messageConverter.ToMessage(routingMessage);
                    try
                    {
                        await dp.SendMessageAsync(message, this.moduleEndpoint.Input);

                        succeeded.Add(routingMessage);
                    }
                    catch (Exception ex)
                    {
                        if (IsRetryable(ex))
                        {
                            failed.Add(routingMessage);
                        }
                        else
                        {
                            Events.InvalidMessage(ex);
                            invalid.Add(new InvalidDetails <IRoutingMessage>(routingMessage, FailureKind.InvalidInput));
                        }

                        Events.ErrorSendingMessages(this.moduleEndpoint, ex);
                    }
                }

                if (failed.Count > 0)
                {
                    Events.RetryingMessages(failed.Count, this.moduleEndpoint.Id);
                    sendFailureDetails = new SendFailureDetails(FailureKind.Transient, new EdgeHubIOException($"Error sending message to module {this.moduleEndpoint.moduleId}"));
                }

                return(new SinkResult <IRoutingMessage>(succeeded, failed, invalid, sendFailureDetails));
            }
 public void BindDeviceProxy(IDeviceProxy deviceProxy)
 {
     this.underlyingProxy = Preconditions.CheckNotNull(deviceProxy);
     this.connectionManager.AddDeviceConnection(this.Identity, this);
     Events.BindDeviceProxy(this.Identity);
 }
        /// <summary>
        /// Performs the pull print.
        /// </summary>
        /// <param name="executionData">The execution data.</param>
        /// <param name="result">The result.</param>
        /// <param name="device">The device.</param>
        /// <param name="proxy">The proxy.</param>
        /// <returns>HP.ScalableTest.Framework.Plugin.PluginExecutionResult.</returns>
        private PluginExecutionResult PerformPullPrint(PluginExecutionData executionData, PluginExecutionResult result, HP.ScalableTest.Framework.Assets.IDeviceInfo device, IDeviceProxy proxy)
        {
            try
            {
                // Log the device being used
                ExecutionServices.DataLogger.Submit(new ActivityExecutionAssetUsageLog(executionData, device));
                UpdateStatus($"Executing as user [{executionData?.Credential?.UserName}]");

                // Reset and make sure we're on home screen
                proxy.DeviceUI.PressKey(KeyCode.ResetKey);
                proxy.DeviceUI.WaitForHomeScreen(TimeSpan.FromSeconds(15));

                // Press the PullPrint example solution button
                var solutionButton = _data.TopLevelButtonName;
                UpdateStatus($"Pressing button [{solutionButton}]");
                proxy.DeviceUI.NavigateToSolution(solutionButton);
                proxy.BrowserUI.WaitForIdle(TimeSpan.FromSeconds(15));

                // Get the list of documents available to print
                UpdateStatus("Checking for available documents");
                Dictionary <string, string>[] checkboxes = proxy.BrowserUI.GetElements("span[class='checkbox']");
                UpdateStatus($"{checkboxes.Length} documents found");

                // Set result to skip if no documents found
                if (checkboxes.Length <= 0)
                {
                    result = new PluginExecutionResult(PluginResult.Skipped, "No documents found to print");
                }
                else
                {
                    UpdateStatus("Checking the the first checkbox");
                    // click the first item in the list to check the checkbox
                    proxy.BrowserUI.ClickElement(checkboxes[0]["id"]);

                    // press the print button
                    UpdateStatus("Clicking the print button");
                    proxy.BrowserUI.ClickElement("printButton");

                    // wait for idle for the job to finish
                    proxy.DeviceProperties.WaitForIdle(TimeSpan.FromSeconds(30));
                    result = new PluginExecutionResult(PluginResult.Passed);
                }
            }
            finally
            {
                try
                {
                    // Navigate through device sign out procedure (if applicable) and return to home screen
                    proxy.DeviceUI.NavigateSignOut();
                    proxy.DeviceUI.WaitForHomeScreen(TimeSpan.FromSeconds(10));
                }
                catch { }

                UpdateStatus("Execution complete");
                UpdateStatus("Result = " + result.Result.ToString());
            }

            return(result);
        }
        public async Task UpdateDeviceConnectionTest()
        {
            int receivedConnectedStatusCount = 0;
            ConnectionStatusChangesHandler connectionStatusChangesHandler = null;
            string hostname = "dummy.azure-devices.net";
            string deviceId = "device1";

            ITokenCredentials GetClientCredentials(TimeSpan tokenExpiryDuration)
            {
                string token    = TokenHelper.CreateSasToken(hostname, DateTime.UtcNow.AddSeconds(tokenExpiryDuration.TotalSeconds));
                var    identity = new DeviceIdentity(hostname, deviceId);

                return(new TokenCredentials(identity, token, string.Empty, Option.None <string>(), Option.None <string>(), false));
            }

            IDeviceProxy GetMockDeviceProxy()
            {
                var deviceProxyMock1 = new Mock <IDeviceProxy>();

                deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(true);
                deviceProxyMock1.Setup(dp => dp.CloseAsync(It.IsAny <Exception>()))
                .Callback(() => deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(false))
                .Returns(Task.CompletedTask);
                return(deviceProxyMock1.Object);
            }

            IClient GetMockedDeviceClient()
            {
                var deviceClient = new Mock <IClient>();

                deviceClient.SetupGet(dc => dc.IsActive).Returns(true);
                deviceClient.Setup(dc => dc.CloseAsync())
                .Callback(() => deviceClient.SetupGet(dc => dc.IsActive).Returns(false))
                .Returns(Task.FromResult(true));

                deviceClient.Setup(dc => dc.SetConnectionStatusChangedHandler(It.IsAny <ConnectionStatusChangesHandler>()))
                .Callback <ConnectionStatusChangesHandler>(c => connectionStatusChangesHandler = c);

                deviceClient.Setup(dc => dc.OpenAsync())
                .Callback(
                    () =>
                {
                    int currentCount = receivedConnectedStatusCount;
                    Assert.NotNull(connectionStatusChangesHandler);
                    connectionStatusChangesHandler.Invoke(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok);
                    Assert.Equal(receivedConnectedStatusCount, currentCount);
                })
                .Returns(Task.CompletedTask);
                return(deviceClient.Object);
            }

            ITokenProvider tokenProvider        = null;
            var            deviceClientProvider = new Mock <IClientProvider>();

            deviceClientProvider.Setup(dc => dc.Create(It.IsAny <IIdentity>(), It.IsAny <ITokenProvider>(), It.IsAny <ITransportSettings[]>(), Option.None <string>()))
            .Callback <IIdentity, ITokenProvider, ITransportSettings[], Option <string> >((s, a, t, m) => tokenProvider = a)
            .Returns(GetMockedDeviceClient);

            var metadataStore = new Mock <IMetadataStore>();

            metadataStore.Setup(m => m.GetMetadata(It.IsAny <string>())).ReturnsAsync(new ConnectionMetadata("dummyValue"));
            var messageConverterProvider = Mock.Of <IMessageConverterProvider>();

            var deviceScopeIdentitiesCache = new Mock <IDeviceScopeIdentitiesCache>();

            deviceScopeIdentitiesCache.Setup(d => d.GetAuthChain(It.Is <string>(i => i == deviceId))).ReturnsAsync(Option.Some(deviceId));

            var credentialsCache = Mock.Of <ICredentialsCache>();
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(
                messageConverterProvider,
                1,
                deviceClientProvider.Object,
                Option.None <UpstreamProtocol>(),
                TokenProvider,
                deviceScopeIdentitiesCache.Object,
                credentialsCache,
                Mock.Of <IIdentity>(i => i.Id == $"{deviceId}/$edgeHub"),
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20),
                false,
                Option.None <IWebProxy>(),
                metadataStore.Object,
                scopeAuthenticationOnly: true,
                trackDeviceState: true,
                true);

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            var deviceConnectivityManager        = Mock.Of <IDeviceConnectivityManager>();
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, Mock.Of <ICredentialsCache>(), new IdentityProvider(hostname), deviceConnectivityManager);

            ITokenCredentials clientCredentials1 = GetClientCredentials(TimeSpan.FromSeconds(10));
            Try <ICloudProxy> cloudProxyTry1     = await connectionManager.CreateCloudConnectionAsync(clientCredentials1);

            Assert.True(cloudProxyTry1.Success);

            IDeviceProxy deviceProxy1 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials1.Identity, deviceProxy1);

            await Task.Delay(TimeSpan.FromSeconds(10));

            Assert.NotNull(tokenProvider);
            Task <string> tokenGetter = tokenProvider.GetTokenAsync(Option.None <TimeSpan>());

            Assert.False(tokenGetter.IsCompleted);

            ITokenCredentials clientCredentials2 = GetClientCredentials(TimeSpan.FromMinutes(2));
            Try <ICloudProxy> cloudProxyTry2     = await connectionManager.CreateCloudConnectionAsync(clientCredentials2);

            Assert.True(cloudProxyTry2.Success);

            IDeviceProxy deviceProxy2 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials2.Identity, deviceProxy2);

            await Task.Delay(TimeSpan.FromSeconds(3));

            Assert.False(tokenGetter.IsCompleted);

            ITokenCredentials clientCredentials3 = GetClientCredentials(TimeSpan.FromMinutes(10));
            Try <ICloudProxy> cloudProxyTry3     = await connectionManager.CreateCloudConnectionAsync(clientCredentials3);

            Assert.True(cloudProxyTry3.Success);

            IDeviceProxy deviceProxy3 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials3.Identity, deviceProxy3);

            await Task.Delay(TimeSpan.FromSeconds(23));

            Assert.True(tokenGetter.IsCompleted);
            Assert.Equal(tokenGetter.Result, clientCredentials3.Token);
        }
Example #31
0
 public DeviceConnection(IDeviceProxy deviceProxy, IDictionary <DeviceSubscription, bool> subscriptions)
 {
     this.Subscriptions = subscriptions;
     this.DeviceProxy   = deviceProxy;
 }
Example #32
0
        private void InitializeDeviceProxy()
        {
            this.deviceProxy = UnityConfig.Instance.Container.Resolve<IDeviceProxy>();
            this.deviceProxy.Initialize();
            this.deviceProxy.ConnectionSuccess += DeviceProxyConnectionSuccess;
            this.deviceProxy.ConnectionFailed += DeviceProxyConnectionFailed;
            this.deviceProxy.WriteFailed += DeviceProxyWriteFailed;
            this.deviceProxy.Protocol.Initialize();

            var deviceName = ApplicationSettings.GetString("DeviceName");
            var deviceConfiguration = DeviceConfigurationRegistry.Instance.Get(deviceName);
            var model = new KdmDeviceModel
            {
                Name = ((SerialDeviceConfiguration)deviceConfiguration).Name,
                DeviceConfiguration = deviceConfiguration
            };

            model.PropertyChanged += Model_PropertyChanged;
            this.deviceProxy.Model = model;

            this.deviceProxy.Connect();
        }
Example #33
0
 private void InitializeReferences()
 {
     this.deviceProxy = this.DeviceLifetimeManager.DeviceProxy;
     this.DeviceLifetimeManager.DeviceEventListener.PropertyChanged += DeviceEventListener_PropertyChanged;
 }