module HomeAssistant.Controller.Presence ( Presence(..) , presence , Motion(..) , motion , motionToPresence ) where import AFRP (Event, hold, lMerge, waitFor, tag, edge) import Control.Arrow (arr, (&&&)) import Control.Category ((>>>)) import Data.Aeson (Value) import qualified Data.Text as T import Data.Bool (bool) import Data.Serialize (Serialize) import GHC.Generics (Generic) import Data.Time (NominalDiffTime) import HomeAssistant.Controller.Entity (entityBool) import HomeAssistant.Controller.Effect (HASS) data Presence = Occupied | Unoccupied deriving (Show, Eq, Generic) instance Serialize Presence presence :: T.Text -> HASS (Event Value) (Event Presence) presence entityId = entityBool entityId >>> arr (fmap (bool Unoccupied Occupied)) data Motion = MotionDetected | MotionNotDetected | MotionUnknown deriving (Show, Eq, Generic) motion :: T.Text -> HASS (Event Value) Motion motion entityId = entityBool entityId >>> arr (fmap (bool MotionNotDetected MotionDetected)) >>> hold MotionUnknown -- Convert a motion status into a simulated presence -- -- 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 motionToPresence :: NominalDiffTime -> HASS Motion Presence motionToPresence delay = (eventOccupied &&& eventUnoccupied) >>> arr (uncurry lMerge) >>> AFRP.hold Unoccupied where eventOccupied :: HASS Motion (Event Presence) eventOccupied = arr (== MotionDetected) >>> edge >>> arr (fmap (const Occupied)) eventUnoccupied :: HASS Motion (Event Presence) eventUnoccupied = arr (== MotionNotDetected) >>> waitFor delay >>> arr (tag Unoccupied) instance Serialize Motion