public async Task SetLightsState(LightsStateViewModel lightsState) { if (!_lightSwitchDbService.AnyLightsToSwitchToTargetState(lightsState)) { return; } var transition = GetLightSwitchTransition(lightsState.State); lightsState.State = transition[0]; // trigger light changing on all clients to disable switch _controlHub.Clients.All.SetAllLightsState(lightsState); // save new state to db so new requests fetch updated state var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; var saving = _lightSwitchDbService.SetLightsState(lightsState, cancellationToken); // send request to set lights lightsState.State = transition[1]; var transitionRequestSent = _queueService.SendLightsState(lightsState.LightIds, transition[1]); if (!transitionRequestSent) { // could not send transition request, rollback all actions cancellationTokenSource.Cancel(); } await saving; }
public bool AnyLightsToSwitchToTargetState(LightsStateViewModel lightsState) { _context.Lights .Where(x => x.State != lightsState.State) .WhereFilterIsEmptyOrContains(x => x.Id, lightsState.LightIds) .Load(); wasFetchingLightsToSwitch = true; return(_context.Lights.Local.Any()); }
public Task <int> SetLightsState(LightsStateViewModel lightsState, CancellationToken cancellationToken) { List <Light> lightsToSwitch; if (wasFetchingLightsToSwitch) { lightsToSwitch = _context.Lights.Local.ToList(); } else { lightsToSwitch = _context.Lights .Where(x => x.State != lightsState.State) .WhereFilterIsEmptyOrContains(x => x.Id, lightsState.LightIds) .ToList(); } lightsToSwitch.ForEach(x => x.State = lightsState.State); return(_context.SaveChangesAsync(cancellationToken)); }
public async Task SetAllLightsState(LightsStateViewModel lightsState) { await _lightSwitchService.SetLightsState(lightsState); }