54 lines
2.4 KiB
Haskell
54 lines
2.4 KiB
Haskell
{-# 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
|