コード例 #1
0
        public void Test_SetPower_ChangesAdapterLevel(byte fullPower, byte zeroPower, double requestedPower, byte expectedLevel)
        {
            var configRepositoryMock = new Mock <INooliteSwitchInfoRepository>(MockBehavior.Strict);
            var config = new NooliteSwitchInfo
            {
                SwitchId       = SwitchId.NewId(),
                Channel        = 98,
                FullPowerLevel = fullPower,
                ZeroPowerLevel = zeroPower
            };

            configRepositoryMock
            .Setup(repository => repository.ContainsConfig(config.SwitchId))
            .Returns(Task.FromResult(true));
            configRepositoryMock
            .Setup(repository => repository.GetConfig(config.SwitchId))
            .Returns(Task.FromResult(config));
            var adapterMock = new Mock <IPC11XXAdapter>(MockBehavior.Strict);

            adapterMock.Setup(adapter => adapter.SendCommand(PC11XXCommand.SetLevel, config.Channel, expectedLevel));
            var controller = new NooliteSwitchController(configRepositoryMock.Object, adapterMock.Object);

            controller.SetPower(config.SwitchId, requestedPower);

            adapterMock.Verify(adapter => adapter.SendCommand(PC11XXCommand.SetLevel, config.Channel, expectedLevel), Times.Once);
        }
コード例 #2
0
        public void SetPacked(int offset, byte[] packed, AssetMapping mapping)
        {
            if (mapping == null)
            {
                throw new ArgumentNullException(nameof(mapping));
            }

            _set.Clear();
            if (packed == null)
            {
                return;
            }

            for (int i = 0; i < packed.Length; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    bool     flagValue = (packed[i] & (1 << j)) != 0;
                    int      diskId    = i * 8 + j + offset;
                    SwitchId id        = AssetMapping.Global.EnumToId(mapping.IdToEnum(new SwitchId(AssetType.Switch, diskId)));
                    if (flagValue)
                    {
                        _set.Add(id);
                    }
                }
            }
        }
コード例 #3
0
 private void CheckBindingIsValid(SwitchId switchId, SensorId sensorId)
 {
     if (!_enabledBindings.ContainsKey(sensorId) ||
         !_allowedCombinations.Contains(Tuple.Create(switchId, sensorId)))
     {
         throw new InvalidOperationException($"Sensor {sensorId} not found in the configuration.");
     }
 }
コード例 #4
0
        public void TurnOff(SwitchId switchId)
        {
            Guard.DebugAssertArgumentNotNull(switchId, nameof(switchId));
            Guard.DebugAssertArgument(CanHandleSwitch(switchId), nameof(switchId));

            var config = _configurationRepository.GetConfig(switchId).Result;

            _adapter.SendCommand(PC11XXCommand.Off, config.Channel);
        }
コード例 #5
0
    public async Task DeleteSwitch(SwitchId id)
    {
        var existingSwitch = await GetSwitch(id);

        var query = new Query("switches").AsDelete().Where("id", id);
        await _db.ExecuteQuery(query);

        _logger.Information("Deleted {Switch}", id);
        _ = _dispatch.Dispatch(existingSwitch.System, existingSwitch.Uuid, DispatchEvent.DELETE_SWITCH);
    }
コード例 #6
0
 public void SetFlag(SwitchId flag, bool value)
 {
     if (value)
     {
         _set.Add(flag);
     }
     else
     {
         _set.Remove(flag);
     }
 }
コード例 #7
0
ファイル: Switch.cs プロジェクト: lulzzz/daipan
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(GetType().ToString());
            sb.AppendLine("SwitchId" + SwitchId.ToString());
            sb.AppendLine(base.ToString());
            sb.AppendLine(Cases.ToString());
            sb.AppendLine(Default.ToString());
            return(sb.ToString());
        }
コード例 #8
0
        public void Test_IfRepoDoesNotContainConfig_ThenCantHandle()
        {
            var configRepositoryMock = new Mock <INooliteSwitchInfoRepository>(MockBehavior.Strict);

            configRepositoryMock
            .Setup(repository => repository.ContainsConfig(It.IsAny <SwitchId>()))
            .Returns(Task.FromResult(false));

            var controller = new NooliteSwitchController(configRepositoryMock.Object, Mock.Of <IPC11XXAdapter>());

            Assert.False(controller.CanHandleSwitch(SwitchId.NewId()));

            configRepositoryMock.Verify(repo => repo.ContainsConfig(It.IsAny <SwitchId>()), Times.Once);
        }
コード例 #9
0
        public async void Test_ConsecutiveDisableEvents_AreOk()
        {
            var config = new SwitchToSensorBinding {
                SwitchId = SwitchId.NewId(), SensorId = SensorId.NewId()
            };
            IReadOnlyCollection <SwitchToSensorBinding> configCollection = new [] { config };
            var bindingsRepoMock = new Mock <ISwitchToSensorBindingsRepository>(MockBehavior.Strict);

            bindingsRepoMock.Setup(m => m.GetAll()).Returns(Task.FromResult(configCollection));
            var handler = new BindingController(Mock.Of <IEventSender>(), bindingsRepoMock.Object);

            await handler.DisableBinding(config.SwitchId, config.SensorId);

            await handler.DisableBinding(config.SwitchId, config.SensorId);
        }
コード例 #10
0
        public void Test_WhenReceivedDisableEvent_ThenDisableBinding()
        {
            var @event           = new DisableBindingEvent(SwitchId.NewId(), SensorId.NewId());
            var stateManagerMock = new Mock <IBindingStateManager>(MockBehavior.Strict);

            stateManagerMock.Setup(manager => manager.DisableBinding(@event.SwitchId, @event.SensorId)).Returns(Task.CompletedTask);;
            var eventsSourceMock = new Mock <IEventSource>(MockBehavior.Strict);

            eventsSourceMock.Setup(e => e.ReceiveEvents <AbstractBindingEvent>()).Returns(Observable.Repeat(@event, 1));
            var handler = new BindingEventsProcessor(stateManagerMock.Object, eventsSourceMock.Object, Mock.Of <ILogger>());

            handler.Run(CancellationToken.None);

            stateManagerMock.Verify(manager => manager.DisableBinding(@event.SwitchId, @event.SensorId), Times.Once);
        }
コード例 #11
0
    public async Task MoveSwitch(SwitchId id, Instant time)
    {
        _logger.Information("Updated {SwitchId} timestamp: {SwitchTimestamp}", id, time);
        var query = new Query("switches").AsUpdate(new { timestamp = time }).Where("id", id);
        await _db.ExecuteQuery(query);

        _ = _dispatch.Dispatch(id, new UpdateDispatchData
        {
            Event     = DispatchEvent.UPDATE_SWITCH,
            EventData = JObject.FromObject(new
            {
                timestamp = time.FormatExport(),
            }),
        });
    }
コード例 #12
0
        public void Test_IfRepoContainsConfig_ThenCanHandle()
        {
            var configRepositoryMock = new Mock <INooliteSwitchInfoRepository>(MockBehavior.Strict);
            var switchId             = SwitchId.NewId();

            configRepositoryMock
            .Setup(repository => repository.ContainsConfig(switchId))
            .Returns(Task.FromResult(true));

            var controller = new NooliteSwitchController(configRepositoryMock.Object, Mock.Of <IPC11XXAdapter>());

            Assert.True(controller.CanHandleSwitch(switchId));

            configRepositoryMock.Verify(repo => repo.ContainsConfig(switchId), Times.Once);
        }
コード例 #13
0
            public void Disable(SwitchId switchId, SensorId sensorId)
            {
                Guard.DebugAssertArgumentNotNull(switchId, nameof(switchId));
                Guard.DebugAssertArgumentNotNull(sensorId, nameof(sensorId));

                CheckBindingIsValid(switchId, sensorId);

                var enabledSwitches = _enabledBindings[sensorId];

                if (!enabledSwitches.Contains(switchId))
                {
                    return;
                }

                lock (enabledSwitches)
                    enabledSwitches.Remove(switchId);
            }
コード例 #14
0
        public byte[] GetPacked(int from, int to, AssetMapping mapping)
        {
            if (mapping == null)
            {
                throw new ArgumentNullException(nameof(mapping));
            }
            var packed = new byte[PackedSize(from, to)];

            for (int i = 0; i < to - from; i++)
            {
                var diskId   = new SwitchId(AssetType.Switch, i + from);
                var globalId = AssetMapping.Global.EnumToId(mapping.IdToEnum(diskId));
                packed[i / 8] |= (byte)((_set.Contains(globalId) ? 1 : 0) << (i % 8));
            }

            return(packed);
        }
コード例 #15
0
ファイル: QuerySwitchEvent.cs プロジェクト: csinkers/ualbion
    public static QuerySwitchEvent Serdes(QuerySwitchEvent e, AssetMapping mapping, ISerializer s)
    {
        if (s == null)
        {
            throw new ArgumentNullException(nameof(s));
        }
        e ??= new QuerySwitchEvent();
        e.Operation = s.EnumU8(nameof(Operation), e.Operation);
        e.Immediate = s.UInt8(nameof(Immediate), e.Immediate);
        int zeroes = s.UInt8(null, 0);

        zeroes    += s.UInt8(null, 0);
        e.SwitchId = SwitchId.SerdesU16(nameof(SwitchId), e.SwitchId, mapping, s);
        // field 8 is the next event id when the condition is false and is deserialised as part of the BranchEventNode that this event should belong to.
        s.Assert(zeroes == 0, "QuerySwitchEvent: Expected fields 3,4 to be 0");
        return(e);
    }
コード例 #16
0
ファイル: SwitchEvent.cs プロジェクト: lucorp/ualbion
        public static SwitchEvent Serdes(SwitchEvent e, AssetMapping mapping, ISerializer s)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }
            e ??= new SwitchEvent();
            e.Operation = s.EnumU8(nameof(Operation), e.Operation);
            e.Unk3      = s.UInt8(nameof(Unk3), e.Unk3);
            int zeroed = s.UInt8(null, 0);

            zeroed    += s.UInt8(null, 0);
            e.SwitchId = SwitchId.SerdesU16(nameof(SwitchId), e.SwitchId, mapping, s);
            zeroed    += s.UInt16(null, 0);
            s.Assert(zeroed == 0, "SwitchEvent: Expected fields 4,5,8 to be 0");
            return(e);
        }
コード例 #17
0
        public void SetPower(SwitchId switchId, double power)
        {
            Guard.DebugAssertArgumentNotNull(switchId, nameof(switchId));
            Guard.DebugAssertArgument(power >= 0 && power <= 1, nameof(switchId));
            Guard.DebugAssertArgument(CanHandleSwitch(switchId), nameof(switchId));

            var config = _configurationRepository.GetConfig(switchId).Result;

            if (config.FullPowerLevel <= config.ZeroPowerLevel)
            {
                throw new InvalidConfigurationException($"Invalid configuration for switch {switchId}. FullPowerLevel should be greater then ZeroPowerLevel.");
            }

            var level = Convert.ToByte(config.ZeroPowerLevel + (config.FullPowerLevel - config.ZeroPowerLevel) * power);

            _adapter.SendCommand(PC11XXCommand.SetLevel, config.Channel, level);
        }
コード例 #18
0
        public async void TestBindingEnabledByDefault_TurnOn()
        {
            var config = new SwitchToSensorBinding {
                SwitchId = SwitchId.NewId(), SensorId = SensorId.NewId()
            };
            IReadOnlyCollection <SwitchToSensorBinding> configCollection = new [] { config };
            var bindingsRepoMock = new Mock <ISwitchToSensorBindingsRepository>(MockBehavior.Strict);

            bindingsRepoMock.Setup(m => m.GetAll()).Returns(Task.FromResult(configCollection));
            var publisherMock = new Mock <IEventSender>(MockBehavior.Strict);

            publisherMock.Setup(m => m.SendEvent(It.Is <TurnOnEvent>(e => e.SwitchId == config.SwitchId)));
            var handler = new BindingController(publisherMock.Object, bindingsRepoMock.Object);

            await handler.ProcessSensorActivation(config.SensorId);

            publisherMock.Verify(m => m.SendEvent(It.IsAny <TurnOnEvent>()), Times.Once);
        }
コード例 #19
0
        public void TestTurnOff()
        {
            var swicthId             = SwitchId.NewId();
            var offEvent             = new TurnOffEvent(swicthId);
            var switchControllerMock = new Mock <ISwitchController>(MockBehavior.Strict);

            switchControllerMock.Setup(cntr => cntr.CanHandleSwitch(swicthId)).Returns(true);
            switchControllerMock.Setup(cntr => cntr.TurnOff(swicthId));
            var eventsSourceMock = new Mock <IEventSource>(MockBehavior.Strict);

            eventsSourceMock.Setup(e => e.ReceiveEvents <AbstractSwitchEvent>()).Returns(Observable.Repeat(offEvent, 1));

            var handler = new SwitchEventsProcessor(switchControllerMock.Object, eventsSourceMock.Object, Mock.Of <ILogger>());

            handler.Run(CancellationToken.None);

            switchControllerMock.Verify(sc => sc.CanHandleSwitch(swicthId), Times.Once);
            switchControllerMock.Verify(sc => sc.TurnOff(swicthId), Times.Once);
        }
コード例 #20
0
        public async void TestWnehUnknownSensor_ThenDoNothing()
        {
            IReadOnlyCollection <SwitchToSensorBinding> config = new []
            {
                new SwitchToSensorBinding {
                    SwitchId = SwitchId.NewId(), SensorId = SensorId.NewId()
                }
            };
            var bindingsRepoMock = new Mock <ISwitchToSensorBindingsRepository>(MockBehavior.Strict);

            bindingsRepoMock.Setup(m => m.GetAll()).Returns(Task.FromResult(config));
            var publisherMock = new Mock <IEventSender>(MockBehavior.Strict);
            var handler       = new BindingController(publisherMock.Object, bindingsRepoMock.Object);

            await handler.ProcessSensorActivation(SensorId.NewId());

            await handler.ProcessSensorDeactivation(SensorId.NewId());

            publisherMock.Verify(m => m.SendEvent(It.IsAny <IEvent>()), Times.Never);
        }
コード例 #21
0
        public async void TestWhenUnknownBinding_ThenError()
        {
            IReadOnlyCollection <SwitchToSensorBinding> config = new []
            {
                new SwitchToSensorBinding {
                    SwitchId = SwitchId.NewId(), SensorId = SensorId.NewId()
                }
            };
            var bindingsRepoMock = new Mock <ISwitchToSensorBindingsRepository>(MockBehavior.Strict);

            bindingsRepoMock.Setup(m => m.GetAll()).Returns(Task.FromResult(config));
            var publisherMock = new Mock <IEventSender>(MockBehavior.Strict);
            var handler       = new BindingController(publisherMock.Object, bindingsRepoMock.Object);

            await Assert.ThrowsAsync <InvalidOperationException>(() => handler.EnableBinding(SwitchId.NewId(), SensorId.NewId()));

            await Assert.ThrowsAsync <InvalidOperationException>(() => handler.DisableBinding(SwitchId.NewId(), SensorId.NewId()));

            publisherMock.Verify(m => m.SendEvent(It.IsAny <IEvent>()), Times.Never);
        }
コード例 #22
0
        public void Test_TurnOff_SendsAdapterOffCommand()
        {
            var switchId             = SwitchId.NewId();
            var configRepositoryMock = new Mock <INooliteSwitchInfoRepository>(MockBehavior.Strict);
            var adapterMock          = new Mock <IPC11XXAdapter>();
            var config = new NooliteSwitchInfo {
                Channel = 98
            };

            configRepositoryMock
            .Setup(repository => repository.ContainsConfig(switchId))
            .Returns(Task.FromResult(true));
            configRepositoryMock
            .Setup(repository => repository.GetConfig(switchId))
            .Returns(Task.FromResult(config));

            var controller = new NooliteSwitchController(configRepositoryMock.Object, adapterMock.Object);

            controller.TurnOff(switchId);

            adapterMock.Verify(adapter => adapter.SendCommand(PC11XXCommand.Off, config.Channel, 0), Times.Once);
        }
コード例 #23
0
    public async Task EditSwitch(IPKConnection conn, SwitchId switchId, IReadOnlyCollection <MemberId> members)
    {
        // Use a transaction here since we're doing multiple executed commands in one
        await using var tx = await conn.BeginTransactionAsync();

        // Remove the old members from the switch
        await conn.ExecuteAsync("delete from switch_members where switch = @Switch",
                                new { Switch = switchId });

        // Add the new members
        await using (var w =
                         conn.BeginBinaryImport("copy switch_members (switch, member) from stdin (format binary)"))
        {
            foreach (var member in members)
            {
                await w.StartRowAsync();

                await w.WriteAsync(switchId.Value, NpgsqlDbType.Integer);

                await w.WriteAsync(member.Value, NpgsqlDbType.Integer);
            }

            await w.CompleteAsync();
        }

        // Finally we commit the tx, since the using block will otherwise rollback it
        await tx.CommitAsync();

        _ = _dispatch.Dispatch(switchId, new UpdateDispatchData
        {
            Event     = DispatchEvent.UPDATE_SWITCH,
            EventData = JObject.FromObject(new
            {
                members = await GetMemberGuids(members),
            }),
        });

        _logger.Information("Updated {SwitchId} members: {Members}", switchId, members);
    }
コード例 #24
0
        public async void TestWhenSensorBindToMultipleSwitches_ThenTurnOffThemAll()
        {
            var sensorId = SensorId.NewId();
            var config1  = new SwitchToSensorBinding {
                SwitchId = SwitchId.NewId(), SensorId = sensorId
            };
            var config2 = new SwitchToSensorBinding {
                SwitchId = SwitchId.NewId(), SensorId = sensorId
            };
            IReadOnlyCollection <SwitchToSensorBinding> configCollection = new [] { config1, config2 };
            var bindingsRepoMock = new Mock <ISwitchToSensorBindingsRepository>(MockBehavior.Strict);

            bindingsRepoMock.Setup(m => m.GetAll()).Returns(Task.FromResult(configCollection));
            var publisherMock = new Mock <IEventSender>(MockBehavior.Strict);

            publisherMock.Setup(m => m.SendEvent(It.Is <TurnOffEvent>(e => e.SwitchId == config1.SwitchId)));
            publisherMock.Setup(m => m.SendEvent(It.Is <TurnOffEvent>(e => e.SwitchId == config2.SwitchId)));
            var handler = new BindingController(publisherMock.Object, bindingsRepoMock.Object);

            await handler.ProcessSensorDeactivation(sensorId);

            publisherMock.Verify(m => m.SendEvent(It.IsAny <TurnOffEvent>()), Times.Exactly(2));
        }
コード例 #25
0
 public EnableBindingEvent(SwitchId switchId, SensorId sensorId) : base(switchId, sensorId)
 {
 }
コード例 #26
0
 public ClearQuestBitEvent(SwitchId questId)
 {
     QuestId = questId;
 }
コード例 #27
0
ファイル: TurnOffEvent.cs プロジェクト: Angerity/homeControl
 public TurnOffEvent(SwitchId switchId) : base(switchId)
 {
 }
コード例 #28
0
ファイル: SwitchEvent.cs プロジェクト: lucorp/ualbion
 public SwitchEvent(SwitchOperation operation, SwitchId switchId, byte unk3)
 {
     Operation = operation;
     SwitchId  = switchId;
     Unk3      = unk3;
 }
コード例 #29
0
 public async Task DisableBinding(SwitchId switchId, SensorId sensorId)
 {
     (await GetState()).Disable(switchId, sensorId);
 }
コード例 #30
0
ファイル: QuerySwitchEvent.cs プロジェクト: csinkers/ualbion
 public QuerySwitchEvent(SwitchId switchId, QueryOperation operation, byte immediate)
 {
     Operation = operation;
     Immediate = immediate;
     SwitchId  = switchId;
 }