From 1e6788ac48d8a963c7b502f8a3a68827034b5df3 Mon Sep 17 00:00:00 2001 From: Sven van Heugten Date: Sat, 17 Jan 2026 15:48:47 +0100 Subject: [PATCH] Simplify even more --- NightLight.Core/NightLightStateMachine.fs | 41 ++++++++++------------- 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/NightLight.Core/NightLightStateMachine.fs b/NightLight.Core/NightLightStateMachine.fs index 1eec7b0..a395388 100644 --- a/NightLight.Core/NightLightStateMachine.fs +++ b/NightLight.Core/NightLightStateMachine.fs @@ -32,18 +32,15 @@ type NightLightStateMachine private (maybeState: NightLightState option) = member this.OnEventReceived(event: Event) : Result = result { - let updateLightStateForRemoteControlledLights (oldLightToState: Map) desiredLightState = - remoteControlledLights - |> Seq.fold - (fun acc key -> - let oldState = oldLightToState[key] + let withUpdatedStateFor (light: Light) (state: State) (oldNightLightState: NightLightState) = + let oldState = oldNightLightState.LightToState[light] - Map.add - key - { oldState with - State = desiredLightState } - acc) - oldLightToState + { oldNightLightState with + LightToState = Map.add light { oldState with State = state } oldNightLightState.LightToState } + + let withUpdatedStateForRemoteControlledLights (state: State) (oldNightLightState: NightLightState) = + remoteControlledLights + |> Seq.fold (fun acc light -> acc |> withUpdatedStateFor light state) oldNightLightState match event, maybeState with | ReceivedZigbeeEvent payload, Some state -> @@ -59,27 +56,23 @@ type NightLightStateMachine private (maybeState: NightLightState option) = | Some light -> generateZigbeeCommandsToFixLight state.LightToState[light] light | None -> Seq.empty | ButtonPress action -> - let newLightToState = + let newState = match action with - | PressedOn -> updateLightStateForRemoteControlledLights state.LightToState On - | PressedOff -> updateLightStateForRemoteControlledLights state.LightToState Off + | PressedOn -> state |> withUpdatedStateForRemoteControlledLights On + | PressedOff -> state |> withUpdatedStateForRemoteControlledLights Off | PressedLeft -> let lightThatShouldBeOn = remoteControlledLights |> Seq.find (fun light -> light.ControlledWithRemote = RemoteLeft) - let oldState = state.LightToState[lightThatShouldBeOn] + state + |> withUpdatedStateForRemoteControlledLights Off + |> withUpdatedStateFor lightThatShouldBeOn On - updateLightStateForRemoteControlledLights state.LightToState Off - |> Map.add lightThatShouldBeOn { oldState with State = On } - - NightLightStateMachine( - Some - { state with - LightToState = newLightToState } - ), + NightLightStateMachine(Some newState), remoteControlledLights - |> Seq.collect (fun light -> generateZigbeeCommandsToFixLight newLightToState[light] light) + |> Seq.collect (fun light -> + generateZigbeeCommandsToFixLight newState.LightToState[light] light) | TimeChanged newTime, maybeState -> let newPartOfDay = getPartOfDay newTime