3 changed files with 138 additions and 42 deletions

No files matched your search

+44 -40
View File
@@ -1,21 +1,18 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HomeAssistant.Controller.Bedroom where
import HomeAssistant.Controller
import qualified Data.Text as T
import AFRP (Event (..), lMerge, duration, edge, filterEvent, named, (>>||))
import AFRP (Event (..), edge, filterEvent, hold, named, snapshot, tag, waitFor, (>>||))
import Data.Aeson (Value, object, (.=))
import Control.Arrow ((>>>), returnA, arr, Arrow (..))
import Data.Bool (bool)
import Data.Time (NominalDiffTime)
import qualified AFRP
import Data.Map (Map)
import qualified Data.Map.Strict as M
import Data.Serialize.Text ()
import Data.Default (def)
import Data.Serialize (Serialize)
@@ -37,46 +34,58 @@ createBedroomScene = Service
bedroomPresence :: HASS (Event Value) (Event Presence)
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
presenceLightEvents :: HASS (Event Value) (Event LightingMode)
presenceLightEvents =
bedroomPresence >>> AFRP.hold Unoccupied
>>> arr lightWanted
>>> (sleepEvent &&& offEvent &&& onEvent)
>>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
where
lightWanted o = o == Occupied
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightingSleep)
onEvent = AFRP.edge >>> arr (AFRP.tag LightingOn)
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightingOff)
bedroomPresenceOccupied :: HASS (Event Value) Bool
bedroomPresenceOccupied = bedroomPresence >>> hold Unoccupied >>> arr (== Occupied)
bedroomLightStatus :: HASS (Event Value) (Map T.Text LightObservation)
bedroomLightStatus = M.fromList <$> traverse (\e -> (e,) <$> observedLight e) [e | EntityId e <- bedroomLightTargets]
newtype Snapshot = Snapshot { getSnapshot :: Map T.Text LightObservation }
deriving (Show, Eq)
deriving Serialize via (Map T.Text LightObservation)
lightLevel :: HASS (Event Value) Int
lightLevel = entityRead "sensor.presence_sensor_bedroom_light_level" >>> AFRP.hold 1
-- Snapshot the light status when leaving (presence turning unoccupied),
-- restored on the next entry.
snapshotOnLeaving :: HASS (Event Value) (Map T.Text LightObservation)
snapshotOnLeaving =
(bedroomPresenceOccupied &&& bedroomLightStatus)
>>> first (arr not >>> edge)
>>> snapshot M.empty
-- The light reactions run "in parallel"; there is a chance that two
-- services are called in one go
bedroomPresenceController :: HASS (Event Value) ()
bedroomPresenceController = proc x -> do
p <- presenceLightEvents >>> traceEvent -< x
capped <- lightLevel >>> arr (< 4) -< x
snap <- (doSnapshot &&& bedroomLightStatus) >>> AFRP.snapshot M.empty >>> arr Snapshot -< x
-- This line is just for debugging
_ <- AFRP.changes >>> traceEvent -< snap
case p of
Event LightingOff -> do
callService "Turn off lights" (light bedroomLightTargets Off) -< ()
Event LightingOn -> do
callServicesDyn "Turn on lights (capped)" (\(c,xs) -> concatMap (uncurry (toLight c)) xs) -< (capped, M.toList (getSnapshot snap))
returnA -< ()
Event LightingSleep -> do
callService "Turn on sleep" (activateScene "scene.makuuhuone_lepotila") -< ()
_ -> returnA -< ()
bedroomPresenceController =
((,,,) <$> bedroomPresenceOccupied <*> cappedLightLevel <*> bedroomLightStatus <*> snapshotOnLeaving)
>>> mconcat
[ AFRP.named "Lights on" lightsOn
, AFRP.named "Lights sleep" lightsSleep
, AFRP.named "Lights off" lightsOff
]
>>> arr (const ()) -- I don't like this extra arr here
where
cappedLightLevel :: HASS (Event Value) Bool
cappedLightLevel = lightLevel >>> arr (< 4)
lightsOn =
arr (\(o, capped, _, snap) -> (o, (capped, M.toList snap)))
>>> first edge
>>> arr (\(ev, p) -> tag p ev)
>>|| callServicesDyn "Turn on lights (capped)" (\(c,xs) -> concatMap (uncurry (toLight c)) xs)
lightsSleep =
arr (\(o, _, st, _) -> (not o, st))
>>> first edge
>>> arr (\(ev, st) -> tag st ev)
>>> filterEvent anyLightsAreOn
>>|| callService "Turn on sleep" (activateScene "scene.makuuhuone_lepotila")
lightsOff =
arr (\(o, _, _, _) -> not o)
>>> waitFor 300
>>|| callService "Turn off lights" (light bedroomLightTargets Off)
anyLightsAreOn :: Foldable f => f LightObservation -> Bool
anyLightsAreOn = any observedOn
toLight :: Bool -> T.Text -> LightObservation -> [Service]
toLight _ entityId LightObservation{observedOn=False} = [light [EntityId entityId] Off]
toLight capped entityId LightObservation{observedOn=True, observedTemperature=t, observedBrightness=b} =
@@ -85,8 +94,6 @@ bedroomPresenceController = proc x -> do
, lightColorTemperature = t
})
]
doSnapshot = presenceLightEvents
>>> arr (\ev -> if ev == Event LightingSleep then Event () else Tick)
data BedroomControls
@@ -149,9 +156,6 @@ door :: HASS (Event Value) (Event DoorState)
door = entityBool "binary_sensor.makuuhuone_ovi_contact"
>>> arr (fmap (bool Closed Open))
waitFor :: NominalDiffTime -> HASS a (Event ())
waitFor n = duration >>> arr (> n) >>> edge
delayedDoor :: HASS (Event Value) (Event DoorState)
delayedDoor = door
+3 -1
View File
@@ -85,7 +85,9 @@ schoolLightController = lightsOn <> lightsOff
lightsOn :: HASS a ()
lightsOn = foldMap atTime timersOn
>>> AFRP.onEvent (callService "Lights on" (light [AreaId "lasten_makuuhuone"] (On def{lightBrightness=Just $ BrightnessPercent 100} )))
>>> AFRP.onEvent (callService "Lights on" lights)
where
lights = light [AreaId "lasten_makuuhuone"] (On def{lightBrightness=Just (BrightnessPercent 100), lightTransition = Just 5} )
lightsOff :: HASS a ()
lightsOff = foldMap atTime timersOff
+91 -1
View File
@@ -5,7 +5,10 @@ module BedroomSpec (spec) where
import AFRP (Event (..), entities)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Aeson (Value)
import Data.Aeson (Value, object, (.=))
import qualified Data.Aeson.Key as Key
import Data.Default (def)
import Data.Time (getCurrentTime, addUTCTime)
import HomeAssistant.Controller
import HomeAssistant.Controller.Bedroom
import Support
@@ -20,11 +23,31 @@ enishenButton = Event . buttonEvent "event.bedroom_quick_jemina_action"
drawerState :: T.Text -> Event Value
drawerState = Event . stateEvent "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contact"
presenceSensor :: T.Text -> Event Value
presenceSensor = Event . stateEvent "binary_sensor.presence_sensor_bedroom_occupancy"
-- Light state event with observed attributes
masseLight :: T.Text -> [(T.Text, Int)] -> Event Value
masseLight state attrs = Event $ object
[ "event" .= object
[ "variables" .= object
[ "trigger" .= object
[ "entity_id" .= ("light.bedroom_masse" :: T.Text)
, "to_state" .= object
[ "state" .= state
, "attributes" .= object [ Key.fromString (T.unpack k) .= v | (k, v) <- attrs ]
]
]
]
]
]
spec :: Spec
spec = describe "Bedroom" $ do
entitySpec
drawerSpec
buttonSpec
presenceSpec
entitySpec :: Spec
entitySpec = describe "entities" $ do
@@ -85,6 +108,73 @@ drawerSpec = describe "bedroomDrawerController" $ do
services (runHASS bedroomDrawerController [Tick])
`shouldBe` [[]]
presenceSpec :: Spec
presenceSpec = describe "bedroomPresenceController" $ do
let sleepScene = activateScene "scene.makuuhuone_lepotila"
it "subscribes to presence, light level and the bedroom lights" $
entities bedroomPresenceController
`shouldBe` S.fromList
[ "binary_sensor.presence_sensor_bedroom_occupancy"
, "sensor.presence_sensor_bedroom_light_level"
, "light.bedroom_ceiling"
, "light.bedroom_jemina"
, "light.bedroom_led_switch"
, "light.bedroom_masse"
]
it "does nothing on Tick" $
services (runHASS bedroomPresenceController [Tick])
`shouldBe` [[]]
it "does nothing when entering for the first time (no snapshot yet)" $
services (runHASS bedroomPresenceController [presenceSensor "on"])
`shouldBe` [[]]
it "activates the sleep scene when leaving with the lights on" $
services (runHASS bedroomPresenceController
[ presenceSensor "on", masseLight "on" [], presenceSensor "off" ])
`shouldBe` [ [], [], [sleepScene] ]
it "does not activate the sleep scene when the lights are off" $
services (runHASS bedroomPresenceController
[ presenceSensor "on", masseLight "on" [], masseLight "off" [], presenceSensor "off" ])
`shouldBe` [ [], [], [], [] ]
it "turns the lights off 300s after leaving" $ do
now <- getCurrentTime
let later = 305 `addUTCTime` now
services (runHASSTimed bedroomPresenceController
[ (now, presenceSensor "on"), (now, presenceSensor "off"), (later, Tick) ])
`shouldBe` [ [], [], [light bedroomLightTargets Off] ]
it "restores the last snapshot when re-entering after sleep" $ do
now <- getCurrentTime
let later = 350 `addUTCTime` now
let masseRestored = light [EntityId "light.bedroom_masse"] (On def
{ lightBrightness = Just (BrightnessAbsolute 140)
, lightColorTemperature = Just 2700
})
services (runHASSTimed bedroomPresenceController
[ (now, presenceSensor "on")
, (now, masseLight "on" [("brightness", 255), ("color_temp_kelvin", 2700)])
, (now, presenceSensor "off")
, (now, Tick)
, (later, presenceSensor "on")
, (later, Tick)
])
`shouldBe` [ []
, []
, [sleepScene]
, []
, [ light [EntityId "light.bedroom_ceiling"] Off
, light [EntityId "light.bedroom_jemina"] Off
, light [EntityId "light.bedroom_led_switch"] Off
, masseRestored
]
, []
]
buttonSpec :: Spec
buttonSpec = describe "bedroomButtonController" $ do
let area = AreaId "makuuhuone"