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); }
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); } } } }
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."); } }
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); }
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); }
public void SetFlag(SwitchId flag, bool value) { if (value) { _set.Add(flag); } else { _set.Remove(flag); } }
/// <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()); }
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); }
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); }
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); }
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(), }), }); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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)); }
public EnableBindingEvent(SwitchId switchId, SensorId sensorId) : base(switchId, sensorId) { }
public ClearQuestBitEvent(SwitchId questId) { QuestId = questId; }
public TurnOffEvent(SwitchId switchId) : base(switchId) { }
public SwitchEvent(SwitchOperation operation, SwitchId switchId, byte unk3) { Operation = operation; SwitchId = switchId; Unk3 = unk3; }
public async Task DisableBinding(SwitchId switchId, SensorId sensorId) { (await GetState()).Disable(switchId, sensorId); }
public QuerySwitchEvent(SwitchId switchId, QueryOperation operation, byte immediate) { Operation = operation; Immediate = immediate; SwitchId = switchId; }