private void Update()
        {
            if (Input.GetKeyDown(KeyCode.O))
            {
                var commandTV    = new TurnOnCommand(_devices[0]);
                var commandRadio = new TurnOnCommand(_devices[1]);

                var invoker = new Invoker();

                invoker.SetCommand(commandTV);
                invoker.ExecuteCommand();

                invoker.SetCommand(commandRadio);
                invoker.ExecuteCommand();
            }

            if (Input.GetKeyDown(KeyCode.K))
            {
                var commandKill = new KillSwitchCommand(_devices);

                var invoker = new Invoker();

                invoker.SetCommand(commandKill);
                invoker.ExecuteCommand();
            }
        }
예제 #2
0
        public void Should_Throw_Exception_From_Event_Store_When_Turning_On_Device()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.NewGuid());

            moqEventStore.Setup(x => x.SaveEvents(It.IsAny <CompositeAggregateId>(), It.IsAny <IEnumerable <IEvent> >())).Throws(new Exception("Problem in Event Store"));
            Assert.Throws <Exception>(() => Domain.Device.TurnOn(eventMetadata, moqEventStore.Object, cmd));
        }
예제 #3
0
        protected void Handle(TurnOnCommand command)
        {
            var pin     = command.AsInt(MessageProperties.PinNumber);
            var reverse = command.AsBool(MessageProperties.ReversePinLevel);

            _gpioDevice.Write(pin, !reverse);
        }
예제 #4
0
        private async Task CalibrationMinimumLight(IContext context)
        {
            if (context.Message is StopCommand stopCommand)
            {
                // Ignore previous commands if we receive any
                if (stopCommand[MessageProperties.Context] == "MAX")
                {
                    return;
                }

                Become(StandardMode);

                ForwardToPowerAdapter(TurnOffCommand.Default);

                ResetStateValues();

                TryCalculateSpectrum();

                Logger.LogInformation($"Calibration of {Uid} : calibration finished with MIN: {_Minimum}, MAX: {_Maximum}, RANGE: {_Range}");

                await Task.Delay(WAIT_AFTER_CHANGE).ConfigureAwait(false);

                ForwardToPowerAdapter(TurnOnCommand.Create(CHANGE_POWER_STATE_TIME));
            }
            else if (context.Message is PropertyChangedEvent minimumState)
            {
                await MessageBroker.SendAfterDelay(ActorMessageContext.Create(Self, StopCommand.Create("MIN")), TimeSpan.FromMilliseconds(1500)).ConfigureAwait(false);

                _Minimum = minimumState.AsDouble(MessageProperties.NewValue);
            }
            else
            {
                await StandardMode(context).ConfigureAwait(false);
            }
        }
예제 #5
0
        private async Task ControlDimmer(double destinationLevel)
        {
            int powerOnTime = 0;
            var dest        = TimeForPercentage(destinationLevel);
            var current     = TimeForPercentage(_PowerLevel.Value);

            if (destinationLevel > _PowerLevel)
            {
                // If last time dimmer was increasing its value we have to change direction by short time power on
                if (_CurrentValue > _PreviousCurrentValue && _CurrentValue > 0)
                {
                    // We add time that we consume on direction change
                    powerOnTime += await ChangeDimmerDirection();
                }

                powerOnTime += (int)(dest - current);

                Logger.LogInformation($"Set dimmer to {destinationLevel} by waiting {powerOnTime}ms");
            }
            else
            {
                // If last time dimmer was decreasing its value we have to change direction by short time power on
                if (_PreviousCurrentValue > _CurrentValue && _CurrentValue > 0)
                {
                    powerOnTime += await ChangeDimmerDirection();
                }

                powerOnTime += (int)(current - dest);
            }

            ForwardToPowerAdapter(TurnOnCommand.Create(powerOnTime));
        }
예제 #6
0
        private void OnMessageReceived(object sender, DeviceMessageReceivedEventArgs e)
        {
            try
            {
                IComponent component = null;
                if (e.Message.Topic == "garden_controller/$PATCH/socket.pavillion")
                {
                    component = _area.GetComponent(Garden.SocketPavillion);
                }
                else if (e.Message.Topic == "garden_controller/$PATCH/lamp.rear_area")
                {
                    component = _area.GetComponent(Garden.LampRearArea);
                }
                else if (e.Message.Topic == "garden_controller/$PATCH/lamp.roof")
                {
                    component = _area.GetComponent(Garden.SpotlightRoof);
                }
                else if (e.Message.Topic == "garden_controller/$PATCH/lamp.tap")
                {
                    component = _area.GetComponent(Garden.LampTap);
                }
                else if (e.Message.Topic == "garden_controller/$PATCH/lamp.garage")
                {
                    component = _area.GetComponent(Garden.LampGarage);
                }
                else if (e.Message.Topic == "garden_controller/$PATCH/lamp.terrace")
                {
                    component = _area.GetComponent(Garden.LampTerrace);
                }
                else if (e.Message.Topic == "garden_controller/$PATCH/lamp.parking_lot")
                {
                    component = _area.GetComponent(Garden.LampParkingLot);
                }

                if (component == null)
                {
                    return;
                }

                var status = Encoding.UTF8.GetString(e.Message.Payload ?? new byte[0]);

                ICommand command = new TurnOffCommand();

                if (status == "on")
                {
                    command = new TurnOnCommand();
                }
                else if (status == "toggle")
                {
                    command = new TogglePowerStateCommand();
                }

                component.ExecuteCommand(command);
            }
            catch (Exception exception)
            {
                Log.Default.Error(exception, "Errow while patching state.");
            }
        }
예제 #7
0
        public void Set_Level_Version_Mismatch_Should_Throw_ArgumentOutOfReangeException()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.NewGuid());
            var           p   = Domain.Device.TurnOn(eventMetadata, moqEventStore.Object, cmd);

            Assert.Throws <ArgumentOutOfRangeException>(() => p.SetLevel(eventMetadata, p.AggregateGuid, 80, 100));
            moqEventStore.Verify(m => m.SaveEvents(It.IsAny <CompositeAggregateId>(), It.IsAny <IEnumerable <IEvent> >()), Times.Once);
        }
예제 #8
0
        protected async Task Handle(TurnOnCommand message)
        {
            var cmd = WakeOnLanCommand.Create(_mac);
            await MessageBroker.SendToService(cmd).ConfigureAwait(false);

            //TODO check state before update the state
            _powerState = await UpdateState(PowerState.StateName, _powerState, true).ConfigureAwait(false);
        }
예제 #9
0
        private async Task <int> ChangeDimmerDirection()
        {
            ForwardToPowerAdapter(TurnOnCommand.Create(SWITCH_CHANGE_DIRECTION));

            await Task.Delay(WAIT_AFTER_CHANGE).ConfigureAwait(false);

            return(SWITCH_CHANGE_DIRECTION);
        }
예제 #10
0
        public void Should_Throw_Exception_When_No_Device_Id_Is_Provided()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.Empty)
            {
                Level = 70
            };

            Assert.Throws <ArgumentException>(() => Domain.Device.TurnOn(eventMetadata, moqEventStore.Object, cmd));
        }
예제 #11
0
        protected async Task Handle(TurnOnCommand message)
        {
            var command = WakeOnLanCommand.Create(_mac);
            await MessageBroker.SendToService(command);

            //var cmd = GetControlCommand("AAAAAQAAAAEAAAAuAw==");

            _powerState = await UpdateState(PowerState.StateName, _powerState, true);
        }
예제 #12
0
        public void Should_Throw_Exception_When_Turning_On_Device_With_Negative_Percentage()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.NewGuid())
            {
                Level = -5
            };

            Assert.Throws <ArgumentException>(() => Domain.Device.TurnOn(moqEventMetadata.Object, moqEventStore.Object, cmd));
        }
예제 #13
0
        public void Should_Throw_Exception_When_Setting_Level_To_Negative_Level()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.NewGuid())
            {
                Level = 70
            };

            var p = Domain.Device.TurnOn(eventMetadata, moqEventStore.Object, cmd);

            Assert.Throws <ArgumentException>(() => p.SetLevel(eventMetadata, p.AggregateGuid, -45, p.Version));
        }
예제 #14
0
        protected async Task TurnOn(TurnOnCommand message)
        {
            byte[] package = PreparePackage(message, nameof(RemoteSocketCommand.TurnOn), out var dipswitchCode);

            Logger.LogInformation($"Sending code {dipswitchCode.Code}");

            var cmd = I2cCommand.Create(_I2cAddress, package);
            await MessageBroker.SendToService(cmd);

            await UpdateState(dipswitchCode);
        }
예제 #15
0
        /* Classe de test  */
        static void Main(string[] args)
        {
            Light   lamp       = new Light();
            Command switchUp   = new TurnOnCommand(lamp);
            Command switchDown = new TurnOffCommand(lamp);

            Switch s = new Switch(switchUp, switchDown);

            s.flipUp();
            s.flipDown();
        }
예제 #16
0
        public void Turn_On_Device_Should_Send_One_Event_To_EventStore()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.NewGuid())
            {
                Level = 9
            };

            var p = Domain.Device.TurnOn(eventMetadata, moqEventStore.Object, cmd);

            moqEventStore.Verify(m => m.SaveEvents(It.IsAny <CompositeAggregateId>(), It.IsAny <IEnumerable <IEvent> >()), Times.Once);
        }
예제 #17
0
        public void Set_Device_Level_Should_Send_Two_Event_To_EventStore()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.NewGuid())
            {
                Level = 70
            };

            var p = Domain.Device.TurnOn(eventMetadata, moqEventStore.Object, cmd);

            p.SetLevel(eventMetadata, p.AggregateGuid, 45, p.Version);
            moqEventStore.Verify(m => m.SaveEvents(It.IsAny <CompositeAggregateId>(), It.IsAny <IEnumerable <IEvent> >()), Times.Exactly(2));
        }
예제 #18
0
        protected async Task Handle(TurnOnCommand message)
        {
            int pinNumber = ValidatePin(message);

            await SetPortState(pinNumber, true);

            if (message.ContainsProperty(MessageProperties.StateTime))
            {
                await Task.Delay(message.AsIntTime(MessageProperties.StateTime));
                await SetPortState(pinNumber, false);
            }
        }
예제 #19
0
        public void Should_Set_Percentage_To_100_When_Turning_On_Device_Without_Setting_Percentage()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.NewGuid());

            var p      = Domain.Device.TurnOn(eventMetadata, moqEventStore.Object, cmd);
            var events = p.GetUncommittedEvents();

            Assert.IsNotEmpty(events);
            Assert.AreEqual(1, events.Count());
            Assert.IsInstanceOf <TurnedOn>(events.First());
            TurnedOn turnedOn = events.First() as TurnedOn;

            turnedOn.Level.ShouldEqual(100);
        }
예제 #20
0
        public void Should_Generate_TurnedOn_Event_When_Turn_On_Device_Command_Is_Sent()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.NewGuid())
            {
                Level = 90
            };

            var p      = Domain.Device.TurnOn(eventMetadata, moqEventStore.Object, cmd);
            var events = p.GetUncommittedEvents();

            Assert.IsNotEmpty(events);
            Assert.AreEqual(1, events.Count());
            Assert.IsInstanceOf <TurnedOn>(events.First());
        }
예제 #21
0
        protected async Task Handle(TurnOnCommand message)
        {
            var cmd = new ComputerCommand
            {
                Address = _hostname,
                Service = "Process",
                Message = new ProcessPost {
                    ProcessName = "kodi", Start = true
                },
                Port = 5000
            };
            await MessageBroker.SendToService(cmd).ConfigureAwait(false);

            _powerState = await UpdateState(PowerState.StateName, _powerState, true).ConfigureAwait(false);
        }
예제 #22
0
        protected async Task Handle(TurnOnCommand message)
        {
            var control = new DenonControlQuery
            {
                Command    = "PowerOn",
                Api        = "formiPhoneAppPower",
                ReturnNode = "Power",
                Address    = _hostName,
                Zone       = _zone.ToString()
            };

            if (await MessageBroker.QueryServiceWithVerify <DenonControlQuery, string, object>(control, "ON"))
            {
                _powerState = await UpdateState(PowerState.StateName, _powerState, true);
            }
        }
예제 #23
0
        protected void Handle(TurnOnCommand turnOnCommand)
        {
            if (!turnOnCommand.ContainsProperty(MessageProperties.StateTime))
            {
                // When we don't get state time and we already turned on we ignore this
                // When state time is set by the sender we always allow to pass threw
                if (_PowerLevel > 0)
                {
                    return;
                }

                turnOnCommand.SetProperty(MessageProperties.StateTime, CHANGE_POWER_STATE_TIME);
            }

            ForwardToPowerAdapter(turnOnCommand);
        }
예제 #24
0
        public void Should_Set_Level_To_30()
        {
            TurnOnCommand cmd = new TurnOnCommand(Guid.NewGuid())
            {
                Level = 70
            };

            var p = Domain.Device.TurnOn(eventMetadata, moqEventStore.Object, cmd);

            p.SetLevel(eventMetadata, p.AggregateGuid, 30, p.Version);
            var events = p.GetUncommittedEvents();

            events.Count().ShouldEqual(2);
            Assert.IsInstanceOf <SetLevel>(events.Last());
            SetLevel setLevel = events.Last() as SetLevel;

            setLevel.Level.ShouldEqual(30);
        }
예제 #25
0
        public override Task RunTask(int taskId)
        {
            Command cmd = null;

            switch (taskId)
            {
            case 0:
                cmd = new TurnOnCommand();
                break;

            case 1:
                cmd = new TurnOffCommand();

                break;

            case 2:
                cmd = new TurnOnCommand();

                ConsoleEx.WriteTitleLine("State Time:");
                var time = ConsoleEx.ReadNumber();
                cmd.SetProperty(MessageProperties.StateTime, time);

                break;

            case 3:
                ConsoleEx.WriteTitleLine("Enter dimmer level [0-100]:");
                var level = ConsoleEx.ReadNumber();
                cmd = new SetPowerLevelCommand();
                ((SetPowerLevelCommand)cmd).PowerLevel = level;
                break;

            case 4:
                ConsoleEx.WriteTitleLine("Adjust Power Level [0-100]:");
                var delta = ConsoleEx.ReadNumber();
                cmd = new AdjustPowerLevelCommand();
                ((AdjustPowerLevelCommand)cmd).Delta = delta;
                break;
            }

            MessageBroker.Send(cmd, Uid);

            return(Task.CompletedTask);
        }
예제 #26
0
        public override Task RunTask(int taskId)
        {
            if (!pinNumber.HasValue)
            {
                ConsoleEx.WriteWarning("Write PIN number:");
                pinNumber = int.Parse(Console.ReadLine());
            }

            Command cmd = null;

            switch (taskId)
            {
            case 0:
                cmd = new TurnOnCommand();
                break;

            case 1:
                cmd = new TurnOffCommand();
                break;

            case 2:
                cmd          = new RefreshCommand();
                cmd.LogLevel = nameof(Microsoft.Extensions.Logging.LogLevel.Information);
                break;

            case 3:
                cmd = new SwitchPowerStateCommand();
                break;
            }

            if (pinNumber.HasValue && pinNumber.Value < 10)
            {
                cmd.SetProperty(MessageProperties.PinNumber, pinNumber.Value);
            }

            MessageBroker.Send(cmd, Uid);

            return(Task.CompletedTask);
        }
예제 #27
0
        public override async Task RunTask(int taskId)
        {
            if (!pinNumber.HasValue)
            {
                ConsoleEx.WriteWarning("Write PIN number:");
                pinNumber = int.Parse(Console.ReadLine());
            }

            Command cmd = null;

            switch (taskId)
            {
            case 0:
                cmd = new TurnOnCommand();
                break;

            case 1:
                cmd = new TurnOffCommand();
                break;

            case 2:
                cmd          = new RefreshCommand();
                cmd.LogLevel = nameof(Microsoft.Extensions.Logging.LogLevel.Information);
                break;

            case 3:
                cmd = new SwitchPowerStateCommand();
                break;

            case 4:
                var inputUid           = "HSPE16InputOnly_2";
                var properyChangeEvent = PropertyChangedEvent.Create(inputUid, PowerState.StateName, false, true, new Dictionary <string, string>()
                {
                    [MessageProperties.PinNumber] = 0.ToString()
                });

                await MessageBroker.Publish(properyChangeEvent, inputUid);

                return;

            case 5:
                var inputUid2           = "HSPE16InputOnly_2";
                var properyChangeEvent2 = PropertyChangedEvent.Create(inputUid2, PowerState.StateName, true, false, new Dictionary <string, string>()
                {
                    [MessageProperties.PinNumber] = 0.ToString()
                });

                await MessageBroker.Publish(properyChangeEvent2, inputUid2);

                return;
            }

            if (pinNumber.HasValue && pinNumber.Value < 10)
            {
                cmd.SetProperty(MessageProperties.PinNumber, pinNumber.Value);
            }

            MessageBroker.Send(cmd, Uid);

            //return Task.CompletedTask;
        }
예제 #28
0
 private async Task ChangePowerState()
 {
     ForwardToPowerAdapter(TurnOnCommand.Create(CHANGE_POWER_STATE_TIME));
     await Task.Delay(WAIT_AFTER_CHANGE);
 }
예제 #29
0
        private void TurnOn()
        {
            TurnOnCommand cmd = new TurnOnCommand(SelectedConsumer);

            cmd.Execute();
        }
예제 #30
0
        private void InitializeStateMachine(StateMachine stateMachine, IArea garden)
        {
            var turnOffCommand = new TurnOffCommand();
            var turnOnCommand  = new TurnOnCommand();

            stateMachine.ResetStateId = StateMachineStateExtensions.OffStateId;

            stateMachine.AddOffState()
            .WithCommand(garden.GetComponent(Garden.LampTerrace), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampTerrace), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampGarage), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampTap), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.SpotlightRoof), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampRearArea), turnOffCommand);

            stateMachine.AddState("Te")
            .WithCommand(garden.GetLamp(Garden.LampTerrace), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.LampGarage), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampTap), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.SpotlightRoof), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampRearArea), turnOffCommand);

            stateMachine.AddState("G")
            .WithCommand(garden.GetLamp(Garden.LampTerrace), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampGarage), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.LampTap), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.SpotlightRoof), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampRearArea), turnOffCommand);

            stateMachine.AddState("W")
            .WithCommand(garden.GetLamp(Garden.LampTerrace), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampGarage), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampTap), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.SpotlightRoof), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampRearArea), turnOffCommand);

            stateMachine.AddState("D")
            .WithCommand(garden.GetLamp(Garden.LampTerrace), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampGarage), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampTap), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.SpotlightRoof), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.LampRearArea), turnOffCommand);

            stateMachine.AddState("Ti")
            .WithCommand(garden.GetLamp(Garden.LampTerrace), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampGarage), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampTap), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.SpotlightRoof), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampRearArea), turnOnCommand);

            stateMachine.AddState("G+W")
            .WithCommand(garden.GetLamp(Garden.LampTerrace), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampGarage), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.LampTap), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.SpotlightRoof), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampRearArea), turnOffCommand);

            stateMachine.AddState("Te+G+W")
            .WithCommand(garden.GetLamp(Garden.LampTerrace), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.LampGarage), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.LampTap), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.SpotlightRoof), turnOffCommand)
            .WithCommand(garden.GetLamp(Garden.LampRearArea), turnOffCommand);

            stateMachine.AddOnState()
            .WithCommand(garden.GetLamp(Garden.LampTerrace), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.LampGarage), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.LampTap), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.SpotlightRoof), turnOnCommand)
            .WithCommand(garden.GetLamp(Garden.LampRearArea), turnOnCommand);
        }