Compare commits
4
Commits
868a5d7e4f
...
05263fed2b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05263fed2b | ||
|
|
6e35445090 | ||
|
|
95fcc61c4f | ||
|
|
2039d03a5e |
No files matched your search
@@ -6,6 +6,8 @@ dist-newstyle
|
|||||||
|
|
||||||
docs/superpowers/plans
|
docs/superpowers/plans
|
||||||
|
|
||||||
|
*.dat
|
||||||
|
handlers.json
|
||||||
*.hp
|
*.hp
|
||||||
*.eventlog
|
*.eventlog
|
||||||
*.eventlog.html
|
*.eventlog.html
|
||||||
|
|||||||
@@ -182,6 +182,7 @@ test-suite home-assistant-controller-test
|
|||||||
, ConnectionSpec
|
, ConnectionSpec
|
||||||
, FlagsSpec
|
, FlagsSpec
|
||||||
, GraphingSpec
|
, GraphingSpec
|
||||||
|
, HallwaySpec
|
||||||
, HttpServerSpec
|
, HttpServerSpec
|
||||||
, KitchenSpec
|
, KitchenSpec
|
||||||
, LivingroomSpec
|
, LivingroomSpec
|
||||||
@@ -189,6 +190,7 @@ test-suite home-assistant-controller-test
|
|||||||
, RuntimeSpec
|
, RuntimeSpec
|
||||||
, Support
|
, Support
|
||||||
, ControllerSpec
|
, ControllerSpec
|
||||||
|
, PresenceSpec
|
||||||
|
|
||||||
-- LANGUAGE extensions used by modules in this package.
|
-- LANGUAGE extensions used by modules in this package.
|
||||||
-- other-extensions:
|
-- other-extensions:
|
||||||
|
|||||||
+8
-2
@@ -31,6 +31,7 @@ module AFRP
|
|||||||
, SerializeUTCTime(..)
|
, SerializeUTCTime(..)
|
||||||
, SerializeLocalTime(..)
|
, SerializeLocalTime(..)
|
||||||
, edge
|
, edge
|
||||||
|
, edgeFrom
|
||||||
, waitFor
|
, waitFor
|
||||||
, duration
|
, duration
|
||||||
, tag
|
, tag
|
||||||
@@ -528,10 +529,15 @@ lMerge (Event a) _ = Event a
|
|||||||
lMerge Tick (Event a) = Event a
|
lMerge Tick (Event a) = Event a
|
||||||
|
|
||||||
edge :: Mealy eff Bool (Event ())
|
edge :: Mealy eff Bool (Event ())
|
||||||
edge =
|
edge = edgeFrom False
|
||||||
|
|
||||||
|
-- | Edge that behaves as if the input has been `start` forever, so the first
|
||||||
|
-- True input does not fire when `start` is already True (no transition).
|
||||||
|
edgeFrom :: Bool -> Mealy eff Bool (Event ())
|
||||||
|
edgeFrom start =
|
||||||
mapAccum
|
mapAccum
|
||||||
(\(_, current) new -> (current, new))
|
(\(_, current) new -> (current, new))
|
||||||
(False, False)
|
(start, start)
|
||||||
(\(old, current) ->
|
(\(old, current) ->
|
||||||
if not old && current
|
if not old && current
|
||||||
then Event ()
|
then Event ()
|
||||||
|
|||||||
@@ -1,9 +1,18 @@
|
|||||||
module HomeAssistant.Controller.Door (DoorState(..)) where
|
module HomeAssistant.Controller.Door (DoorState(..), doorState) where
|
||||||
|
|
||||||
import GHC.Generics (Generic)
|
import GHC.Generics (Generic)
|
||||||
import Data.Serialize (Serialize)
|
import Data.Serialize (Serialize)
|
||||||
|
import AFRP (Mealy, Event)
|
||||||
|
import Data.Aeson (Value)
|
||||||
|
import Data.Text (Text)
|
||||||
|
import HomeAssistant.Controller.Entity (entityBool)
|
||||||
|
import Control.Arrow ((>>>), arr)
|
||||||
|
import Data.Bool (bool)
|
||||||
|
|
||||||
data DoorState = Open | Closed
|
data DoorState = Open | Closed
|
||||||
deriving (Show, Eq, Generic)
|
deriving (Show, Eq, Generic)
|
||||||
|
|
||||||
instance Serialize DoorState
|
instance Serialize DoorState
|
||||||
|
|
||||||
|
doorState :: Text -> Mealy eff (Event Value) (Event DoorState)
|
||||||
|
doorState entity = entityBool entity >>> arr (fmap (bool Closed Open))
|
||||||
@@ -1,31 +1,90 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
{-# LANGUAGE Arrows #-}
|
{-# LANGUAGE Arrows #-}
|
||||||
|
{-# LANGUAGE StrictData #-}
|
||||||
|
{-# LANGUAGE RecordWildCards #-}
|
||||||
module HomeAssistant.Controller.Hallway where
|
module HomeAssistant.Controller.Hallway where
|
||||||
|
|
||||||
import HomeAssistant.Controller (Presence, HASS, motion, motionToPresence, traceEvent, callServiceDyn, light, Target (..), LightCommand (..))
|
import HomeAssistant.Controller (Presence (..), HASS, motion, motionToPresence, callServiceDyn, light, Target (..), LightCommand (..), doorState, DoorState (Closed), callService)
|
||||||
import HomeAssistant.Controller.Light.Mode (LightingMode (..), lightingModeEvents)
|
|
||||||
import AFRP (Event (..))
|
import AFRP (Event (..))
|
||||||
import qualified AFRP
|
import qualified AFRP
|
||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value)
|
||||||
import Control.Arrow ((>>>), returnA)
|
import Control.Arrow ((>>>), arr, returnA)
|
||||||
import Data.Time (LocalTime(..), TimeOfDay (..))
|
import Data.Time (LocalTime(..), TimeOfDay (..))
|
||||||
import Data.Default (def)
|
import Data.Default (def)
|
||||||
|
import Data.Serialize (Serialize)
|
||||||
|
import GHC.Generics (Generic)
|
||||||
|
|
||||||
|
data Mode
|
||||||
|
= Quiet -- ^ Possibly sleep time, doors are open, minimize light leakage
|
||||||
|
| Regular -- ^ Doors are closed, light leakage is not a concern
|
||||||
|
deriving (Generic, Eq, Show)
|
||||||
|
|
||||||
|
instance Serialize Mode
|
||||||
|
|
||||||
|
data ModeInput = ModeInput
|
||||||
|
{ roomTimeOfDay :: TimeOfDay
|
||||||
|
, bedroomDoor :: Maybe DoorState
|
||||||
|
, childrenBedroomDoor :: Maybe DoorState
|
||||||
|
}
|
||||||
|
|
||||||
|
mode :: HASS (Event Value) Mode
|
||||||
|
mode = roomState >>> arr sleepMode
|
||||||
|
where
|
||||||
|
sleepMode :: ModeInput -> Mode
|
||||||
|
sleepMode ModeInput{bedroomDoor = Just Closed, childrenBedroomDoor = Just Closed} = Regular
|
||||||
|
sleepMode ModeInput{..}
|
||||||
|
| roomTimeOfDay > TimeOfDay 20 30 0 || roomTimeOfDay < TimeOfDay 7 30 0 = Quiet
|
||||||
|
| otherwise = Regular
|
||||||
|
roomState = ModeInput <$> timeOfDay <*> masterBedroom <*> childrenBedroom
|
||||||
|
timeOfDay = fmap localTimeOfDay AFRP.currentTime
|
||||||
|
masterBedroom = doorState "binary_sensor.makuuhuone_ovi_contact" >>> AFRP.holdKnown
|
||||||
|
childrenBedroom = doorState "binary_sensor.lasten_makuuhuone_ovi_contact" >>> AFRP.holdKnown
|
||||||
|
|
||||||
hallwayPresence :: HASS (Event Value) Presence
|
hallwayPresence :: HASS (Event Value) Presence
|
||||||
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
|
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
|
||||||
|
|
||||||
hallwayLightsController :: HASS (Event Value) ()
|
|
||||||
hallwayLightsController = proc x -> do
|
lightsOnTrigger :: HASS (Event Value) (Event ())
|
||||||
now <- AFRP.currentTime -< ()
|
lightsOnTrigger = hallwayPresence >>> arr (== Occupied) >>> AFRP.edge
|
||||||
p <- hallwayPresence -< x
|
|
||||||
ev <- lightingModeEvents -< p
|
modeTrigger :: HASS (Event Value) (Event Mode)
|
||||||
traceEvent -< ev
|
modeTrigger = ((,) <$> hallwayPresence <*> (mode >>> AFRP.changes)) >>> arr go
|
||||||
case ev of
|
|
||||||
-- The lights entity is a "group of lights" in hass
|
|
||||||
Event LightingOn | lightsAllowed now -> callServiceDyn "Lights on" (light [EntityId "light.hallway_lights"]) -< On def
|
|
||||||
Event LightingOff -> callServiceDyn "Lights off" (light [EntityId "light.hallway_lights"]) -< Off
|
|
||||||
_ -> returnA -< ()
|
|
||||||
where
|
where
|
||||||
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
|
go (Unoccupied, _) = Tick
|
||||||
|
go (Occupied, e) = e
|
||||||
|
|
||||||
|
modeC :: HASS (Event Value) ()
|
||||||
|
modeC = modeTrigger >>> mconcat
|
||||||
|
[ AFRP.filterEvent (== Quiet) AFRP.>>|| lightOff
|
||||||
|
, AFRP.filterEvent (== Regular) AFRP.>>|| lightOn
|
||||||
|
] >>>
|
||||||
|
arr (const ())
|
||||||
|
where
|
||||||
|
lightOff = callService "Lower light off" (light [EntityId "light.hallway_ceiling"] Off)
|
||||||
|
lightOn = callService "Lower light back on" (light [EntityId "light.hallway_ceiling"] (On def))
|
||||||
|
|
||||||
|
onC :: HASS (Event Value) ()
|
||||||
|
onC = proc ev -> do
|
||||||
|
trigger <- lightsOnTrigger -< ev
|
||||||
|
m <- mode -< ev
|
||||||
|
let entities = case m of
|
||||||
|
Quiet -> [EntityId "light.hallway_ceiling_2"]
|
||||||
|
Regular -> [EntityId "light.hallway_lights"]
|
||||||
|
case trigger of
|
||||||
|
Event _ -> lightsOn -< entities
|
||||||
|
Tick -> returnA -< ()
|
||||||
|
where
|
||||||
|
lightsOn = callServiceDyn "Lights on" (\es -> light es (On def))
|
||||||
|
|
||||||
|
lightsOffTrigger :: HASS (Event Value) (Event ())
|
||||||
|
lightsOffTrigger = hallwayPresence >>> arr (== Unoccupied) >>>
|
||||||
|
AFRP.edgeFrom True -- we start from 'edgeFrom True' because the initial state is to be unoccupied
|
||||||
|
|
||||||
|
offC :: HASS (Event Value) ()
|
||||||
|
offC = (lightsOffTrigger AFRP.>>|| lightsOff) >>>
|
||||||
|
arr (const ())
|
||||||
|
where
|
||||||
|
lightsOff = callService "Lights off" (light [EntityId "light.hallway_lights"] Off)
|
||||||
|
|
||||||
|
hallwayLightsController :: HASS (Event Value) ()
|
||||||
|
hallwayLightsController = onC <> offC <> modeC
|
||||||
@@ -3,10 +3,11 @@ module HomeAssistant.Controller.Presence
|
|||||||
, presence
|
, presence
|
||||||
, Motion(..)
|
, Motion(..)
|
||||||
, motion
|
, motion
|
||||||
|
, motionEvent
|
||||||
, motionToPresence
|
, motionToPresence
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import AFRP (Event, hold, lMerge, waitFor, tag, edge)
|
import AFRP (Event, hold, lMerge, waitFor, tag, edge, holdKnown)
|
||||||
import Control.Arrow (arr, (&&&))
|
import Control.Arrow (arr, (&&&))
|
||||||
import Control.Category ((>>>))
|
import Control.Category ((>>>))
|
||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value)
|
||||||
@@ -28,28 +29,32 @@ presence entityId = entityBool entityId
|
|||||||
>>> arr (fmap (bool Unoccupied Occupied))
|
>>> arr (fmap (bool Unoccupied Occupied))
|
||||||
|
|
||||||
|
|
||||||
data Motion = MotionDetected | MotionNotDetected | MotionUnknown
|
data Motion = MotionDetected | MotionNotDetected
|
||||||
deriving (Show, Eq, Generic)
|
deriving (Show, Eq, Generic)
|
||||||
|
|
||||||
|
|
||||||
motion :: T.Text -> HASS (Event Value) Motion
|
motionEvent :: T.Text -> HASS (Event Value) (Event Motion)
|
||||||
|
motionEvent entityId = entityBool entityId
|
||||||
|
>>> arr (fmap (bool MotionNotDetected MotionDetected))
|
||||||
|
|
||||||
|
motion :: T.Text -> HASS (Event Value) (Maybe Motion)
|
||||||
motion entityId = entityBool entityId
|
motion entityId = entityBool entityId
|
||||||
>>> arr (fmap (bool MotionNotDetected MotionDetected))
|
>>> arr (fmap (bool MotionNotDetected MotionDetected))
|
||||||
>>> hold MotionUnknown
|
>>> holdKnown
|
||||||
|
|
||||||
|
|
||||||
-- Convert a motion status into a simulated presence
|
-- Convert a motion status into a simulated presence
|
||||||
--
|
--
|
||||||
-- A motion tracker detects _motion_, but if you are still, it can't detect you.
|
-- A motion tracker detects _motion_, but if you are still, it can't detect you.
|
||||||
-- A simple and cheap heuristic is to assume the person is a bit longer there
|
-- A simple and cheap heuristic is to assume the person is a bit longer there
|
||||||
motionToPresence :: NominalDiffTime -> HASS Motion Presence
|
motionToPresence :: NominalDiffTime -> HASS (Maybe Motion) Presence
|
||||||
motionToPresence delay = (eventOccupied &&& eventUnoccupied)
|
motionToPresence delay = (eventOccupied &&& eventUnoccupied)
|
||||||
>>> arr (uncurry lMerge)
|
>>> arr (uncurry lMerge)
|
||||||
>>> AFRP.hold Unoccupied
|
>>> AFRP.hold Unoccupied
|
||||||
where
|
where
|
||||||
eventOccupied :: HASS Motion (Event Presence)
|
eventOccupied :: HASS (Maybe Motion) (Event Presence)
|
||||||
eventOccupied = arr (== MotionDetected) >>> edge >>> arr (fmap (const Occupied))
|
eventOccupied = arr (== Just MotionDetected) >>> edge >>> arr (fmap (const Occupied))
|
||||||
eventUnoccupied :: HASS Motion (Event Presence)
|
eventUnoccupied :: HASS (Maybe Motion) (Event Presence)
|
||||||
eventUnoccupied = arr (== MotionNotDetected) >>> waitFor delay >>> arr (tag Unoccupied)
|
eventUnoccupied = arr (== Just MotionNotDetected) >>> waitFor delay >>> arr (tag Unoccupied)
|
||||||
|
|
||||||
instance Serialize Motion
|
instance Serialize Motion
|
||||||
@@ -42,7 +42,7 @@ import HttpServer qualified
|
|||||||
import Katip (KatipContext, Namespace (Namespace), Severity (..), logF, logLocM, ls, runKatipContextT, runKatipT, sl, katipAddNamespace)
|
import Katip (KatipContext, Namespace (Namespace), Severity (..), logF, logLocM, ls, runKatipContextT, runKatipT, sl, katipAddNamespace)
|
||||||
import Network.Socket (withSocketsDo)
|
import Network.Socket (withSocketsDo)
|
||||||
import System.Environment (getEnv, lookupEnv)
|
import System.Environment (getEnv, lookupEnv)
|
||||||
import System.FilePath ((</>))
|
import System.FilePath ((</>), (<.>))
|
||||||
import System.Metrics qualified
|
import System.Metrics qualified
|
||||||
import Text.Read (readMaybe)
|
import Text.Read (readMaybe)
|
||||||
import UnliftIO.Async
|
import UnliftIO.Async
|
||||||
@@ -81,7 +81,7 @@ runController :: forall m. (HasCallStack, MonadCatch m, KatipContext m, MonadIO
|
|||||||
runController rootDir bus (Controller name machine) = checkpoint (Annotation name) $ katipAddNamespace ns $ do
|
runController rootDir bus (Controller name machine) = checkpoint (Annotation name) $ katipAddNamespace ns $ do
|
||||||
inbound <- liftIO $ atomically (dupTChan (busInbound bus))
|
inbound <- liftIO $ atomically (dupTChan (busInbound bus))
|
||||||
let workerDefinition = runMealy machine (channelHassEval @m bus)
|
let workerDefinition = runMealy machine (channelHassEval @m bus)
|
||||||
let path = rootDir </> T.unpack name
|
let path = rootDir </> T.unpack name <.> "dat"
|
||||||
worker <-
|
worker <-
|
||||||
load path workerDefinition >>= \case
|
load path workerDefinition >>= \case
|
||||||
Decoded a -> pure a
|
Decoded a -> pure a
|
||||||
|
|||||||
@@ -0,0 +1,211 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
|
module HallwaySpec (spec) where
|
||||||
|
|
||||||
|
import AFRP (Event (..))
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import Data.Aeson (Value)
|
||||||
|
import Data.Bool (bool)
|
||||||
|
import Data.Default (def)
|
||||||
|
import Data.List (scanl')
|
||||||
|
import Data.Time (UTCTime, addUTCTime)
|
||||||
|
import HomeAssistant.Controller
|
||||||
|
import HomeAssistant.Controller.Hallway
|
||||||
|
import Support
|
||||||
|
import Test.Hspec
|
||||||
|
import Test.Hspec.Hedgehog
|
||||||
|
import qualified Hedgehog.Gen as Gen
|
||||||
|
import qualified Hedgehog.Range as Range
|
||||||
|
|
||||||
|
day, night :: UTCTime
|
||||||
|
day = clock 10 0 -- 10:00, outside sleep hours
|
||||||
|
night = clock 21 0 -- 21:00, inside sleep hours (20:30 - 07:30)
|
||||||
|
|
||||||
|
motionSensor :: T.Text -> Event Value
|
||||||
|
motionSensor = Event . stateEvent "binary_sensor.hallway_movement_occupancy"
|
||||||
|
|
||||||
|
masterDoor :: T.Text -> Event Value
|
||||||
|
masterDoor = Event . stateEvent "binary_sensor.makuuhuone_ovi_contact"
|
||||||
|
|
||||||
|
childrenDoor :: T.Text -> Event Value
|
||||||
|
childrenDoor = Event . stateEvent "binary_sensor.lasten_makuuhuone_ovi_contact"
|
||||||
|
|
||||||
|
-- Same shape as the generator in PresenceSpec: mostly short gaps (< 500s
|
||||||
|
-- timeout), occasionally a 600s gap so presence can expire and the room can
|
||||||
|
-- become unoccupied again.
|
||||||
|
data TestEvent = TestEvent Int (Event Bool)
|
||||||
|
deriving Show
|
||||||
|
|
||||||
|
genTestEvent :: Gen TestEvent
|
||||||
|
genTestEvent = TestEvent
|
||||||
|
<$> Gen.frequency [(8, Gen.integral (Range.linear 0 20)), (2, pure 600)]
|
||||||
|
<*> Gen.frequency [(3, pure Tick), (1, Event <$> Gen.bool)]
|
||||||
|
|
||||||
|
-- | Presence and both of its presence-derived triggers, observed in lock-step
|
||||||
|
-- over the same motion stream, so the triggers can be judged against the
|
||||||
|
-- intermediate presence value at each step.
|
||||||
|
presenceProbe :: HASS (Event Value) (Presence, Event (), Event ())
|
||||||
|
presenceProbe = (,,) <$> hallwayPresence <*> lightsOnTrigger <*> lightsOffTrigger
|
||||||
|
|
||||||
|
-- | Expected firing steps: every step that *enters* `target`. The implicit
|
||||||
|
-- state before the first step is Unoccupied — the room starts unoccupied —
|
||||||
|
-- so an Unoccupied-trigger never fires at the first step.
|
||||||
|
edgeSteps :: Presence -> [Presence] -> [Int]
|
||||||
|
edgeSteps target ps =
|
||||||
|
[ i
|
||||||
|
| (i, (prev, p)) <- zip [0 ..] (zip (Unoccupied : ps) ps)
|
||||||
|
, prev /= target
|
||||||
|
, p == target
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
spec :: Spec
|
||||||
|
spec = describe "Hallway" $ do
|
||||||
|
lightsSpec
|
||||||
|
presenceTransitionSpec
|
||||||
|
modeTriggerSpec
|
||||||
|
|
||||||
|
presenceTransitionSpec :: Spec
|
||||||
|
presenceTransitionSpec = describe "presenceTriggers" $
|
||||||
|
it "fires exactly on the corresponding presence transitions" $ hedgehog $ do
|
||||||
|
events <- forAll $ Gen.list (Range.linear 0 100) genTestEvent
|
||||||
|
let steps = drop 1 $ scanl' (flip addUTCTime) day [fromIntegral t | TestEvent t _ <- events]
|
||||||
|
timed = values (runHASSTimed presenceProbe
|
||||||
|
(zipWith (\t (TestEvent _ e) ->
|
||||||
|
(t, stateEvent "binary_sensor.hallway_movement_occupancy" . bool "off" "on" <$> e))
|
||||||
|
steps events))
|
||||||
|
presences = [p | (p, _, _) <- timed]
|
||||||
|
onSteps = [i | (i, (_, Event (), _)) <- zip [0 ..] timed]
|
||||||
|
offSteps = [i | (i, (_, _, Event ())) <- zip [0 ..] timed]
|
||||||
|
onSteps === edgeSteps Occupied presences
|
||||||
|
offSteps === edgeSteps Unoccupied presences
|
||||||
|
cover 30 "at least one unoccupied -> occupied transition" (not (null onSteps))
|
||||||
|
cover 30 "at least one occupied -> unoccupied transition" (not (null offSteps))
|
||||||
|
|
||||||
|
-- | Presence, the chosen mode and the mode-adjustment trigger observed in
|
||||||
|
-- lock-step over the same event stream.
|
||||||
|
modeProbe :: HASS (Event Value) (Presence, Mode, Event Mode)
|
||||||
|
modeProbe = (,,) <$> hallwayPresence <*> mode <*> modeTrigger
|
||||||
|
|
||||||
|
data ModeAction
|
||||||
|
= Motion Bool -- ^ @True@ is motion detected
|
||||||
|
| MasterDoor Bool -- ^ @True@ is closed
|
||||||
|
| ChildrenDoor Bool -- ^ @True@ is closed
|
||||||
|
| Idle
|
||||||
|
deriving Show
|
||||||
|
|
||||||
|
data ModeEvent = ModeEvent Int ModeAction
|
||||||
|
deriving Show
|
||||||
|
|
||||||
|
genModeEvent :: Gen ModeEvent
|
||||||
|
genModeEvent = ModeEvent
|
||||||
|
<$> Gen.frequency [(6, Gen.integral (Range.linear 0 15)), (1, pure 900)]
|
||||||
|
<*> Gen.frequency [(4, Motion <$> Gen.bool)
|
||||||
|
,(2, MasterDoor <$> Gen.bool)
|
||||||
|
,(2, ChildrenDoor <$> Gen.bool)
|
||||||
|
,(2, pure Idle)
|
||||||
|
]
|
||||||
|
|
||||||
|
modeEventValue :: ModeAction -> Event Value
|
||||||
|
modeEventValue (Motion b) = Event $ stateEvent "binary_sensor.hallway_movement_occupancy" (bool "off" "on" b)
|
||||||
|
modeEventValue (MasterDoor b) = Event $ stateEvent "binary_sensor.makuuhuone_ovi_contact" (bool "off" "on" b)
|
||||||
|
modeEventValue (ChildrenDoor b) = Event $ stateEvent "binary_sensor.lasten_makuuhuone_ovi_contact" (bool "off" "on" b)
|
||||||
|
modeEventValue Idle = Tick
|
||||||
|
|
||||||
|
-- | The mode-adjustment trigger: the presence-based lights are already on
|
||||||
|
-- (room occupied), the world changed which lights should be on, so adjust.
|
||||||
|
-- The first observed mode is the baseline the lights-on trigger already
|
||||||
|
-- acted on, so it is not an adjustment.
|
||||||
|
modeTriggerSpec :: Spec
|
||||||
|
modeTriggerSpec = describe "modeTrigger" $
|
||||||
|
it "fires exactly on occupied steps that change the mode, tagged with the new mode" $ hedgehog $ do
|
||||||
|
events <- forAll $ Gen.list (Range.linear 0 100) genModeEvent
|
||||||
|
let steps = drop 1 $ scanl' (flip addUTCTime) (clock 20 0) [fromIntegral t | ModeEvent t _ <- events]
|
||||||
|
timed = values (runHASSTimed modeProbe
|
||||||
|
(zipWith (\t (ModeEvent _ a) -> (t, modeEventValue a)) steps events))
|
||||||
|
modes = [m | (_, m, _) <- timed]
|
||||||
|
-- The previous mode; at the first step it is the mode itself, since
|
||||||
|
-- the first observed mode is the baseline the lights-on trigger
|
||||||
|
-- already acted on, not an adjustment.
|
||||||
|
prior = case modes of [] -> []; m0 : _ -> m0 : init modes
|
||||||
|
expected =
|
||||||
|
[ i
|
||||||
|
| (i, (prevM, (p, m, _))) <- zip [0 ..] (zip prior timed)
|
||||||
|
, prevM /= m
|
||||||
|
, p == Occupied
|
||||||
|
]
|
||||||
|
suppressed =
|
||||||
|
[ () | (prevM, (p, m, _)) <- zip prior timed
|
||||||
|
, p == Unoccupied
|
||||||
|
, prevM /= m
|
||||||
|
]
|
||||||
|
fired = [i | (i, (_, _, Event _)) <- zip [0 ..] timed]
|
||||||
|
tags = [(i, tag) | (i, (_, _, Event tag)) <- zip [0 ..] timed]
|
||||||
|
fired === expected
|
||||||
|
tags === [(i, m) | i <- expected, let m = modes !! i]
|
||||||
|
cover 25 "fires at least once" (not (null fired))
|
||||||
|
cover 25 "suppressed a mode change while unoccupied" (not (null suppressed))
|
||||||
|
cover 25 "reaches quiet mode" (Quiet `elem` modes)
|
||||||
|
|
||||||
|
|
||||||
|
lightsSpec :: Spec
|
||||||
|
lightsSpec = do
|
||||||
|
describe "hallwayLightsController" $ do
|
||||||
|
it "turns the full lights on when someone enters during daytime" $
|
||||||
|
services (runHASSTimed hallwayLightsController [(day, motionSensor "on")])
|
||||||
|
`shouldBe` [[light [EntityId "light.hallway_lights"] (On def)]]
|
||||||
|
|
||||||
|
it "turns the full lights on when someone enters during daytime preceding tick" $
|
||||||
|
services (runHASSTimed hallwayLightsController [(day, Tick), (day, motionSensor "on")])
|
||||||
|
`shouldBe` [[], [light [EntityId "light.hallway_lights"] (On def)]]
|
||||||
|
|
||||||
|
it "turns the lights off when everyone leaves, without sleep mode" $
|
||||||
|
let later = 505 `addUTCTime` day
|
||||||
|
in services (runHASSTimed hallwayLightsController
|
||||||
|
[ (day, Tick)
|
||||||
|
, (day, motionSensor "on")
|
||||||
|
, (day, motionSensor "off")
|
||||||
|
, (later, Tick)
|
||||||
|
])
|
||||||
|
`shouldBe` [ []
|
||||||
|
, [light [EntityId "light.hallway_lights"] (On def)]
|
||||||
|
, []
|
||||||
|
, [light [EntityId "light.hallway_lights"] Off]
|
||||||
|
]
|
||||||
|
|
||||||
|
it "turns on only the ceiling light when entering during sleep hours with a door open" $
|
||||||
|
services (runHASSTimed hallwayLightsController
|
||||||
|
[ (night, Tick)
|
||||||
|
, (night, masterDoor "on")
|
||||||
|
, (night, motionSensor "on")
|
||||||
|
])
|
||||||
|
`shouldBe` [ []
|
||||||
|
, []
|
||||||
|
, [light [EntityId "light.hallway_ceiling_2"] (On def)]
|
||||||
|
]
|
||||||
|
|
||||||
|
it "sets the lower hallway light off when a door is opened during sleep hours" $
|
||||||
|
services (runHASSTimed hallwayLightsController
|
||||||
|
[ (night, masterDoor "off")
|
||||||
|
, (night, childrenDoor "off")
|
||||||
|
, (night, motionSensor "on")
|
||||||
|
, (night, masterDoor "on")
|
||||||
|
])
|
||||||
|
`shouldBe` [ []
|
||||||
|
, []
|
||||||
|
, [light [EntityId "light.hallway_lights"] (On def)]
|
||||||
|
, [light [EntityId "light.hallway_ceiling"] Off]
|
||||||
|
]
|
||||||
|
|
||||||
|
it "turns the lower hallway light on when the doors close while presence is active" $
|
||||||
|
services (runHASSTimed hallwayLightsController
|
||||||
|
[ (night, masterDoor "on")
|
||||||
|
, (night, motionSensor "on")
|
||||||
|
, (night, masterDoor "off")
|
||||||
|
, (night, childrenDoor "off")
|
||||||
|
])
|
||||||
|
`shouldBe` [ []
|
||||||
|
, [light [EntityId "light.hallway_ceiling_2"] (On def)]
|
||||||
|
, []
|
||||||
|
, [light [EntityId "light.hallway_ceiling"] (On def)]
|
||||||
|
]
|
||||||
@@ -8,12 +8,14 @@ import qualified BusSpec
|
|||||||
import qualified ConnectionSpec
|
import qualified ConnectionSpec
|
||||||
import qualified FlagsSpec
|
import qualified FlagsSpec
|
||||||
import qualified GraphingSpec
|
import qualified GraphingSpec
|
||||||
|
import qualified HallwaySpec
|
||||||
import qualified HttpServerSpec
|
import qualified HttpServerSpec
|
||||||
import qualified KitchenSpec
|
import qualified KitchenSpec
|
||||||
import qualified LivingroomSpec
|
import qualified LivingroomSpec
|
||||||
import qualified MetricsSpec
|
import qualified MetricsSpec
|
||||||
import qualified RuntimeSpec
|
import qualified RuntimeSpec
|
||||||
import qualified ControllerSpec
|
import qualified ControllerSpec
|
||||||
|
import qualified PresenceSpec
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = hspec $ do
|
main = hspec $ do
|
||||||
@@ -24,9 +26,11 @@ main = hspec $ do
|
|||||||
ConnectionSpec.spec
|
ConnectionSpec.spec
|
||||||
FlagsSpec.spec
|
FlagsSpec.spec
|
||||||
GraphingSpec.spec
|
GraphingSpec.spec
|
||||||
|
HallwaySpec.spec
|
||||||
HttpServerSpec.spec
|
HttpServerSpec.spec
|
||||||
KitchenSpec.spec
|
KitchenSpec.spec
|
||||||
LivingroomSpec.spec
|
LivingroomSpec.spec
|
||||||
MetricsSpec.spec
|
MetricsSpec.spec
|
||||||
RuntimeSpec.spec
|
RuntimeSpec.spec
|
||||||
ControllerSpec.spec
|
ControllerSpec.spec
|
||||||
|
PresenceSpec.spec
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
module PresenceSpec where
|
||||||
|
import Test.Hspec (Spec, describe, shouldBe, it)
|
||||||
|
import HomeAssistant.Controller (motion, motionToPresence, HASS, Presence(..))
|
||||||
|
import Control.Arrow ((>>>))
|
||||||
|
import Data.Aeson (Value)
|
||||||
|
import Support
|
||||||
|
import Data.Time (UTCTime)
|
||||||
|
import AFRP (Event(..))
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import Test.Hspec.Hedgehog
|
||||||
|
import qualified Hedgehog.Gen as Gen
|
||||||
|
import qualified Hedgehog.Range as Range
|
||||||
|
import Data.Time.Clock (addUTCTime, diffUTCTime)
|
||||||
|
import Data.List (scanl')
|
||||||
|
import Data.Bool (bool)
|
||||||
|
|
||||||
|
motionSensor :: T.Text -> Event Value
|
||||||
|
motionSensor = Event . stateEvent "sensor.foo"
|
||||||
|
|
||||||
|
day :: UTCTime
|
||||||
|
day = clock 10 0 -- 10:00, outside sleep hours
|
||||||
|
|
||||||
|
sut :: HASS (Event Value) Presence
|
||||||
|
sut = motion "sensor.foo" >>> motionToPresence 500
|
||||||
|
|
||||||
|
data TestEvent = TestEvent Int (Event Bool)
|
||||||
|
deriving Show
|
||||||
|
|
||||||
|
genTestEvent :: Gen TestEvent
|
||||||
|
genTestEvent = TestEvent
|
||||||
|
<$> Gen.frequency [(8, Gen.integral (Range.linear 0 20)), (2, pure 600)]
|
||||||
|
<*> Gen.frequency [(3, pure Tick), (1, Event <$> Gen.bool)]
|
||||||
|
|
||||||
|
spec :: Spec
|
||||||
|
spec = describe "Presence" $ do
|
||||||
|
it "Starts as unoccupied" $
|
||||||
|
values (runHASSTimed sut [(day, Tick)]) `shouldBe` [Unoccupied]
|
||||||
|
it "Detection motion means presence" $ do
|
||||||
|
values (runHASSTimed sut [(day, motionSensor "on")]) `shouldBe` [Occupied]
|
||||||
|
values (runHASSTimed sut [(day, Tick), (day, motionSensor "on")]) `shouldBe` [Unoccupied, Occupied]
|
||||||
|
it "Leaving doesn't mean immediately unoccupied room" $ do
|
||||||
|
values (runHASSTimed sut [(day, motionSensor "on"), (day, motionSensor "off")]) `shouldBe` [Occupied, Occupied]
|
||||||
|
it "re-detects occupancy only after the timeout since the previous detection" $ hedgehog $ do
|
||||||
|
events <- forAll $ Gen.list (Range.linear 0 100) genTestEvent
|
||||||
|
let steps = drop 1 $ scanl' (flip addUTCTime) day [fromIntegral t | TestEvent t _ <- events]
|
||||||
|
length steps === length events
|
||||||
|
let timed = zip steps (values (runHASSTimed sut (zipWith (\t (TestEvent _ e) -> (t, stateEvent "sensor.foo" . bool "off" "on" <$> e)) steps events)))
|
||||||
|
let transitions = [() | ((_, Occupied), (_, Unoccupied)) <- zip timed (drop 1 timed)]
|
||||||
|
cover 20 "occupied -> unoccupied transition" (not (null transitions))
|
||||||
|
let starts = [t | (Unoccupied, (t, Occupied)) <- zip (Unoccupied : map snd timed) timed]
|
||||||
|
let deltas = zipWith (\a b -> b `diffUTCTime` a) starts (drop 1 starts)
|
||||||
|
(null deltas || minimum deltas > 500) === True
|
||||||
@@ -6,11 +6,13 @@ module Support
|
|||||||
, runHASS
|
, runHASS
|
||||||
, runHASSTimed
|
, runHASSTimed
|
||||||
, services
|
, services
|
||||||
|
, values
|
||||||
, fakeRequest
|
, fakeRequest
|
||||||
, sec
|
, sec
|
||||||
, stateEvent
|
, stateEvent
|
||||||
, buttonEvent
|
, buttonEvent
|
||||||
, withTestLogEnv
|
, withTestLogEnv
|
||||||
|
, clock
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Control.Exception (bracket)
|
import Control.Exception (bracket)
|
||||||
@@ -75,9 +77,14 @@ runHASSTimed m = go (runMealy m interp)
|
|||||||
case runAcc (stepAuto w (Request t utc nil "test") a) [] of
|
case runAcc (stepAuto w (Request t utc nil "test") a) [] of
|
||||||
((b, w'), svcs) -> (b, svcs) : go w' as
|
((b, w'), svcs) -> (b, svcs) : go w' as
|
||||||
|
|
||||||
|
-- To observe external effects
|
||||||
services :: [(b, [Service])] -> [[Service]]
|
services :: [(b, [Service])] -> [[Service]]
|
||||||
services = map snd
|
services = map snd
|
||||||
|
|
||||||
|
-- To observe intermediary steps
|
||||||
|
values :: [(b, [Service])] -> [b]
|
||||||
|
values = map fst
|
||||||
|
|
||||||
-- | Build a state-trigger payload matching `entityChangeEvent'` / `entityBool'`
|
-- | Build a state-trigger payload matching `entityChangeEvent'` / `entityBool'`
|
||||||
-- lenses. The subscribe_trigger websocket event wraps the trigger datum under
|
-- lenses. The subscribe_trigger websocket event wraps the trigger datum under
|
||||||
-- `event.variables.trigger`, with `entity_id` and `to_state.state` fields.
|
-- `event.variables.trigger`, with `entity_id` and `to_state.state` fields.
|
||||||
@@ -106,3 +113,11 @@ buttonEvent entityId eventType = object
|
|||||||
]
|
]
|
||||||
]
|
]
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-- runHASSTimed builds its request with the UTC zone, so a UTCTime given as
|
||||||
|
-- seconds-of-day reads back as exactly that local time of day
|
||||||
|
clock :: Int -> Int -> UTCTime
|
||||||
|
clock h m = sec (fromIntegral (h * 60 + m) * 60)
|
||||||
|
|
||||||
Reference in new issue
Block a user