internal async Task<Result> ExecuteDeviceTypeCommandAsync(DeviceTypeCommand command, string argument, string argument2, CancellationToken cancellationToken)
        {
            using (var context = new ZvsContext(EntityContextConnection))
            {
                int dId = int.TryParse(argument2, out dId) ? dId : 0;

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

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

                var commandAction =
                    $"{command.Name}{(string.IsNullOrEmpty(argument) ? "" : " " + argument)} {device.Name}";

                var aGuid = device.Type.Adapter.AdapterGuid;
                var adapter = AdapterManager.FindZvsAdapter(aGuid);
                if (adapter == null)
                {
                    return Result.ReportErrorFormat("{0} failed, device adapter is not loaded!",
                        commandAction);
                }

                if (!adapter.IsEnabled)
                    return Result.ReportErrorFormat("{0} failed because the {1} adapter is {2}",
                        commandAction,
                        device.Type.Adapter.Name,
                        adapter.IsEnabled ? "not ready" : "disabled");

                await adapter.ProcessDeviceTypeCommandAsync(device.Type, device, command, argument);
                return Result.ReportSuccessFormat("{0} complete", commandAction);
            }
        }
Пример #2
0
        public override async Task ProcessDeviceTypeCommandAsync(DeviceType deviceType, Device device,
            DeviceTypeCommand command, string argument)
        {

            var miCommand = command.CustomData1;
            var zone = command.CustomData2;
            var ip = (from d in device.Values where d.Name == "IPAddress" select d.Value).FirstOrDefault();
            decimal level;
            decimal.TryParse(argument, out level);
            await _controller.Send(ip, miCommand, zone, level);

            await Log.ReportInfoAsync(string.Format("{0} Command Sent Command:{1}, Zone:{2}, IP:{3}, Level:{4}", Name, miCommand, zone, ip, level), CancellationToken);
        }
Пример #3
0
 private Task Publish(DeviceType deviceType, Device device, DeviceTypeCommand deviceTypeCommand,
                      DeviceCommand deviceCommand, string argument)
 {
     JavaScriptSerializer js = new JavaScriptSerializer();
     var o =
         new
             {
                 DeviceName = device.Name,
                 DeviceCommandName = (deviceCommand == null ? null : deviceCommand.Name),
                 DeviceTypeCommandName = (deviceTypeCommand == null ? null : deviceTypeCommand.Name),
                 DeviceTypeCommandValue = (deviceTypeCommand == null ? null : deviceTypeCommand.Value),
                 Argument = argument,
                 DeviceTypeName = (device == null || device.Type == null ? null : device.Type.Name),
                 device.CurrentLevelInt,
                 device.CurrentLevelText
             };
     var str = js.Serialize(o);
     client.Publish(SystemTopic, Encoding.UTF8.GetBytes(str));
     return Task.FromResult(0);
 }
 public override Task ProcessDeviceTypeCommandAsync(DeviceType deviceType, Device device, DeviceTypeCommand command, string argument)
 {
     throw new NotImplementedException();
 }
Пример #5
0
 public override Task ProcessDeviceTypeCommandAsync(DeviceType deviceType, Device device, DeviceTypeCommand command, string argument)
 {
     return Publish(deviceType, device, command, null, argument);
    
 }
Пример #6
0
        public override async Task ProcessDeviceTypeCommandAsync(DeviceType deviceType, Device device, DeviceTypeCommand command, string argument)
        {
            var nodeNumber = Convert.ToByte(device.NodeNumber);
            if (!IsNodeReady(nodeNumber))
            {
                await Log.ReportInfoFormatAsync(CancellationToken, "Failed to issue command on {0}, node {1}. Node not ready.", device.Name, nodeNumber);
                return;
            }

            if (deviceType.UniqueIdentifier == OpenzWaveDeviceTypes.Controller.ToString())
            {
                #region Controller Commands
                switch (command.UniqueIdentifier)
                {
                    case "RESET":
                        {
                            MManager.ResetController(MHomeId);
                            break;
                        }
                    case "ADDDEVICE":
                        {
                            var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.AddDevice, (byte)device.NodeNumber);
                            dlg.ShowDialog();
                            dlg.Dispose();
                            break;
                        }

                    case "CreateNewPrimary":
                        {
                            var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.CreateNewPrimary, (byte)device.NodeNumber);
                            dlg.ShowDialog();
                            dlg.Dispose();
                            break;
                        }
                    case "ReceiveConfiguration":
                        {
                            var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.ReceiveConfiguration, (byte)device.NodeNumber);
                            dlg.ShowDialog();
                            dlg.Dispose();
                            break;
                        }

                    case "RemoveDevice":
                        {
                            var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.RemoveDevice, (byte)device.NodeNumber);
                            dlg.ShowDialog();
                            dlg.Dispose();
                            break;
                        }
                    case "TransferPrimaryRole":
                        {
                            var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.TransferPrimaryRole, (byte)device.NodeNumber);
                            dlg.ShowDialog();
                            dlg.Dispose();
                            break;
                        }
                    case "HasNodeFailed":
                        {
                            var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.HasNodeFailed, (byte)device.NodeNumber);
                            dlg.ShowDialog();
                            dlg.Dispose();
                            break;
                        }
                    case "RemoveFailedNode":
                        {
                            var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.RemoveFailedNode, (byte)device.NodeNumber);
                            dlg.ShowDialog();
                            dlg.Dispose();
                            break;
                        }
                    case "ReplaceFailedNode":
                        {
                            var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.ReplaceFailedNode, (byte)device.NodeNumber);
                            dlg.ShowDialog();
                            dlg.Dispose();
                            break;
                        }
                }
                #endregion
            }
            else if (deviceType.UniqueIdentifier == OpenzWaveDeviceTypes.Switch.ToString())
            {
                #region Switch command handeling
                switch (command.UniqueIdentifier)
                {
                    case "MOMENTARY":
                        {
                            int delay;
                            int.TryParse(argument, out delay);
                            var nodeId = (byte)device.NodeNumber;

                            MManager.SetNodeOn(MHomeId, nodeId);
                            await Task.Delay(delay);
                            MManager.SetNodeOff(MHomeId, nodeId);

                            break;

                        }
                    case "TURNON":
                        {
                            MManager.SetNodeOn(MHomeId, (byte)device.NodeNumber);
                            break;
                        }
                    case "TURNOFF":
                        {
                            MManager.SetNodeOff(MHomeId, (byte)device.NodeNumber);
                            break;
                        }
                }
                #endregion
            }
            else if (deviceType.UniqueIdentifier == OpenzWaveDeviceTypes.Dimmer.ToString())
            {
                #region Dimmer command handling
                switch (command.UniqueIdentifier)
                {
                    case "TURNON":
                        {
                            using (var context = new ZvsContext(EntityContextConnection))
                            {
                                var value = await device.GetDeviceTypeValueAsync(OpenzWaveDeviceTypeSettings.DefaultDimmerOnLevel.ToString(), context);

                                if (value != null)
                                {
                                    byte bValue = byte.TryParse(value, out bValue) ? bValue : (byte)99;
                                    MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, bValue);
                                    break;
                                }
                            }

                            MManager.SetNodeOn(MHomeId, (byte)device.NodeNumber);
                            break;
                        }
                    case "TURNOFF":
                        {
                            MManager.SetNodeOff(MHomeId, (byte)device.NodeNumber);
                            break;
                        }
                    case "SETPRESETLEVEL":
                        {
                            switch (argument)
                            {
                                case "0%":
                                    MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(0));
                                    break;
                                case "20%":
                                    MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(20));
                                    break;
                                case "40%":
                                    MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(40));
                                    break;
                                case "60%":
                                    MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(60));
                                    break;
                                case "80%":
                                    MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(80));
                                    break;
                                case "100%":
                                    MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(100));
                                    break;
                                case "255":
                                    MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(255));
                                    break;
                            }
                            break;
                        }
                }
                #endregion
            }
            else if (deviceType.UniqueIdentifier == OpenzWaveDeviceTypes.Thermostat.ToString())
            {
                #region Thermostat Command Handling
                switch (command.UniqueIdentifier)
                {
                    case "SETENERGYMODE":
                        {
                            MManager.SetNodeOff(MHomeId, (byte)device.NodeNumber);
                            break;
                        }
                    case "SETCONFORTMODE":
                        {
                            MManager.SetNodeOn(MHomeId, (byte)device.NodeNumber);
                            break;
                        }
                }
                #endregion
            }
        }
Пример #7
0
        public override async Task OnDeviceTypesCreating(DeviceTypeBuilder deviceTypeBuilder)
        {
            //Controller Type Devices
            var controllerDt = new DeviceType
            {
                UniqueIdentifier = OpenzWaveDeviceTypes.Controller.ToString(),
                Name = "OpenZWave Controller",
                ShowInList = true
            };
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "RESET",
                Name = "Reset Controller",
                ArgumentType = DataType.NONE,
                Description = "Erases all Z-Wave network settings from your controller. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "ADDDEVICE",
                Name = "Add Device to Network",
                ArgumentType = DataType.NONE,
                Description = "Adds a ZWave Device to your network. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "AddController",
                Name = "Add Controller to Network",
                ArgumentType = DataType.NONE,
                Description = "Adds a ZWave Controller to your network. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "CreateNewPrimary",
                Name = "Create New Primary",
                ArgumentType = DataType.NONE,
                Description = "Puts the target controller into receive configuration mode. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "ReceiveConfiguration",
                Name = "Receive Configuration",
                ArgumentType = DataType.NONE,
                Description = "Receives the network configuration from another controller. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "RemoveController",
                Name = "Remove Controller",
                ArgumentType = DataType.NONE,
                Description = "Removes a Controller from your network. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "RemoveDevice",
                Name = "Remove Device",
                ArgumentType = DataType.NONE,
                Description = "Removes a Device from your network. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "TransferPrimaryRole",
                Name = "Transfer Primary Role",
                ArgumentType = DataType.NONE,
                Description = "Transfers the primary role to another controller. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "HasNodeFailed",
                Name = "Has Node Failed",
                ArgumentType = DataType.NONE,
                Description = "Tests whether a node has failed. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "RemoveFailedNode",
                Name = "Remove Failed Node",
                ArgumentType = DataType.NONE,
                Description = "Removes the failed node from the controller's list. Argument2 = DeviceId."
            });
            controllerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "ReplaceFailedNode",
                Name = "Replace Failed Node",
                ArgumentType = DataType.NONE,
                Description = "Tests the failed node. Argument2 = DeviceId."
            });
            var result = await deviceTypeBuilder.RegisterAsync(AdapterGuid, controllerDt, CancellationToken);
            if (result.HasError)
                await
                    Log.ReportErrorFormatAsync(CancellationToken,
                        "An error occured when registering the OpenZWave controller device type. {0}", result.Message);


            //Switch Type Devices
            var switchDt = new DeviceType
            {
                UniqueIdentifier = OpenzWaveDeviceTypes.Switch.ToString(),
                Name = "OpenZWave Binary",
                ShowInList = true
            };
            switchDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "TURNON",
                Name = "Turn On",
                ArgumentType = DataType.NONE,
                Description = "Activates a switch. Argument2 = DeviceId."
            });
            switchDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "TURNOFF",
                Name = "Turn Off",
                ArgumentType = DataType.NONE,
                Description = "Deactivates a switch. Argument2 = DeviceId."
            });
            switchDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "MOMENTARY",
                Name = "Turn On for X milliseconds",
                ArgumentType = DataType.INTEGER,
                Description =
                    "Turns a device on for the specified number of milliseconds and then turns the device back off. Argument2 = DeviceId."
            });
            var switchSaveResult = await deviceTypeBuilder.RegisterAsync(AdapterGuid, switchDt, CancellationToken);
            if (switchSaveResult.HasError)
                await
                    Log.ReportErrorFormatAsync(CancellationToken,
                        "An error occured when registering the OpenZWave switch device type. {0}",
                        switchSaveResult.Message);

            //Dimmer Type Devices
            var dimmerDt = new DeviceType
            {
                UniqueIdentifier = OpenzWaveDeviceTypes.Dimmer.ToString(),
                Name = "OpenZWave Dimmer",
                ShowInList = true
            };
            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "TURNON",
                Name = "Turn On",
                ArgumentType = DataType.NONE,
                Description = "Activates a dimmer. Argument2 = DeviceId."
            });
            dimmerDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "TURNOFF",
                Name = "Turn Off",
                ArgumentType = DataType.NONE,
                Description = "Deactivates a dimmer. Argument2 = DeviceId."
            });

            var dimmerPresetCmd = new DeviceTypeCommand
            {
                UniqueIdentifier = "SETPRESETLEVEL",
                Name = "Set Level",
                ArgumentType = DataType.LIST,
                Description = "Sets a dimmer to a preset level. Argument2 = DeviceId."
            };
            dimmerPresetCmd.Options.Add(new CommandOption { Name = "0%" });
            dimmerPresetCmd.Options.Add(new CommandOption { Name = "20%" });
            dimmerPresetCmd.Options.Add(new CommandOption { Name = "40%" });
            dimmerPresetCmd.Options.Add(new CommandOption { Name = "60%" });
            dimmerPresetCmd.Options.Add(new CommandOption { Name = "80%" });
            dimmerPresetCmd.Options.Add(new CommandOption { Name = "100%" });
            dimmerPresetCmd.Options.Add(new CommandOption { Name = "255" });
            dimmerDt.Commands.Add(dimmerPresetCmd);
            var dimmerSaveResult = await deviceTypeBuilder.RegisterAsync(AdapterGuid, dimmerDt, CancellationToken);
            if (dimmerSaveResult.HasError)
                await
                    Log.ReportErrorFormatAsync(CancellationToken,
                        "An error occured when registering the OpenZWave dimmer device type. {0}",
                        dimmerSaveResult.Message);

            //Thermostat Type Devices
            var thermoDt = new DeviceType
            {
                UniqueIdentifier = OpenzWaveDeviceTypes.Thermostat.ToString(),
                Name = "OpenZWave Thermostat",
                ShowInList = true
            };
            thermoDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "SETENERGYMODE",
                Name = "Set Energy Mode",
                ArgumentType = DataType.NONE,
                Description = "Set thermostat to Energy Mode. Argument2 = DeviceId."
            });
            thermoDt.Commands.Add(new DeviceTypeCommand
            {
                UniqueIdentifier = "SETCONFORTMODE",
                Name = "Set Comfort Mode",
                ArgumentType = DataType.NONE,
                Description = "Set thermostat to Comfort Mode. (Run) Argument2 = DeviceId."
            });
            var thermoSaveResult = await deviceTypeBuilder.RegisterAsync(AdapterGuid, thermoDt, CancellationToken);
            if (thermoSaveResult.HasError)
                await
                    Log.ReportErrorFormatAsync(CancellationToken,
                        "An error occured when registering the OpenZWave thermostat device type. {0}",
                        thermoSaveResult.Message);

            var unknwonDt = new DeviceType
            {
                UniqueIdentifier = OpenzWaveDeviceTypes.Unknown.ToString(),
                Name = "OpenZWave Unknown",
                ShowInList = true
            };
            var unknownSaveResult = await deviceTypeBuilder.RegisterAsync(AdapterGuid, unknwonDt, CancellationToken);
            if (unknownSaveResult.HasError)
                await
                    Log.ReportErrorFormatAsync(CancellationToken,
                        "An error occured when registering the OpenZWave unknwon device type. {0}",
                        unknownSaveResult.Message);

            //Door Lock Type Devices
            var lockDt = new DeviceType
            {
                UniqueIdentifier = OpenzWaveDeviceTypes.Doorlock.ToString(),
                Name = "OpenZWave Door lock",
                ShowInList = true
            };
            var lockSaveResult = await deviceTypeBuilder.RegisterAsync(AdapterGuid, lockDt, CancellationToken);
            if (lockSaveResult.HasError)
                await
                    Log.ReportErrorFormatAsync(CancellationToken,
                        "An error occured when registering the OpenZWave door lock device type. {0}",
                        lockSaveResult.Message);

            //Sensors
            var sensorDt = new DeviceType
            {
                UniqueIdentifier = OpenzWaveDeviceTypes.Sensor.ToString(),
                Name = "OpenZWave Sensor",
                ShowInList = true
            };
            var sensorSaveResult = await deviceTypeBuilder.RegisterAsync(AdapterGuid, sensorDt, CancellationToken);
            if (sensorSaveResult.HasError)
                await
                    Log.ReportErrorFormatAsync(CancellationToken,
                        "An error occured when registering the OpenZWave sensor device type. {0}",
                        sensorSaveResult.Message);
            using (var context = new ZvsContext(EntityContextConnection))
            {
                ControllerTypeId = await context.DeviceTypes.Where(o => o.UniqueIdentifier == OpenzWaveDeviceTypes.Controller.ToString()).Select(o => o.Id).FirstOrDefaultAsync();
                SwitchTypeId = await context.DeviceTypes.Where(o => o.UniqueIdentifier == OpenzWaveDeviceTypes.Switch.ToString()).Select(o => o.Id).FirstOrDefaultAsync();
                DimmerTypeId = await context.DeviceTypes.Where(o => o.UniqueIdentifier == OpenzWaveDeviceTypes.Dimmer.ToString()).Select(o => o.Id).FirstOrDefaultAsync();
                ThermoTypeId = await context.DeviceTypes.Where(o => o.UniqueIdentifier == OpenzWaveDeviceTypes.Thermostat.ToString()).Select(o => o.Id).FirstOrDefaultAsync();
                UnknownTypeId = await context.DeviceTypes.Where(o => o.UniqueIdentifier == OpenzWaveDeviceTypes.Unknown.ToString()).Select(o => o.Id).FirstOrDefaultAsync();
                LockTypeId = await context.DeviceTypes.Where(o => o.UniqueIdentifier == OpenzWaveDeviceTypes.Doorlock.ToString()).Select(o => o.Id).FirstOrDefaultAsync();
                SensorTypeId = await context.DeviceTypes.Where(o => o.UniqueIdentifier == OpenzWaveDeviceTypes.Sensor.ToString()).Select(o => o.Id).FirstOrDefaultAsync();
            }
        }
        public async Task RunCommandAsyncDeviceTypeCommand()
        {
            //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);

            var device = UnitTesting.CreateFakeDevice();
            using (var context = new ZvsContext(dbConnection))
            {
                var deviceTypeCommand = new DeviceTypeCommand
                {
                    Name = "Turn On"
                };
                context.Commands.Add(deviceTypeCommand);
                context.Devices.Add(device);
                await context.SaveChangesAsync(CancellationToken.None);

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

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

            var commandsSendToAdapter = new List<int>();
            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = true,
                    ProcessDeviceTypeCommandAsyncDeviceTypeDeviceDeviceTypeCommandString = async (adapterDevice, command, argument, argument2) => commandsSendToAdapter.Add(command.Id)
                }
            };

            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))
            {
                var deviceTypeCommand = new DeviceTypeCommand
                {
                    Name = "Turn On"
                };
                device.Type.Commands.Add(deviceTypeCommand);
                context.Devices.Add(device);
                await context.SaveChangesAsync(CancellationToken.None);

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

                //Assert
                Assert.IsFalse(result.HasError);
                Assert.IsTrue(commandsSendToAdapter.Count == 1, "Process did not run the correct amount of commands.");
                Assert.IsTrue(commandsSendToAdapter[0] == deviceTypeCommand.Id, "Wrong command processed");
            }
        }
        public async Task ExecuteDeviceTypeCommandAsyncAdapterNotEnabledTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager = new StubIAdapterManager
            {
                FindZvsAdapterGuid = adapterGuid => new StubZvsAdapter
                {
                    IsEnabled = false,
                }
            };
            var ranstoredCommands = new List<int>();
            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))
            {
                var deviceTypeCommand = new DeviceTypeCommand
                {
                    Name = "Turn On"
                };
                device.Type.Commands.Add(deviceTypeCommand);
                context.Devices.Add(device);
                await context.SaveChangesAsync(CancellationToken.None);

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

                //Assert
                Assert.IsTrue(result.HasError);
                Assert.IsTrue(ranstoredCommands.Count == 0, "Process did not run the correct amount of commands.");
                Assert.IsTrue(result.Message.Contains("adapter is disabled"), "Expect error message to contain 'adapter is disabled'");
            }
        }
Пример #11
0
 public abstract Task ProcessDeviceTypeCommandAsync(DeviceType deviceType, Device device, DeviceTypeCommand command, string argument);
        public async Task RegisterAsyncRemvoedCommandOptionDeviceTypeTest()
        {
            //arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var dtb = new DeviceTypeBuilder(dbConnection);
            var adapter = UnitTesting.CreateFakeAdapter();
            var dt = new DeviceType
            {
                AdapterId = adapter.Id,
                UniqueIdentifier = "UNIT_TEST_DEVICE_TYPE1",
                Name = "Unit Test Device Type"
            };
            var dtc = new DeviceTypeCommand
            {
                UniqueIdentifier = "DTC1",
                Name = "Test Device Type Command"
            };
            var option1 = new CommandOption
            {
                Name = "Option 1"
            };
            var option2 = new CommandOption
            {
                Name = "Option 2"
            };
            dt.Commands.Add(dtc);
            adapter.DeviceTypes.Add(dt);
            dtc.Options.Add(option1);
            dtc.Options.Add(option2);
            using (var context = new ZvsContext(dbConnection))
            {
                context.Adapters.Add(adapter);
                await context.SaveChangesAsync();
            }

            dtc.Options.Remove(option1);

            //act
            var result = await dtb.RegisterAsync(adapter.AdapterGuid, dt, CancellationToken.None);

            using (var context = new ZvsContext(dbConnection))
            {
                var dtc1 = context.DeviceTypeCommands
                    .Include(o => o.Options)
                    .First();

                //assert 
                Console.WriteLine(result.Message);
                Assert.IsFalse(result.HasError);
                Assert.IsTrue(dtc1.Options.Count == 1, "Expected 2 options");
            }

        }
        public async Task RegisterAsyncUpdatedCommandDeviceTypeTest()
        {
            //arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var dtb = new DeviceTypeBuilder( dbConnection);
            var adapter = UnitTesting.CreateFakeAdapter();
            var dt = new DeviceType
            {
                AdapterId = adapter.Id,
                UniqueIdentifier = "UNIT_TEST_DEVICE_TYPE1",
                Name = "Unit Test Device Type"
            };
            var dtc = new DeviceTypeCommand
            {
                UniqueIdentifier = "DTC1",
                Name = "Test Device Type Command"
            };
            dt.Commands.Add(dtc);
            adapter.DeviceTypes.Add(dt);
            using (var context = new ZvsContext(dbConnection))
            {
                context.Adapters.Add(adapter);
                await context.SaveChangesAsync();
            }

            dtc.Name = "New DTC Test Name";

            //act
            var result = await dtb.RegisterAsync(adapter.AdapterGuid, dt, CancellationToken.None);

            using (var context = new ZvsContext(dbConnection))
            {
                var dtc1 = context.DeviceTypeCommands.First();

                //assert 
                Console.WriteLine(result.Message);
                Assert.IsFalse(result.HasError);
                Assert.IsTrue(dtc1.Name == dtc.Name, "Command did not update");
            }

        }