public async Task ExecuteBuiltinCommandAsyncGroupOnBadIdTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager    = new StubIAdapterManager();
            var log               = new StubIFeedback <LogEntry>();
            var cts               = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device  = UnitTesting.CreateFakeDevice();
            var device2 = UnitTesting.CreateFakeDevice();

            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "GROUP_ON"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, "0", "", cts.Token);

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(result.Message.Contains("Invalid group"), "Expected to see 'Invalid group' in log");
            }
        }
        public async Task ExecuteBuiltinCommandAsyncGroupOnTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var groupOnIdsRequestSentToAdapter = new List <Group>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    ActivateGroupAsyncGroup = async g => groupOnIdsRequestSentToAdapter.Add(g)
                }
            };
            var log = new StubIFeedback <LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device  = UnitTesting.CreateFakeDevice();
            var device2 = UnitTesting.CreateFakeDevice();
            var device3 = UnitTesting.CreateFakeDevice();

            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                context.Devices.Add(device2);
                context.Devices.Add(device3);

                var group = new Group
                {
                    Name = "Test Group"
                };
                group.Devices.Add(device);
                group.Devices.Add(device2);
                context.Groups.Add(group);

                var builtinCommand = new BuiltinCommand
                {
                    Name             = "Turn on a Group",
                    UniqueIdentifier = "GROUP_ON"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result =
                    await
                    commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand,
                                                                 group.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
                Assert.IsTrue(groupOnIdsRequestSentToAdapter.Count == 2, "Process did not run the correct amount of commands.");
                Assert.IsTrue(group.Id == groupOnIdsRequestSentToAdapter[0].Id, "Ran the wrong group!");
            }
        }
        public async Task RegisterAsyncNewTest()
        {
            //arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());
            var bcb = new BuiltinCommandBuilder(dbConnection);

            var builtinCommand = new BuiltinCommand
            {
                Name = "Unit Test Builtin Command",
                UniqueIdentifier = "BUILTIN_COMMAND1"
            };

            //act
            var result = await bcb.RegisterAsync(builtinCommand, CancellationToken.None);

            BuiltinCommand setting;
            using (var context = new ZvsContext(dbConnection))
            {
                setting =
                    await
                        context.BuiltinCommands.FirstOrDefaultAsync(
                            o => o.UniqueIdentifier == builtinCommand.UniqueIdentifier);

            }

            //assert 
            Console.WriteLine(result.Message);
            Assert.IsFalse(result.HasError, result.Message);
            Assert.IsNotNull(setting, "Expected new builtin command setting saved to DB");
        }
        public async Task ExecuteBuiltinCommandAsyncUnknownCommandTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var deviceCommandIds = new List <int>();
            var adapterManager   = new StubIAdapterManager();
            var log = new StubIFeedback <LogEntry>();

            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var builtinCommand = new BuiltinCommand
                {
                    Name             = "Unknown Built-in Command",
                    UniqueIdentifier = "UNKNOWN_COMMAND_TYPE"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, "", "", cts.Token);

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(deviceCommandIds.Count == 0, "Process did not run the correct amount of commands.");
            }
        }
        public async Task RegisterAsyncNewTest()
        {
            //arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());
            var bcb = new BuiltinCommandBuilder(dbConnection);

            var builtinCommand = new BuiltinCommand
            {
                Name             = "Unit Test Builtin Command",
                UniqueIdentifier = "BUILTIN_COMMAND1"
            };

            //act
            var result = await bcb.RegisterAsync(builtinCommand, CancellationToken.None);

            BuiltinCommand setting;

            using (var context = new ZvsContext(dbConnection))
            {
                setting =
                    await
                    context.BuiltinCommands.FirstOrDefaultAsync(
                        o => o.UniqueIdentifier == builtinCommand.UniqueIdentifier);
            }

            //assert
            Console.WriteLine(result.Message);
            Assert.IsFalse(result.HasError, result.Message);
            Assert.IsNotNull(setting, "Expected new builtin command setting saved to DB");
        }
        public async Task <Result> RegisterAsync(BuiltinCommand builtinCommand, CancellationToken cancellationToken)
        {
            if (builtinCommand == null)
            {
                return(Result.ReportError("builtinCommand is null"));
            }

            using (var context = new ZvsContext(EntityContextConnection))
            {
                var existingC = await context.BuiltinCommands.FirstOrDefaultAsync(o => o.UniqueIdentifier == builtinCommand.UniqueIdentifier, cancellationToken);

                var wasModified = false;
                if (existingC == null)
                {
                    context.BuiltinCommands.Add(builtinCommand);
                    wasModified = true;
                }
                else
                {
                    PropertyChangedEventHandler handler = (s, a) => wasModified = true;
                    existingC.PropertyChanged += handler;

                    existingC.Name         = builtinCommand.Name;
                    existingC.CustomData1  = builtinCommand.CustomData1;
                    existingC.CustomData2  = builtinCommand.CustomData2;
                    existingC.ArgumentType = builtinCommand.ArgumentType;
                    existingC.Description  = builtinCommand.Description;
                    existingC.Help         = builtinCommand.Help;

                    existingC.PropertyChanged -= handler;

                    var addded =
                        builtinCommand.Options.Where(option => existingC.Options.All(o => o.Name != option.Name))
                        .ToList();
                    foreach (var option in addded)
                    {
                        existingC.Options.Add(option);
                        wasModified = true;
                    }

                    var removed =
                        existingC.Options.Where(option => builtinCommand.Options.All(o => o.Name != option.Name)).ToList();
                    foreach (var option in removed)
                    {
                        context.CommandOptions.Local.Remove(option);
                        wasModified = true;
                    }
                }

                if (wasModified)
                {
                    return(await context.TrySaveChangesAsync(cancellationToken));
                }

                return(Result.ReportSuccess("Nothing to update"));
            }
        }
        public async Task RegisterAsyncOptionRemoveTest()
        {
            //arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());
            var bcb = new BuiltinCommandBuilder(dbConnection);

            var builtinCommand = new BuiltinCommand
            {
                Name             = "Unit Test Builtin Command",
                UniqueIdentifier = "BUILTIN_COMMAND1",
            };

            var option1 = new CommandOption
            {
                Name = "Option 1"
            };
            var option2 = new CommandOption
            {
                Name = "Option 2"
            };

            builtinCommand.Options.Add(option1);
            builtinCommand.Options.Add(option2);

            using (var context = new ZvsContext(dbConnection))
            {
                context.BuiltinCommands.Add(builtinCommand);
                await context.SaveChangesAsync();
            }

            builtinCommand.Options.Remove(option2);

            //act
            var result = await bcb.RegisterAsync(builtinCommand, CancellationToken.None);

            BuiltinCommand setting;

            using (var context = new ZvsContext(dbConnection))
            {
                setting = await context.BuiltinCommands
                          .Include(o => o.Options)
                          .FirstOrDefaultAsync(o => o.UniqueIdentifier == builtinCommand.UniqueIdentifier);
            }

            //assert
            Console.WriteLine(result.Message);
            Assert.IsFalse(result.HasError, result.Message);
            Assert.IsNotNull(setting, "Expected new builtin command setting saved to DB");
            Assert.IsTrue(setting.Options.Count == 1, "Expected 1 option!");
            Assert.IsTrue(setting.Options[0].Name == option1.Name);
        }
        public async Task<Result> RegisterAsync(BuiltinCommand builtinCommand, CancellationToken cancellationToken)
        {
            if (builtinCommand == null)
                return Result.ReportError("builtinCommand is null");

            using (var context = new ZvsContext(EntityContextConnection))
            {
                var existingC = await context.BuiltinCommands.FirstOrDefaultAsync(o => o.UniqueIdentifier == builtinCommand.UniqueIdentifier, cancellationToken);
                var wasModified = false;
                if (existingC == null)
                {
                    context.BuiltinCommands.Add(builtinCommand);
                    wasModified = true;
                }
                else
                {
                    PropertyChangedEventHandler handler = (s, a) => wasModified = true;
                    existingC.PropertyChanged += handler;

                    existingC.Name = builtinCommand.Name;
                    existingC.CustomData1 = builtinCommand.CustomData1;
                    existingC.CustomData2 = builtinCommand.CustomData2;
                    existingC.ArgumentType = builtinCommand.ArgumentType;
                    existingC.Description = builtinCommand.Description;
                    existingC.Help = builtinCommand.Help;

                    existingC.PropertyChanged -= handler;

                    var addded =
                        builtinCommand.Options.Where(option => existingC.Options.All(o => o.Name != option.Name))
                            .ToList();
                    foreach (var option in addded)
                    {
                        existingC.Options.Add(option);
                        wasModified = true;
                    }

                    var removed =
                        existingC.Options.Where(option => builtinCommand.Options.All(o => o.Name != option.Name)).ToList();
                    foreach (var option in removed)
                    {
                        context.CommandOptions.Local.Remove(option);
                        wasModified = true;
                    }
                }

                if (wasModified)
                    return await context.TrySaveChangesAsync(cancellationToken);

                return Result.ReportSuccess("Nothing to update");
            }
        }
        public async Task ExecuteBuiltinCommandAsyncGroupOnNoDevicesTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var groupOnIdsRequestSentToAdapter = new List <Group>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    ActivateGroupAsyncGroup = async g => groupOnIdsRequestSentToAdapter.Add(g)
                }
            };
            var log = new StubIFeedback <LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var group = new Group
                {
                    Name = "Test Group"
                };
                context.Groups.Add(group);

                var builtinCommand = new BuiltinCommand
                {
                    Name             = "Turn on a Group",
                    UniqueIdentifier = "GROUP_ON"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result =
                    await
                    commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand,
                                                                 group.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(result.Message.Contains("no devices found "), "Expected to see 'no devices found' in log when executed group with no devices");
            }
        }
예제 #10
0
        public async Task ExecuteBuiltinCommandAsyncRepollAllTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var repollDeviceIdRequestSentToAdapter = new List <int>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled         = true,
                    RepollAsyncDevice = async d => repollDeviceIdRequestSentToAdapter.Add(d.Id)
                }
            };
            var log = new StubIFeedback <LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device  = UnitTesting.CreateFakeDevice();
            var device2 = UnitTesting.CreateFakeDevice();

            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                context.Devices.Add(device2);
                var builtinCommand = new BuiltinCommand
                {
                    Name             = "Repoll all",
                    UniqueIdentifier = "REPOLL_ALL"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, device.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
                Assert.IsTrue(repollDeviceIdRequestSentToAdapter.Count == 2, "Process did not run the correct amount of commands.");
                Assert.IsTrue(repollDeviceIdRequestSentToAdapter[0] == device.Id, "Wrong command processed");
                Assert.IsTrue(repollDeviceIdRequestSentToAdapter[1] == device2.Id, "Wrong command processed");
            }
        }
예제 #11
0
        public async Task ExecuteBuiltinCommandAsyncRepollDisabledAdapterMeTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = false,
                }
            };
            var log = new StubIFeedback <LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device = UnitTesting.CreateFakeDevice();

            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "REPOLL_ME"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, device.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(result.Message.Contains("adapter is disabled"), "Expect error message to contain 'adapter is disabled'");
            }
        }
예제 #12
0
        public async Task ExecuteBuiltinCommandInvlaidDeviceIdAsyncRepollMeTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var repollDeviceIdRequestSentToAdapter = new List <int>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled         = true,
                    RepollAsyncDevice = async d => repollDeviceIdRequestSentToAdapter.Add(d.Id)
                }
            };
            var log = new StubIFeedback <LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "REPOLL_ME"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, 12.ToString(CultureInfo.InvariantCulture), "", cts.Token);

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(result.Message.Contains("Cannot find device "), "Expect error message to contain 'Cannot find device '");
            }
        }
예제 #13
0
        public async Task RunCommandAsyncBuiltinCommand()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    ProcessDeviceTypeCommandAsyncDeviceTypeDeviceDeviceTypeCommandString = (adapterDevice, command, argument, argument2) => Task.FromResult(0)
                }
            };
            var log = new StubIFeedback <LogEntry>();

            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "TIMEDELAY"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.RunCommandAsync(builtinCommand.Id, "1", "", cts.Token);

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
            }
        }
예제 #14
0
        public async Task ExecuteBuiltinCommandAsyncTimeDelayTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager    = new StubIAdapterManager();
            var log               = new StubIFeedback <LogEntry>();
            var cts               = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "TIMEDELAY"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                var sw = new Stopwatch();

                //Act
                sw.Start();
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, "1", "", cts.Token);

                sw.Stop();

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
                Assert.IsFalse(sw.Elapsed < TimeSpan.FromMilliseconds(1000), "Time delay was not long enough");
                Assert.IsFalse(sw.Elapsed > TimeSpan.FromMilliseconds(1300), "Time delay was too long");
            }
        }
        public async Task ExecuteBuiltinCommandAsyncRepollDisabledAdapterMeTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = false,
                }
            };
            var log = new StubIFeedback<LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device = UnitTesting.CreateFakeDevice();
            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "REPOLL_ME"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, device.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);
                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(result.Message.Contains("adapter is disabled"), "Expect error message to contain 'adapter is disabled'");
            }
        }
        public async Task ExecuteBuiltinCommandInvlaidDeviceIdAsyncRepollMeTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var repollDeviceIdRequestSentToAdapter = new List<int>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    RepollAsyncDevice = async d => repollDeviceIdRequestSentToAdapter.Add(d.Id)
                }
            };
            var log = new StubIFeedback<LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "REPOLL_ME"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, 12.ToString(CultureInfo.InvariantCulture), "", cts.Token);
                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(result.Message.Contains("Cannot find device "), "Expect error message to contain 'Cannot find device '");
            }
        }
예제 #17
0
        internal async Task <Result> ExecuteBuiltinCommandAsync(BuiltinCommand command, string argument, string argument2, CancellationToken cancellationToken)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                switch (command.UniqueIdentifier)
                {
                case "TIMEDELAY":
                {
                    int delay;
                    int.TryParse(argument, out delay);
                    await Task.Delay(delay * 1000, cancellationToken);

                    return(Result.ReportSuccessFormat("{0} second time delay complete", delay));
                }

                case "REPOLL_ME":
                {
                    int dId;
                    int.TryParse(argument, out dId);

                    var device = await context.Devices
                                 .Include(o => o.Type.Adapter)
                                 .FirstOrDefaultAsync(o => o.Type.UniqueIdentifier != "BUILTIN" && o.Id == dId,
                                                      cancellationToken);

                    if (device == null)
                    {
                        return(Result.ReportErrorFormat("Cannot find device with id of {0}", dId));
                    }

                    var adapter = AdapterManager.FindZvsAdapter(device.Type.Adapter.AdapterGuid);
                    if (adapter == null)
                    {
                        return
                            (Result.ReportErrorFormat(
                                 "Re-poll of {0} failed, the associated adapter is not loaded", device.Name));
                    }

                    if (!adapter.IsEnabled)
                    {
                        return(Result.ReportErrorFormat("Re-poll of {0} failed, adapter is disabled", device.Name));
                    }

                    await adapter.RepollAsync(device);

                    return(Result.ReportSuccessFormat("Re-poll of {0} ({1}) complete", device.Name, device.Id));
                }

                case "REPOLL_ALL":
                {
                    var devices = await context.Devices
                                  .Include(o => o.Type.Adapter)
                                  .Where(o => o.Type.UniqueIdentifier != "BUILTIN")
                                  .ToListAsync(cancellationToken);

                    foreach (var device in devices)
                    {
                        await
                        ExecuteBuiltinCommandAsync(new BuiltinCommand { UniqueIdentifier = "REPOLL_ME" },
                                                   device.Id.ToString(CultureInfo.InvariantCulture), "", cancellationToken);
                    }

                    return(Result.ReportSuccessFormat("Built-in cmd re-poll {0} devices complete", devices.Count));
                }

                case "GROUP_ON":
                case "GROUP_OFF":
                {
                    int gId   = int.TryParse(argument, out gId) ? gId : 0;
                    var group = await context.Groups
                                .Include(o => o.Devices)
                                .FirstOrDefaultAsync(o => o.Id == gId, cancellationToken);

                    if (group == null)
                    {
                        return(Result.ReportErrorFormat("Command {0} failed. Invalid group id", command.Name));
                    }

                    if (group.Devices.Count < 1)
                    {
                        return(Result.ReportErrorFormat("Unable to {0} {1}, no devices found in the group", command.Name, group.Name));
                    }

                    var adapterGuids = await context.Devices
                                       .Where(o => o.Groups.Any(g => g.Id == gId))
                                       .Select(o => o.Type.Adapter.AdapterGuid)
                                       .Distinct()
                                       .ToListAsync(cancellationToken);

                    //EXECUTE ON ALL Adapters
                    foreach (var adapter in adapterGuids.Select(adapterGuid => AdapterManager.FindZvsAdapter(adapterGuid)).Where(adapter => adapter != null && adapter.IsEnabled))
                    {
                        if (command.UniqueIdentifier == "GROUP_ON")
                        {
                            await adapter.ActivateGroupAsync(@group);
                        }
                        else
                        {
                            await adapter.DeactivateGroupAsync(@group);
                        }
                    }

                    return(Result.ReportSuccessFormat("{0} {2}, {1} complete",
                                                      command.Name,
                                                      group.Name, command.Id));
                }

                case "RUN_SCENE":
                {
                    int id;
                    int.TryParse(argument, out id);

                    var sceneRunner = new SceneRunner(Log, this, EntityContextConnection);
                    var sceneResult = await sceneRunner.RunSceneAsync(id, cancellationToken);

                    var details = $"{sceneResult.Message} Built-in cmd '{command.Name}' ({command.Id}) complete";

                    return(sceneResult.HasError ? Result.ReportError(details) : Result.ReportSuccess(details));
                }

                default:
                {
                    return
                        (Result.ReportErrorFormat(
                             "Built-in cmd {0} failed. No logic defined for this built-in command.", command.Id));
                }
                }
            }
        }
        public async Task ExecuteBuiltinCommandAsyncRepollAllTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var repollDeviceIdRequestSentToAdapter = new List<int>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    RepollAsyncDevice = async d => repollDeviceIdRequestSentToAdapter.Add(d.Id)
                }
            };
            var log = new StubIFeedback<LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device = UnitTesting.CreateFakeDevice();
            var device2 = UnitTesting.CreateFakeDevice();
            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                context.Devices.Add(device2);
                var builtinCommand = new BuiltinCommand
                {
                    Name = "Repoll all",
                    UniqueIdentifier = "REPOLL_ALL"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, device.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);
                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
                Assert.IsTrue(repollDeviceIdRequestSentToAdapter.Count == 2, "Process did not run the correct amount of commands.");
                Assert.IsTrue(repollDeviceIdRequestSentToAdapter[0] == device.Id, "Wrong command processed");
                Assert.IsTrue(repollDeviceIdRequestSentToAdapter[1] == device2.Id, "Wrong command processed");
            }
        }
        public async Task RegisterAsyncOptionRemoveTest()
        {
            //arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());
            var bcb = new BuiltinCommandBuilder(dbConnection);

            var builtinCommand = new BuiltinCommand
            {
                Name = "Unit Test Builtin Command",
                UniqueIdentifier = "BUILTIN_COMMAND1",

            };

            var option1 = new CommandOption
            {
                Name = "Option 1"
            };
            var option2 = new CommandOption
            {
                Name = "Option 2"
            };
            builtinCommand.Options.Add(option1);
            builtinCommand.Options.Add(option2);

            using (var context = new ZvsContext(dbConnection))
            {
                context.BuiltinCommands.Add(builtinCommand);
                await context.SaveChangesAsync();
            }

            builtinCommand.Options.Remove(option2);

            //act
            var result = await bcb.RegisterAsync(builtinCommand, CancellationToken.None);

            BuiltinCommand setting;
            using (var context = new ZvsContext(dbConnection))
            {
                setting = await context.BuiltinCommands
                        .Include(o => o.Options)
                        .FirstOrDefaultAsync(o => o.UniqueIdentifier == builtinCommand.UniqueIdentifier);

            }

            //assert 
            Console.WriteLine(result.Message);
            Assert.IsFalse(result.HasError, result.Message);
            Assert.IsNotNull(setting, "Expected new builtin command setting saved to DB");
            Assert.IsTrue(setting.Options.Count == 1, "Expected 1 option!");
            Assert.IsTrue(setting.Options[0].Name == option1.Name);
        }
        public async Task ExecuteBuiltinCommandAsyncGroupOnBadIdTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager = new StubIAdapterManager();
            var log = new StubIFeedback<LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device = UnitTesting.CreateFakeDevice();
            var device2 = UnitTesting.CreateFakeDevice();
            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "GROUP_ON"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, "0", "", cts.Token);
                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(result.Message.Contains("Invalid group"), "Expected to see 'Invalid group' in log");
            }
        }
        public async Task ExecuteBuiltinCommandAsyncGroupOnNoDevicesTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var groupOnIdsRequestSentToAdapter = new List<Group>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    ActivateGroupAsyncGroup = async g => groupOnIdsRequestSentToAdapter.Add(g)
                }
            };
            var log = new StubIFeedback<LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var group = new Group
                {
                    Name = "Test Group"
                };
                context.Groups.Add(group);

                var builtinCommand = new BuiltinCommand
                {
                    Name = "Turn on a Group",
                    UniqueIdentifier = "GROUP_ON"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result =
                    await
                        commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand,
                            group.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);
                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(result.Message.Contains("no devices found "), "Expected to see 'no devices found' in log when executed group with no devices");
            }
        }
        public async Task ExecuteBuiltinCommandAsyncGroupOffTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var groupOnIdsRequestSentToAdapter = new List<Group>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    DeactivateGroupAsyncGroup = async g => groupOnIdsRequestSentToAdapter.Add(g)
                }
            };
            var log = new StubIFeedback<LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device = UnitTesting.CreateFakeDevice();
            var device2 = UnitTesting.CreateFakeDevice();
            var device3 = UnitTesting.CreateFakeDevice();
            using (var context = new ZvsContext(dbConnection))
            {
                context.Devices.Add(device);
                context.Devices.Add(device2);
                context.Devices.Add(device3);

                var group = new Group
                {
                    Name = "Test Group"
                };
                group.Devices.Add(device);
                group.Devices.Add(device2);
                context.Groups.Add(group);

                var builtinCommand = new BuiltinCommand
                {
                    Name = "Turn off Group",
                    UniqueIdentifier = "GROUP_OFF"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, group.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);
                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
                Assert.IsTrue(groupOnIdsRequestSentToAdapter.Count == 2, "Process did not run the correct amount of commands.");
                Assert.IsTrue(group.Id == groupOnIdsRequestSentToAdapter[0].Id, "Ran the wrong group!");
            }
        }
        public async Task ExecuteBuiltinCommandAsyncSceneTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var deviceCommandIds = new List<int>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    ProcessDeviceCommandAsyncDeviceDeviceCommandStringString = async (adapterDevice, command, argument, argument2) => deviceCommandIds.Add(command.Id)
                }
            };
            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e);
                    return Task.FromResult(0);
                }
            };

            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device = UnitTesting.CreateFakeDevice();
            using (var context = new ZvsContext(dbConnection))
            {
                var deviceCommand = new DeviceCommand
                {
                    Name = "Turn On"
                };
                device.Commands.Add(deviceCommand);
                context.Devices.Add(device);

                var scene = new Scene
                {
                    Name = "Test Scene"
                };
                scene.Commands.Add(new SceneStoredCommand
                {
                    Command = deviceCommand,
                    Argument = "0"
                });
                context.Scenes.Add(scene);

                var builtinCommand = new BuiltinCommand
                {
                    Name = "Activate Scene",
                    UniqueIdentifier = "RUN_SCENE"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, scene.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);
                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
                Assert.IsTrue(deviceCommandIds.Count == 1, "Process did not run the correct amount of commands.");
                Assert.IsTrue(deviceCommand.Id == deviceCommandIds[0], "Ran the wrong scene!");
            }
        }
        public async Task ExecuteBuiltinCommandAsyncUnknownCommandTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var deviceCommandIds = new List<int>();
            var adapterManager = new StubIAdapterManager();
            var log = new StubIFeedback<LogEntry>();

            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var builtinCommand = new BuiltinCommand
                {
                    Name = "Unknown Built-in Command",
                    UniqueIdentifier = "UNKNOWN_COMMAND_TYPE"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, "", "", cts.Token);
                Console.WriteLine(result.Message);

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(deviceCommandIds.Count == 0, "Process did not run the correct amount of commands.");
            }
        }
        public async Task RunCommandAsyncBuiltinCommand()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    ProcessDeviceTypeCommandAsyncDeviceTypeDeviceDeviceTypeCommandString = (adapterDevice, command, argument, argument2) => Task.FromResult(0)
                }
            };
            var log = new StubIFeedback<LogEntry>();

            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "TIMEDELAY"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.RunCommandAsync(builtinCommand.Id, "1", "", cts.Token);
                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
            }
        }
        public async Task ExecuteBuiltinCommandAsyncTimeDelayTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager = new StubIAdapterManager();
            var log = new StubIFeedback<LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            using (var context = new ZvsContext(dbConnection))
            {
                var builtinCommand = new BuiltinCommand
                {
                    UniqueIdentifier = "TIMEDELAY"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());
                var sw = new Stopwatch();

                //Act
                sw.Start();
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, "1", "", cts.Token);
                sw.Stop();

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
                Assert.IsFalse(sw.Elapsed < TimeSpan.FromMilliseconds(1000), "Time delay was not long enough");
                Assert.IsFalse(sw.Elapsed > TimeSpan.FromMilliseconds(1300), "Time delay was too long");
            }
        }
예제 #27
0
        public async Task ExecuteBuiltinCommandAsyncSceneTest()
        {
            //Arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var deviceCommandIds = new List <int>();
            var adapterManager   = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    ProcessDeviceCommandAsyncDeviceDeviceCommandStringString = async(adapterDevice, command, argument, argument2) => deviceCommandIds.Add(command.Id)
                }
            };
            var log = new StubIFeedback <LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e);
                    return(Task.FromResult(0));
                }
            };

            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            var device = UnitTesting.CreateFakeDevice();

            using (var context = new ZvsContext(dbConnection))
            {
                var deviceCommand = new DeviceCommand
                {
                    Name = "Turn On"
                };
                device.Commands.Add(deviceCommand);
                context.Devices.Add(device);

                var scene = new Scene
                {
                    Name = "Test Scene"
                };
                scene.Commands.Add(new SceneStoredCommand
                {
                    Command  = deviceCommand,
                    Argument = "0"
                });
                context.Scenes.Add(scene);

                var builtinCommand = new BuiltinCommand
                {
                    Name             = "Activate Scene",
                    UniqueIdentifier = "RUN_SCENE"
                };
                context.Commands.Add(builtinCommand);
                await context.SaveChangesAsync(new CancellationToken());

                //Act
                var result = await commmandProcessor.ExecuteBuiltinCommandAsync(builtinCommand, scene.Id.ToString(CultureInfo.InvariantCulture), "", cts.Token);

                Console.WriteLine(result.Message);

                //Assert
                Assert.IsFalse(result.HasError);
                Assert.IsTrue(deviceCommandIds.Count == 1, "Process did not run the correct amount of commands.");
                Assert.IsTrue(deviceCommand.Id == deviceCommandIds[0], "Ran the wrong scene!");
            }
        }
        internal async Task<Result> ExecuteBuiltinCommandAsync(BuiltinCommand command, string argument, string argument2, CancellationToken cancellationToken)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                switch (command.UniqueIdentifier)
                {
                    case "TIMEDELAY":
                        {
                            int delay;
                            int.TryParse(argument, out delay);
                            await Task.Delay(delay * 1000, cancellationToken);
                            return Result.ReportSuccessFormat("{0} second time delay complete", delay);
                        }
                    case "REPOLL_ME":
                        {
                            int dId;
                            int.TryParse(argument, out dId);

                            var device = await context.Devices
                                .Include(o => o.Type.Adapter)
                                .FirstOrDefaultAsync(o => o.Type.UniqueIdentifier != "BUILTIN" && o.Id == dId,
                                    cancellationToken);

                            if (device == null)
                                return Result.ReportErrorFormat("Cannot find device with id of {0}", dId);

                            var adapter = AdapterManager.FindZvsAdapter(device.Type.Adapter.AdapterGuid);
                            if (adapter == null)
                                return
                                    Result.ReportErrorFormat(
                                        "Re-poll of {0} failed, the associated adapter is not loaded", device.Name);

                            if (!adapter.IsEnabled)
                                return Result.ReportErrorFormat("Re-poll of {0} failed, adapter is disabled", device.Name);

                            await adapter.RepollAsync(device);
                            return Result.ReportSuccessFormat("Re-poll of {0} ({1}) complete", device.Name, device.Id);
                        }
                    case "REPOLL_ALL":
                        {
                            var devices = await context.Devices
                                .Include(o => o.Type.Adapter)
                                .Where(o => o.Type.UniqueIdentifier != "BUILTIN")
                                .ToListAsync(cancellationToken);

                            foreach (var device in devices)
                            {
                                await
                                    ExecuteBuiltinCommandAsync(new BuiltinCommand { UniqueIdentifier = "REPOLL_ME" },
                                        device.Id.ToString(CultureInfo.InvariantCulture), "", cancellationToken);
                            }

                            return Result.ReportSuccessFormat("Built-in cmd re-poll {0} devices complete", devices.Count);

                        }
                    case "GROUP_ON":
                    case "GROUP_OFF":
                        {
                            int gId = int.TryParse(argument, out gId) ? gId : 0;
                            var group = await context.Groups
                                .Include(o => o.Devices)
                                .FirstOrDefaultAsync(o => o.Id == gId, cancellationToken);

                            if (group == null)
                                return Result.ReportErrorFormat("Command {0} failed. Invalid group id", command.Name);

                            if (group.Devices.Count < 1)
                                return Result.ReportErrorFormat("Unable to {0} {1}, no devices found in the group", command.Name, group.Name);

                            var adapterGuids = await context.Devices
                                .Where(o => o.Groups.Any(g => g.Id == gId))
                                .Select(o => o.Type.Adapter.AdapterGuid)
                                .Distinct()
                                .ToListAsync(cancellationToken);

                            //EXECUTE ON ALL Adapters
                            foreach (var adapter in adapterGuids.Select(adapterGuid => AdapterManager.FindZvsAdapter(adapterGuid)).Where(adapter => adapter != null && adapter.IsEnabled))
                            {
                                if (command.UniqueIdentifier == "GROUP_ON")
                                    await adapter.ActivateGroupAsync(@group);
                                else
                                    await adapter.DeactivateGroupAsync(@group);
                            }

                            return Result.ReportSuccessFormat("{0} {2}, {1} complete",
                                command.Name,
                                group.Name, command.Id);

                        }
                    case "RUN_SCENE":
                        {
                            int id;
                            int.TryParse(argument, out id);

                            var sceneRunner = new SceneRunner(Log, this, EntityContextConnection);
                            var sceneResult = await sceneRunner.RunSceneAsync(id, cancellationToken);

                            var details = $"{sceneResult.Message} Built-in cmd '{command.Name}' ({command.Id}) complete";

                            return sceneResult.HasError ? Result.ReportError(details) : Result.ReportSuccess(details);
                        }
                    default:
                        {
                            return
                                Result.ReportErrorFormat(
                                    "Built-in cmd {0} failed. No logic defined for this built-in command.", command.Id);
                        }
                }

            }
        }
        public async Task RegisterAsyncUpdateTest()
        {
            //arrange 
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "bcb-RegisterAsyncUpdateTest" };
            Database.SetInitializer(new CreateFreshDbInitializer());
            var bcb = new BuiltinCommandBuilder(dbConnection);

            var builtinCommand = new BuiltinCommand
            {
                Name = "Unit Test Builtin Command",
                UniqueIdentifier = "BUILTIN_COMMAND1"
            };

            using (var context = new ZvsContext(dbConnection))
            {
                context.BuiltinCommands.Add(builtinCommand);
                await context.SaveChangesAsync();
            }

            builtinCommand.Name = "New Name";

            //act
            var result = await bcb.RegisterAsync(builtinCommand, CancellationToken.None);

            BuiltinCommand setting;
            using (var context = new ZvsContext(dbConnection))
            {
                setting =
                    await
                        context.BuiltinCommands.FirstOrDefaultAsync(
                            o => o.UniqueIdentifier == builtinCommand.UniqueIdentifier);
            }

            //assert 
            Console.WriteLine(result.Message);
            Assert.IsFalse(result.HasError, result.Message);
            Assert.IsNotNull(setting, "Expected new builtin command setting saved to DB");
            Assert.IsTrue(setting.Name == "New Name");
        }