public DeviceInitializeDeviceCommunicationStateActionTest()
        {
            linkRequest = new LinkRequest()
            {
                //LinkObjects = new LinkRequestIPA5Object
                //{
                //    LinkActionResponseList = new List<XO.Responses.LinkActionResponse>()
                //},
                Actions = new List <LinkActionRequest>()
                {
                    new LinkActionRequest()
                    {
                        MessageID     = RandomGenerator.BuildRandomString(8),
                        Timeout       = 10000,
                        DeviceRequest = new LinkDeviceRequest()
                        {
                            DeviceIdentifier = new LinkDeviceIdentifier()
                            {
                                Manufacturer = "DeviceMockerInc",
                                Model        = "DeviceMokerModel",
                                SerialNumber = "CEEEDEADBEEF"
                            }
                        }
                    }
                }
            };

            deviceSection = new DeviceSection();

            //mockLoggingClient = new Mock<ILoggingServiceClient>();
            mockDevicePluginLoader = new Mock <IDevicePluginLoader>();

            mockCancellationBroker = new Mock <IDeviceCancellationBroker>();

            mockController = new Mock <IDeviceStateController>();
            //mockController.SetupGet(e => e.LoggingClient).Returns(mockLoggingClient.Object);
            mockController.SetupGet(e => e.DevicePluginLoader).Returns(mockDevicePluginLoader.Object);
            mockController.SetupGet(e => e.Configuration).Returns(deviceSection);
            mockController.SetupGet(e => e.PluginPath).Returns(pluginPath);
            mockController.Setup(e => e.GetCancellationBroker()).Returns(mockCancellationBroker.Object);

            deviceInformation = new DeviceInformation()
            {
                Manufacturer = linkRequest.Actions[0].DeviceRequest.DeviceIdentifier.Manufacturer,
                Model        = linkRequest.Actions[0].DeviceRequest.DeviceIdentifier.Model,
                SerialNumber = linkRequest.Actions[0].DeviceRequest.DeviceIdentifier.SerialNumber,
            };
            fakeDeviceOne.Setup(e => e.DeviceInformation).Returns(deviceInformation);
            deviceInformation.SerialNumber = "CEEEBEEFDEAD";
            fakeDeviceTwo.Setup(e => e.DeviceInformation).Returns(deviceInformation);
            moqCardDevices.AddRange(new ICardDevice[] { fakeDeviceOne.Object, fakeDeviceTwo.Object });
            mockController.SetupGet(e => e.TargetDevices).Returns(moqCardDevices);

            subject = new DeviceInitializeDeviceCommunicationStateAction(mockController.Object);

            asyncManager = new DeviceStateMachineAsyncManager(ref mockController, subject);
        }
        public DeviceStateManagerImplTest()
        {
            subject = new DeviceStateManagerImpl();

            DeviceAppSection          = new DeviceSection();
            mockConfigurationProvider = new Mock <IDeviceConfigurationProvider>();
            mockConfigurationProvider.Setup(e => e.GetAppConfig()).Returns(DeviceAppSection);

            //mockChannelClient = new Mock<IChannelClient>();

            //mockListenerConnector = new Mock<IListenerConnector>();
            //mockListenerConnector.SetupAllProperties();
            //mockListenerConnector.Setup(e => e.ChannelClient).Returns(mockChannelClient.Object);

            //mockListenerConnectorProvider = new Mock<IListenerConnectorProvider>();
            //mockListenerConnectorProvider.Setup(e => e.GetConnector(It.IsAny<IConfiguration>())).Returns(mockListenerConnector.Object);

            //mockLoggingServiceClient = new Mock<ILoggingServiceClient>();

            //mockLoggingServiceClientProvider = new Mock<ILoggingServiceClientProvider>();
            //mockLoggingServiceClientProvider.Setup(e => e.GetLoggingServiceClient()).Returns(mockLoggingServiceClient.Object);

            mockDeviceStateAction = new Mock <IDeviceStateAction>();
            mockDeviceStateAction.Setup(e => e.DoWork()).Returns(Task.CompletedTask);

            mockDeviceStateActionController = new Mock <IDeviceStateActionController>();
            mockDeviceStateActionController.Setup(e => e.GetNextAction(It.IsAny <DeviceWorkflowState>())).Returns(mockDeviceStateAction.Object);
            mockDeviceStateActionController.Setup(e => e.GetFinalState()).Returns(mockDeviceStateAction.Object);

            mockDeviceStateActionControllerProvider = new Mock <IDeviceStateActionControllerProvider>();
            mockDeviceStateActionControllerProvider.Setup(e => e.GetStateActionController(subject)).Returns(mockDeviceStateActionController.Object);

            // Setup fake card devices list and also 2 fake devices for testing purposes.
            cardDevices = new List <ICardDevice>();

            fakeDeviceOne = new Mock <ICardDevice>();
            fakeDeviceTwo = new Mock <ICardDevice>();

            cardDevices.AddRange(new ICardDevice[] { fakeDeviceOne.Object, fakeDeviceTwo.Object });

            mockDevicePluginLoader = new Mock <IDevicePluginLoader>();
            mockDevicePluginLoader.Setup(e => e.FindAvailableDevices(someFakePath)).Returns(cardDevices);

            using IKernel kernel = new DeviceKernelResolver().ResolveKernel();
            //kernel.Rebind<IListenerConnectorProvider>().ToConstant(mockListenerConnectorProvider.Object);
            kernel.Rebind <IDevicePluginLoader>().ToConstant(mockDevicePluginLoader.Object);
            kernel.Rebind <IDeviceConfigurationProvider>().ToConstant(mockConfigurationProvider.Object);
            //kernel.Rebind<ILoggingServiceClientProvider>().ToConstant(mockLoggingServiceClientProvider.Object);
            kernel.Rebind <IDeviceStateActionControllerProvider>().ToConstant(mockDeviceStateActionControllerProvider.Object);
            kernel.Bind <DeviceStateManagerImpl>().ToSelf();
            kernel.Inject(subject);
        }
        public async void DoWork_ShouldFailRequest_When_TimeoutPolicyReturnsFailure()
        {
            List <ICardDevice> iCardDevices = new List <ICardDevice>()
            {
                new Devices.Simulator.DeviceSimulator()
                {
                    SortOrder = 1
                }
            };

            mockDevicePluginLoader.Setup(e => e.FindAvailableDevices(pluginPath)).Returns(iCardDevices);

            DeviceInformation deviceInformation = new DeviceInformation()
            {
                Manufacturer = "DeviceMocker",
                Model        = "DeviceMock",
                SerialNumber = "CEEDEADBEEF"
            };

            fakeDeviceOne.Setup(e => e.DeviceInformation).Returns(deviceInformation);

            DeviceSection deviceSection = new DeviceSection();

            deviceSection.Simulator.SortOrder = 1;
            mockController.Setup(e => e.Configuration).Returns(deviceSection);

            var timeoutPolicy = PollyPolicyResultGenerator.GetFailurePolicy <List <LinkErrorValue> >(new Exception("Request timed out"));

            mockCancellationBroker.Setup(e => e.ExecuteWithTimeoutAsync(It.IsAny <Func <CancellationToken, List <LinkErrorValue> > >(),
                                                                        It.IsAny <int>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(timeoutPolicy));

            await subject.DoWork();

            Assert.True(asyncManager.WaitFor());

            //mockLoggingClient.Verify(e => e.LogErrorAsync(It.IsAny<string>(), It.IsAny<Dictionary<string, object>>()), Times.Once());

            mockController.Verify(e => e.Error(subject), Times.Once());
        }
Exemplo n.º 4
0
        public override Task DoWork()
        {
            string             pluginPath            = Controller.PluginPath;
            List <ICardDevice> availableCardDevices  = null;
            List <ICardDevice> discoveredCardDevices = null;
            List <ICardDevice> validatedCardDevices  = null;

            try
            {
                availableCardDevices = Controller.DevicePluginLoader.FindAvailableDevices(pluginPath);

                // filter out devices that are disabled
                if (availableCardDevices.Count > 0)
                {
                    DeviceSection deviceSection = Controller.Configuration;
                    foreach (var device in availableCardDevices)
                    {
                        switch (device.ManufacturerConfigID)
                        {
                        case "IdTech":
                        {
                            device.SortOrder = deviceSection.IdTech.SortOrder;
                            break;
                        }

                        case "Verifone":
                        {
                            device.SortOrder = deviceSection.Verifone.SortOrder;
                            break;
                        }

                        case "Simulator":
                        {
                            device.SortOrder = deviceSection.Simulator.SortOrder;
                            break;
                        }
                        }
                    }
                    availableCardDevices.RemoveAll(x => x.SortOrder == -1);

                    if (availableCardDevices?.Count > 1)
                    {
                        availableCardDevices.Sort();
                    }
                }

                // Probe validated devices
                discoveredCardDevices = new List <ICardDevice>();
                validatedCardDevices  = new List <ICardDevice>();
                validatedCardDevices.AddRange(availableCardDevices);

                for (int i = validatedCardDevices.Count - 1; i >= 0; i--)
                {
                    if (string.Equals(availableCardDevices[i].ManufacturerConfigID, DeviceType.NoDevice.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    bool success = false;
                    try
                    {
                        List <DeviceInformation> deviceInformation = availableCardDevices[i].DiscoverDevices();

                        if (deviceInformation == null)
                        {
                            continue;
                        }

                        foreach (var deviceInfo in deviceInformation)
                        {
                            DeviceConfig deviceConfig = new DeviceConfig()
                            {
                                Valid = true
                            };
                            SerialDeviceConfig serialConfig = new SerialDeviceConfig
                            {
                                CommPortName = Controller.Configuration.DefaultDevicePort
                            };
                            deviceConfig.SetSerialDeviceConfig(serialConfig);

                            ICardDevice device = validatedCardDevices[i].Clone() as ICardDevice;

                            device.DeviceEventOccured += Controller.DeviceEventReceived;

                            // Device powered on status capturing: free up the com port and try again.
                            // This occurs when a USB device repowers the USB interface and the virtual port is open.
                            CancellationTokenSource   cancellationTokenSource = new CancellationTokenSource();
                            IDeviceCancellationBroker cancellationBroker      = Controller.GetCancellationBroker();
                            var timeoutPolicy = cancellationBroker.ExecuteWithTimeoutAsync <List <LinkErrorValue> >(
                                _ => device.Probe(deviceConfig, deviceInfo, out success),
                                Timeouts.DALGetStatusTimeout,
                                CancellationToken.None);

                            if (timeoutPolicy.Result.Outcome == Polly.OutcomeType.Failure)
                            {
                                Console.WriteLine($"Unable to obtain device status for - '{device.Name}'.");
                                device.DeviceEventOccured -= Controller.DeviceEventReceived;
                                device?.Dispose();
                                LastException = new StateException("Unable to find a valid device to connect to.");
                                _             = Error(this);
                                return(Task.CompletedTask);
                            }
                            else if (success)
                            {
                                discoveredCardDevices.Add(device);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"device: exception='{e.Message}'");

                        discoveredCardDevices[i].DeviceEventOccured -= Controller.DeviceEventReceived;

                        // Consume failures
                        if (success)
                        {
                            success = false;
                        }
                    }

                    if (success)
                    {
                        continue;
                    }

                    validatedCardDevices.RemoveAt(i);
                }
            }
            catch
            {
                availableCardDevices = new List <ICardDevice>();
            }

            if (discoveredCardDevices?.Count > 1)
            {
                discoveredCardDevices.Sort();
            }

            if (discoveredCardDevices?.Count > 0)
            {
                Controller.SetTargetDevices(discoveredCardDevices);
            }

            if (Controller.TargetDevices != null)
            {
                foreach (var device in Controller.TargetDevices)
                {
                    //Controller.LoggingClient.LogInfoAsync($"Device found: name='{device.Name}', model={device.DeviceInformation.Model}, " +
                    //    $"serial={device.DeviceInformation.SerialNumber}");
                    Console.WriteLine($"Device found: name='{device.Name}', model='{device?.DeviceInformation?.Model}', " +
                                      $"serial='{device?.DeviceInformation?.SerialNumber}'");
                    device.DeviceSetIdle();
                }
            }
            else
            {
                //Controller.LoggingClient.LogInfoAsync("Unable to find a valid device to connect to.");
                Console.WriteLine("Unable to find a valid device to connect to.");
                LastException = new StateException("Unable to find a valid device to connect to.");
                _             = Error(this);
                return(Task.CompletedTask);
            }

            _ = Complete(this);

            return(Task.CompletedTask);
        }