Compare commits
16
Commits
6caa2acafb
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c89504399 | ||
|
|
383143024a | ||
|
|
c5c11fe8d3 | ||
|
|
05263fed2b | ||
|
|
6e35445090 | ||
|
|
95fcc61c4f | ||
|
|
2039d03a5e | ||
|
|
868a5d7e4f | ||
|
|
d710251a4e | ||
|
|
c78f5a4a6d | ||
|
|
889ad1c091 | ||
|
|
5f8b3cbe00 | ||
|
|
078f24e4b9 | ||
|
|
15e50322c4 | ||
|
|
617bd255ff | ||
|
|
022342af32 |
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
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ library
|
|||||||
|
|
||||||
-- Modules exported by the library.
|
-- Modules exported by the library.
|
||||||
exposed-modules: AFRP
|
exposed-modules: AFRP
|
||||||
|
, AFRP.Diagram
|
||||||
, HomeAssistant.Controller
|
, HomeAssistant.Controller
|
||||||
, HomeAssistant.Controller.Bedroom
|
, HomeAssistant.Controller.Bedroom
|
||||||
, HomeAssistant.Controller.Children
|
, HomeAssistant.Controller.Children
|
||||||
@@ -181,6 +182,7 @@ test-suite home-assistant-controller-test
|
|||||||
, ConnectionSpec
|
, ConnectionSpec
|
||||||
, FlagsSpec
|
, FlagsSpec
|
||||||
, GraphingSpec
|
, GraphingSpec
|
||||||
|
, HallwaySpec
|
||||||
, HttpServerSpec
|
, HttpServerSpec
|
||||||
, KitchenSpec
|
, KitchenSpec
|
||||||
, LivingroomSpec
|
, LivingroomSpec
|
||||||
@@ -188,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:
|
||||||
|
|||||||
+57
-25
@@ -1,11 +1,13 @@
|
|||||||
{-# LANGUAGE LambdaCase #-}
|
{-# LANGUAGE LambdaCase #-}
|
||||||
|
{-# LANGUAGE Arrows #-}
|
||||||
|
{-# LANGUAGE TypeOperators #-}
|
||||||
|
|
||||||
module AFRP
|
module AFRP
|
||||||
( Mealy(..)
|
( Mealy(..)
|
||||||
, Auto(..)
|
, Auto(..)
|
||||||
, DecodedAuto(..)
|
, DecodedAuto(..)
|
||||||
, eff
|
, eff
|
||||||
, withEntities
|
, named
|
||||||
, Event(..)
|
, Event(..)
|
||||||
, hold
|
, hold
|
||||||
, holdKnown
|
, holdKnown
|
||||||
@@ -18,8 +20,10 @@ module AFRP
|
|||||||
, changes
|
, changes
|
||||||
, whenA
|
, whenA
|
||||||
, filterA
|
, filterA
|
||||||
|
, filterEvent
|
||||||
, thenA
|
, thenA
|
||||||
, (>>|)
|
, (>>|)
|
||||||
|
, (>>||)
|
||||||
, toEvent
|
, toEvent
|
||||||
, lMerge
|
, lMerge
|
||||||
, Pair(..)
|
, Pair(..)
|
||||||
@@ -27,6 +31,7 @@ module AFRP
|
|||||||
, SerializeUTCTime(..)
|
, SerializeUTCTime(..)
|
||||||
, SerializeLocalTime(..)
|
, SerializeLocalTime(..)
|
||||||
, edge
|
, edge
|
||||||
|
, edgeFrom
|
||||||
, waitFor
|
, waitFor
|
||||||
, duration
|
, duration
|
||||||
, tag
|
, tag
|
||||||
@@ -67,6 +72,8 @@ import qualified Data.Conduit.Cereal as CC
|
|||||||
import qualified Conduit as C
|
import qualified Conduit as C
|
||||||
import Control.Monad.Catch (MonadCatch, handle)
|
import Control.Monad.Catch (MonadCatch, handle)
|
||||||
import Control.Exception.Annotated (throw)
|
import Control.Exception.Annotated (throw)
|
||||||
|
import AFRP.Diagram
|
||||||
|
import Data.Text (Text)
|
||||||
|
|
||||||
|
|
||||||
data Codec s = Codec { getter :: !(Get s), putter :: !(Putter s) }
|
data Codec s = Codec { getter :: !(Get s), putter :: !(Putter s) }
|
||||||
@@ -257,54 +264,58 @@ load path a = handle defaultOnMissingFile (flip deserialize a <$> liftIO (B.read
|
|||||||
| isDoesNotExistError e = pure $ FailDecode "State doesn't exist yet" a
|
| isDoesNotExistError e = pure $ FailDecode "State doesn't exist yet" a
|
||||||
| otherwise = throw e
|
| otherwise = throw e
|
||||||
|
|
||||||
|
|
||||||
-- | The set of entity ids an arrow subscribes to. Static: it does not
|
-- | The set of entity ids an arrow subscribes to. Static: it does not
|
||||||
-- change as the machine steps, so the runtime can read it once to build
|
-- change as the machine steps, so the runtime can read it once to build
|
||||||
-- trigger subscriptions.
|
-- trigger subscriptions.
|
||||||
data Mealy eff a b = Mealy
|
data Mealy eff a b = Mealy
|
||||||
{ entities :: S.Set T.Text
|
{ entities :: S.Set T.Text
|
||||||
|
, runDiagramC :: forall x. (DiagramF x -> x) -> x
|
||||||
, runMealy :: forall m. Monad m => (forall x. eff x -> m x) -> Auto m a b
|
, runMealy :: forall m. Monad m => (forall x. eff x -> m x) -> Auto m a b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
-- Provide a name
|
||||||
|
named :: Text -> Mealy eff a b -> Mealy eff a b
|
||||||
|
named n f = f{runDiagramC = \run -> run (Step n (runDiagramC f run))}
|
||||||
|
|
||||||
instance Semigroup b => Semigroup (Mealy eff a b) where
|
instance Semigroup b => Semigroup (Mealy eff a b) where
|
||||||
Mealy ast af <> Mealy bst bf = Mealy (ast <> bst) $ \nt -> af nt <> bf nt
|
Mealy ast ad af <> Mealy bst bd bf = Mealy (ast <> bst) (combineDiagram Merge ad bd) $ \nt -> af nt <> bf nt
|
||||||
|
|
||||||
|
|
||||||
instance Monoid b => Monoid (Mealy eff a b) where
|
instance Monoid b => Monoid (Mealy eff a b) where
|
||||||
mempty = Mealy mempty $ \_nt -> mempty
|
mempty = Mealy mempty emptyDiagram $ \_nt -> mempty
|
||||||
|
|
||||||
eff :: (Request -> a -> eff b) -> Mealy eff a b
|
eff :: (Request -> a -> eff b) -> Mealy eff a b
|
||||||
eff f = Mealy mempty $ \nt -> do
|
eff f = Mealy mempty emptyDiagram $ \nt -> do
|
||||||
Stateful (Codec get put) (State () False) $ \s req a -> do
|
Stateful (Codec get put) (State () False) $ \s req a -> do
|
||||||
b <- nt (f req a)
|
b <- nt (f req a)
|
||||||
pure (b, s)
|
pure (b, s)
|
||||||
|
|
||||||
-- | Override the static entity set of an arrow. Use when a combinator
|
|
||||||
-- (e.g. 'switch') hides continuation entities from the runtime's
|
|
||||||
-- startup subscription scan.
|
|
||||||
withEntities :: S.Set T.Text -> Mealy eff a b -> Mealy eff a b
|
|
||||||
withEntities es (Mealy _ f) = Mealy es f
|
|
||||||
|
|
||||||
instance Category (Mealy eff) where
|
instance Category (Mealy eff) where
|
||||||
{- HLINT ignore "Use const" -}
|
{- HLINT ignore "Use const" -}
|
||||||
id = Mealy mempty $ \_nt -> id
|
id = Mealy mempty emptyDiagram $ \_nt -> id
|
||||||
(Mealy ast f) . (Mealy bst g) = Mealy (ast <> bst) $ \nt -> do
|
(Mealy ast ad f) . (Mealy bst bd g) = Mealy (ast <> bst) (combineDiagram Then bd ad) $ \nt -> do
|
||||||
f nt . g nt
|
f nt . g nt
|
||||||
|
|
||||||
instance Arrow (Mealy eff) where
|
instance Arrow (Mealy eff) where
|
||||||
arr f = Mealy mempty $ \_nt -> arr f
|
arr f = Mealy mempty emptyDiagram $ \_nt -> arr f
|
||||||
first (Mealy st f) = Mealy st $ \nt -> first (f nt)
|
first (Mealy st d f) = Mealy st d $ \nt -> first (f nt)
|
||||||
|
(Mealy ast ad f) &&& (Mealy bst bd g) = Mealy (ast <> bst) (combineDiagram Both ad bd) $ \nt -> do
|
||||||
|
f nt &&& g nt
|
||||||
|
|
||||||
instance ArrowChoice (Mealy eff) where
|
instance ArrowChoice (Mealy eff) where
|
||||||
left (Mealy st f) = Mealy st $ \nt -> left (f nt)
|
left (Mealy st d f) = Mealy st d $ \nt -> left (f nt)
|
||||||
|
(Mealy ast ad f) +++ (Mealy bst bd g) = Mealy (ast <> bst) (combineDiagram Branch ad bd) $ \nt -> do
|
||||||
|
f nt +++ g nt
|
||||||
|
|
||||||
|
|
||||||
instance Functor (Mealy eff a) where
|
instance Functor (Mealy eff a) where
|
||||||
fmap f (Mealy st g) = Mealy st $ \nt -> fmap f (g nt)
|
fmap f (Mealy st d g) = Mealy st d $ \nt -> fmap f (g nt)
|
||||||
|
|
||||||
instance Applicative (Mealy eff a) where
|
instance Applicative (Mealy eff a) where
|
||||||
pure b = Mealy mempty $ \_ -> pure b
|
pure b = Mealy mempty emptyDiagram $ \_ -> pure b
|
||||||
Mealy ast f <*> Mealy bst x = Mealy (ast <> bst) $ \nt ->
|
Mealy ast ad f <*> Mealy bst bd x = Mealy (ast <> bst) (combineDiagram Compose ad bd) $ \nt ->
|
||||||
f nt <*> x nt
|
f nt <*> x nt
|
||||||
|
|
||||||
data Event a
|
data Event a
|
||||||
@@ -332,7 +343,7 @@ hold def = mapAccum step def id
|
|||||||
holdKnown :: (Serialize a, Eq a) => Mealy m (Event a) (Maybe a)
|
holdKnown :: (Serialize a, Eq a) => Mealy m (Event a) (Maybe a)
|
||||||
holdKnown = arr (fmap Just) >>> hold Nothing
|
holdKnown = arr (fmap Just) >>> hold Nothing
|
||||||
|
|
||||||
snapshot :: (Serialize a, Eq a) => a -> Mealy m (Event (), a) a
|
snapshot :: (Serialize a, Eq a) => a -> Mealy m (Event x, a) a
|
||||||
snapshot def = mapAccum step def id
|
snapshot def = mapAccum step def id
|
||||||
where
|
where
|
||||||
step prev (Tick, _) = prev
|
step prev (Tick, _) = prev
|
||||||
@@ -369,10 +380,10 @@ preMapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure
|
|||||||
|
|
||||||
|
|
||||||
mapAccum :: (Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
mapAccum :: (Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
||||||
mapAccum step x extract = Mealy mempty $ \_nt -> mapAccum' step x extract
|
mapAccum step x extract = Mealy mempty emptyDiagram $ \_nt -> mapAccum' step x extract
|
||||||
|
|
||||||
preMapAccum :: (Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
preMapAccum :: (Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
||||||
preMapAccum step x extract = Mealy mempty $ \_nt -> preMapAccum' step x extract
|
preMapAccum step x extract = Mealy mempty emptyDiagram $ \_nt -> preMapAccum' step x extract
|
||||||
|
|
||||||
mapAccum' :: forall m x a b. (Monad m, Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Auto m a b
|
mapAccum' :: forall m x a b. (Monad m, Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Auto m a b
|
||||||
mapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure $ step s a)
|
mapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure $ step s a)
|
||||||
@@ -381,7 +392,7 @@ mapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure $ s
|
|||||||
step s a = let s' = f (state s) a in (extract s', State s' (dirty s || state s /= s'))
|
step s a = let s' = f (state s) a in (extract s', State s' (dirty s || state s /= s'))
|
||||||
|
|
||||||
preMapAccumRequest :: (Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
preMapAccumRequest :: (Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
||||||
preMapAccumRequest step x extract = Mealy mempty $ \_ -> preMapAccumRequest' step x extract
|
preMapAccumRequest step x extract = Mealy mempty emptyDiagram $ \_ -> preMapAccumRequest' step x extract
|
||||||
|
|
||||||
preMapAccumRequest' :: forall m x a b. (Serialize x, Eq x, Monad m) => (Request -> x -> a -> x) -> x -> (x -> b) -> Auto m a b
|
preMapAccumRequest' :: forall m x a b. (Serialize x, Eq x, Monad m) => (Request -> x -> a -> x) -> x -> (x -> b) -> Auto m a b
|
||||||
preMapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
|
preMapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
|
||||||
@@ -390,7 +401,7 @@ preMapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s r
|
|||||||
step s req a = let s' = f req (state s) a in (extract (state s), State s' (dirty s || state s /= s'))
|
step s req a = let s' = f req (state s) a in (extract (state s), State s' (dirty s || state s /= s'))
|
||||||
|
|
||||||
mapAccumRequest :: (Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
mapAccumRequest :: (Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
||||||
mapAccumRequest step x extract = Mealy mempty $ \_ -> mapAccumRequest' step x extract
|
mapAccumRequest step x extract = Mealy mempty emptyDiagram $ \_ -> mapAccumRequest' step x extract
|
||||||
|
|
||||||
mapAccumRequest' :: forall m x a b. (Monad m, Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Auto m a b
|
mapAccumRequest' :: forall m x a b. (Monad m, Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Auto m a b
|
||||||
mapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
|
mapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
|
||||||
@@ -484,6 +495,13 @@ whenA predicate auto = arr (\a -> if predicate a then Left a else Right ()) >>>
|
|||||||
filterA :: (a -> Bool) -> Mealy eff a (Either () a)
|
filterA :: (a -> Bool) -> Mealy eff a (Either () a)
|
||||||
filterA f = arr $ \a -> bool (Left ()) (Right a) (f a)
|
filterA f = arr $ \a -> bool (Left ()) (Right a) (f a)
|
||||||
|
|
||||||
|
-- filters events through if they match the predicate
|
||||||
|
filterEvent :: (ArrowChoice cat, Arrow cat) => (a -> Bool) -> Event a `cat` Event a
|
||||||
|
filterEvent predicate = proc ev -> do
|
||||||
|
case ev of
|
||||||
|
Event a | predicate a -> id -< ev
|
||||||
|
_ -> arr (const Tick) -< ()
|
||||||
|
|
||||||
thenA :: (ArrowChoice cat, Arrow cat) => cat a (Either b1 c) -> cat c (Either b1 b2) -> cat a (Either b1 b2)
|
thenA :: (ArrowChoice cat, Arrow cat) => cat a (Either b1 c) -> cat c (Either b1 b2) -> cat a (Either b1 b2)
|
||||||
thenA f g = f >>> arr Left ||| g
|
thenA f g = f >>> arr Left ||| g
|
||||||
|
|
||||||
@@ -492,6 +510,15 @@ thenA f g = f >>> arr Left ||| g
|
|||||||
|
|
||||||
infixl 2 >>|
|
infixl 2 >>|
|
||||||
|
|
||||||
|
(>>||) :: (ArrowChoice cat, Arrow cat) => cat a (Event b) -> cat b c -> cat a (Event c)
|
||||||
|
f >>|| g = proc x -> do
|
||||||
|
e <- f -< x
|
||||||
|
case e of
|
||||||
|
Event e' -> g >>> arr Event -< e'
|
||||||
|
Tick -> arr (const Tick) -< ()
|
||||||
|
|
||||||
|
infixr 1 >>||
|
||||||
|
|
||||||
toEvent :: Mealy eff (Either () a) (Event a)
|
toEvent :: Mealy eff (Either () a) (Event a)
|
||||||
toEvent = arr (either (const Tick) Event)
|
toEvent = arr (either (const Tick) Event)
|
||||||
|
|
||||||
@@ -502,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 ()
|
||||||
@@ -606,7 +638,7 @@ requestLocalTime :: Request -> LocalTime
|
|||||||
requestLocalTime Request{requestTime, requestTimeZone} = utcToLocalTime requestTimeZone requestTime
|
requestLocalTime Request{requestTime, requestTimeZone} = utcToLocalTime requestTimeZone requestTime
|
||||||
|
|
||||||
currentTime :: Mealy eff a LocalTime
|
currentTime :: Mealy eff a LocalTime
|
||||||
currentTime = Mealy mempty $ \_nt -> Fun $ \req _ ->
|
currentTime = Mealy mempty emptyDiagram $ \_nt -> Fun $ \req _ ->
|
||||||
requestLocalTime req
|
requestLocalTime req
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
module AFRP.Diagram where
|
||||||
|
import Data.Text (Text)
|
||||||
|
import qualified Text.Printf as Text
|
||||||
|
import qualified Data.Text as T
|
||||||
|
|
||||||
|
-- For rendering the arrows
|
||||||
|
data DiagramF f
|
||||||
|
= Empty
|
||||||
|
| Step Text f -- Named step
|
||||||
|
| Then f f -- >>>
|
||||||
|
| Both f f -- &&&
|
||||||
|
| Branch f f -- |||
|
||||||
|
| Merge f f -- <>
|
||||||
|
| Compose f f -- <*>
|
||||||
|
|
||||||
|
type DiagramAlgebra a = DiagramF a -> a
|
||||||
|
type DiagramC= forall a. DiagramAlgebra a -> a
|
||||||
|
|
||||||
|
combineDiagram :: (forall a. a -> a -> DiagramF a) -> DiagramC -> DiagramC -> DiagramC
|
||||||
|
combineDiagram constructor a b r = r (constructor (a r) (b r))
|
||||||
|
|
||||||
|
emptyDiagram :: DiagramC
|
||||||
|
emptyDiagram r = r Empty
|
||||||
|
|
||||||
|
|
||||||
|
renderF :: DiagramF (Maybe T.Text) -> Maybe T.Text
|
||||||
|
renderF = \case
|
||||||
|
Empty -> Nothing
|
||||||
|
Step n x -> Just $ n <> T.pack (maybe "" (Text.printf "( %s )") x)
|
||||||
|
Then (Just a) (Just b) -> Just $ a <> " -> " <> b
|
||||||
|
Then (Just a) _ -> Just a
|
||||||
|
Then _ b -> b
|
||||||
|
Both (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s, %s)" a b
|
||||||
|
Both (Just a) _ -> Just a
|
||||||
|
Both _ b -> b
|
||||||
|
Branch (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s || %s)" a b
|
||||||
|
-- I'm leaving this here. This would be technically more correct (showing
|
||||||
|
-- the empty branch, ie. the full if-then-else, but often we care about a
|
||||||
|
-- more simplistic `when` style structure
|
||||||
|
-- Branch (Just a) Nothing -> Just $ T.pack $ Text.printf "(%s || <skip>)" a
|
||||||
|
Branch (Just a) Nothing -> Just $ T.pack $ Text.printf "%s" a
|
||||||
|
Branch _ b -> b
|
||||||
|
Merge (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s, %s)" a b
|
||||||
|
Merge (Just a) _ -> Just a
|
||||||
|
Merge _ b -> b
|
||||||
|
Compose (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s, %s)" a b
|
||||||
|
Compose (Just a) _ -> Just a
|
||||||
|
Compose _ b -> b
|
||||||
@@ -1,21 +1,18 @@
|
|||||||
{-# LANGUAGE Arrows #-}
|
{-# LANGUAGE Arrows #-}
|
||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
{-# LANGUAGE DerivingVia #-}
|
|
||||||
module HomeAssistant.Controller.Bedroom where
|
module HomeAssistant.Controller.Bedroom where
|
||||||
|
|
||||||
import HomeAssistant.Controller
|
import HomeAssistant.Controller
|
||||||
import qualified Data.Text as T
|
import qualified Data.Text as T
|
||||||
import AFRP (Event (..), lMerge, duration, edge)
|
import AFRP (Event (..), edge, filterEvent, hold, named, snapshot, tag, waitFor, (>>||))
|
||||||
import Data.Aeson (Value, object, (.=))
|
import Data.Aeson (Value, object, (.=))
|
||||||
import Control.Arrow ((>>>), returnA, arr, Arrow (..))
|
import Control.Arrow ((>>>), returnA, arr, Arrow (..))
|
||||||
import Data.Bool (bool)
|
import Data.Bool (bool)
|
||||||
import Data.Time (NominalDiffTime)
|
|
||||||
import qualified AFRP
|
import qualified AFRP
|
||||||
import Data.Map (Map)
|
import Data.Map (Map)
|
||||||
import qualified Data.Map.Strict as M
|
import qualified Data.Map.Strict as M
|
||||||
import Data.Serialize.Text ()
|
import Data.Serialize.Text ()
|
||||||
import Data.Default (def)
|
import Data.Default (def)
|
||||||
import Data.Serialize (Serialize)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -31,62 +28,80 @@ createBedroomScene = Service
|
|||||||
, "snapshot_entities" .= [l | EntityId l <- bedroomLightTargets]
|
, "snapshot_entities" .= [l | EntityId l <- bedroomLightTargets]
|
||||||
]
|
]
|
||||||
, serviceTarget= []
|
, serviceTarget= []
|
||||||
|
, serviceExclusions= []
|
||||||
}
|
}
|
||||||
|
|
||||||
-- Bedroom presence
|
-- Bedroom presence
|
||||||
bedroomPresence :: HASS (Event Value) (Event Presence)
|
bedroomPresence :: HASS (Event Value) (Event Presence)
|
||||||
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
|
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
|
||||||
|
|
||||||
presenceLightEvents :: HASS (Event Value) (Event LightingMode)
|
bedroomPresenceOccupied :: HASS (Event Value) Bool
|
||||||
presenceLightEvents =
|
bedroomPresenceOccupied = bedroomPresence >>> hold Unoccupied >>> arr (== Occupied)
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
bedroomLightStatus :: HASS (Event Value) (Map T.Text LightObservation)
|
bedroomLightStatus :: HASS (Event Value) (Map T.Text LightObservation)
|
||||||
bedroomLightStatus = M.fromList <$> traverse (\e -> (e,) <$> observedLight e) [e | EntityId e <- bedroomLightTargets]
|
bedroomLightStatus = M.fromList <$> traverse (\e -> (e,) <$> observedLight e) [e | EntityId e <- bedroomLightTargets]
|
||||||
|
|
||||||
newtype Snapshot = Snapshot { getSnapshot :: Map T.Text LightObservation }
|
-- Ready to sleep: someone detected and every light off or dimmed far down
|
||||||
deriving (Show, Eq)
|
readyForSleep :: HASS (Event Value) Bool
|
||||||
deriving Serialize via (Map T.Text LightObservation)
|
readyForSleep = (&&) <$> bedroomPresenceOccupied <*> (all sleepLight . M.elems <$> bedroomLightStatus)
|
||||||
|
where
|
||||||
|
-- ~10% of the 0-255 brightness range
|
||||||
|
sleepLight o = not (observedOn o) || maybe False (<= 25) (observedBrightness o)
|
||||||
|
|
||||||
lightLevel :: HASS (Event Value) Int
|
lightLevel :: HASS (Event Value) Int
|
||||||
lightLevel = entityRead "sensor.presence_sensor_bedroom_light_level" >>> AFRP.hold 1
|
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 :: HASS (Event Value) ()
|
||||||
bedroomPresenceController = proc x -> do
|
bedroomPresenceController =
|
||||||
p <- presenceLightEvents >>> traceEvent -< x
|
((,,,) <$> bedroomPresenceOccupied <*> cappedLightLevel <*> bedroomLightStatus <*> snapshotOnLeaving)
|
||||||
capped <- lightLevel >>> arr (< 4) -< x
|
>>> mconcat
|
||||||
snap <- (doSnapshot &&& bedroomLightStatus) >>> AFRP.snapshot M.empty >>> arr Snapshot -< x
|
[ AFRP.named "Lights on" lightsOn
|
||||||
-- This line is just for debugging
|
, AFRP.named "Lights sleep" lightsSleep
|
||||||
_ <- AFRP.changes >>> traceEvent -< snap
|
, AFRP.named "Lights off" lightsOff
|
||||||
case p of
|
]
|
||||||
Event LightingOff -> do
|
>>> arr (const ()) -- I don't like this extra arr here
|
||||||
callService (light bedroomLightTargets Off) -< ()
|
|
||||||
Event LightingOn -> do
|
|
||||||
callServicesDyn (\(c,xs) -> concatMap (uncurry (toLight c)) xs) -< (capped, M.toList (getSnapshot snap))
|
|
||||||
returnA -< ()
|
|
||||||
Event LightingSleep -> do
|
|
||||||
callService (activateScene "scene.makuuhuone_lepotila") -< ()
|
|
||||||
_ -> returnA -< ()
|
|
||||||
where
|
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 :: Bool -> T.Text -> LightObservation -> [Service]
|
||||||
toLight _ entityId LightObservation{observedOn=False} = [light [EntityId entityId] Off]
|
toLight _ entityId LightObservation{observedOn=False} = [light [EntityId entityId] [] Off]
|
||||||
toLight capped entityId LightObservation{observedOn=True, observedTemperature=t, observedBrightness=b} =
|
toLight capped entityId LightObservation{observedOn=True, observedTemperature=t, observedBrightness=b} =
|
||||||
[ light [EntityId entityId] (On def
|
[ light [EntityId entityId] [] (On def
|
||||||
{lightBrightness = fmap (\b' -> BrightnessAbsolute $ if capped then 140 `min` b' else b') b
|
{lightBrightness = fmap (\b' -> BrightnessAbsolute $ if capped then 140 `min` b' else b') b
|
||||||
, lightColorTemperature = t
|
, lightColorTemperature = t
|
||||||
})
|
})
|
||||||
]
|
]
|
||||||
doSnapshot = presenceLightEvents
|
|
||||||
>>> arr (\ev -> if ev == Event LightingSleep then Event () else Tick)
|
|
||||||
|
|
||||||
|
|
||||||
data BedroomControls
|
data BedroomControls
|
||||||
@@ -110,21 +125,27 @@ bedroomButtonController = proc x -> do
|
|||||||
-- Any event will cause the sleep mode to be turned off
|
-- Any event will cause the sleep mode to be turned off
|
||||||
case ev of
|
case ev of
|
||||||
Event (Masse (OnButton ShortRelease)) -> do
|
Event (Masse (OnButton ShortRelease)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_masse") -< ()
|
callService "scene.makuuhuone_masse" (activateScene "scene.makuuhuone_masse") -< ()
|
||||||
Event (Masse (OnButton DoubleClick)) -> do
|
Event (Masse (OnButton DoubleClick)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_keski") -< ()
|
callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
|
||||||
Event (Masse (OnButton LongClick)) -> do
|
Event (Masse (OnButton LongClick)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< ()
|
||||||
|
Event (Masse (OffButton LongClick)) -> do
|
||||||
|
callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
|
||||||
|
callService "Hallway lights off" (light [EntityId "light.hallway_lights"] [] Off) -< ()
|
||||||
Event (Masse (OffButton _)) -> do
|
Event (Masse (OffButton _)) -> do
|
||||||
callService (light [AreaId "makuuhuone"] Off) -< ()
|
callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
|
||||||
Event (Enishen (OnButton ShortRelease)) -> do
|
Event (Enishen (OnButton ShortRelease)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_jemina") -< ()
|
callService "scene.makuuhuone_jemina" (activateScene "scene.makuuhuone_jemina") -< ()
|
||||||
Event (Enishen (OnButton DoubleClick)) -> do
|
Event (Enishen (OnButton DoubleClick)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_keski") -< ()
|
callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
|
||||||
Event (Enishen (OnButton LongClick)) -> do
|
Event (Enishen (OnButton LongClick)) -> do
|
||||||
callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< ()
|
||||||
|
Event (Enishen (OffButton LongClick)) -> do
|
||||||
|
callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
|
||||||
|
callService "Hallway lights off" (light [EntityId "light.hallway_lights"] [] Off) -< ()
|
||||||
Event (Enishen (OffButton _)) -> do
|
Event (Enishen (OffButton _)) -> do
|
||||||
callService (light [AreaId "makuuhuone"] Off) -< ()
|
callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
|
|
||||||
|
|
||||||
@@ -134,22 +155,21 @@ drawer = entityBool "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contac
|
|||||||
>>> arr (fmap (bool Closed Open))
|
>>> arr (fmap (bool Closed Open))
|
||||||
|
|
||||||
bedroomDrawerController :: HASS (Event Value) ()
|
bedroomDrawerController :: HASS (Event Value) ()
|
||||||
bedroomDrawerController = proc x -> do
|
bedroomDrawerController =
|
||||||
st <- drawer >>> traceEvent -< x
|
drawer >>>
|
||||||
case st of
|
(named "Drawer opened" lightOn <> named "Drawer closed" lightOff)
|
||||||
Event Open -> callService (switchService [entity] True) -< ()
|
>>> arr (const ())
|
||||||
Event Closed -> callService (switchService [entity] False) -< ()
|
|
||||||
_ -> returnA -< ()
|
|
||||||
where
|
where
|
||||||
entity = EntityId "switch.bedroom_drawer_light_masse"
|
entity = EntityId "switch.bedroom_drawer_light_masse"
|
||||||
|
lightOff = filterEvent (== Closed)
|
||||||
|
>>|| callService "drawer light off" (switchService [entity] [] False)
|
||||||
|
lightOn = filterEvent (== Open)
|
||||||
|
>>|| callService "drawer light on" (switchService [entity] [] True)
|
||||||
|
|
||||||
door :: HASS (Event Value) (Event DoorState)
|
door :: HASS (Event Value) (Event DoorState)
|
||||||
door = entityBool "binary_sensor.makuuhuone_ovi_contact"
|
door = entityBool "binary_sensor.makuuhuone_ovi_contact"
|
||||||
>>> arr (fmap (bool Closed Open))
|
>>> arr (fmap (bool Closed Open))
|
||||||
|
|
||||||
waitFor :: NominalDiffTime -> HASS a (Event ())
|
|
||||||
waitFor n = duration >>> arr (> n) >>> edge
|
|
||||||
|
|
||||||
|
|
||||||
delayedDoor :: HASS (Event Value) (Event DoorState)
|
delayedDoor :: HASS (Event Value) (Event DoorState)
|
||||||
delayedDoor = door
|
delayedDoor = door
|
||||||
@@ -163,8 +183,8 @@ humidifierController = proc x -> do
|
|||||||
case st of
|
case st of
|
||||||
-- Turn the humidifier on when the door is closed
|
-- Turn the humidifier on when the door is closed
|
||||||
-- the humidifier is low-powered, no point in losing all the humidity
|
-- the humidifier is low-powered, no point in losing all the humidity
|
||||||
Event Open -> callService (humidifier False) -< ()
|
Event Open -> callService "Humidifier off" (humidifier False) -< ()
|
||||||
Event Closed -> callService (humidifier True) -< ()
|
Event Closed -> callService "Humidifier on" (humidifier True) -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
where
|
where
|
||||||
humidifier state = Service
|
humidifier state = Service
|
||||||
@@ -172,4 +192,5 @@ humidifierController = proc x -> do
|
|||||||
, serviceName= bool "turn_off" "turn_on" state
|
, serviceName= bool "turn_off" "turn_on" state
|
||||||
, serviceData= Nothing
|
, serviceData= Nothing
|
||||||
, serviceTarget= [EntityId "humidifier.makuuhuone_ilmankostutin"]
|
, serviceTarget= [EntityId "humidifier.makuuhuone_ilmankostutin"]
|
||||||
|
, serviceExclusions= []
|
||||||
}
|
}
|
||||||
@@ -85,11 +85,13 @@ schoolLightController = lightsOn <> lightsOff
|
|||||||
|
|
||||||
lightsOn :: HASS a ()
|
lightsOn :: HASS a ()
|
||||||
lightsOn = foldMap atTime timersOn
|
lightsOn = foldMap atTime timersOn
|
||||||
>>> AFRP.onEvent (callService (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 :: HASS a ()
|
||||||
lightsOff = foldMap atTime timersOff
|
lightsOff = foldMap atTime timersOff
|
||||||
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] Off))
|
>>> AFRP.onEvent (callService "Lights off" (light [AreaId "lasten_makuuhuone"] [LabelId "decoration"] Off))
|
||||||
|
|
||||||
|
|
||||||
childrenBedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
|
childrenBedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
|
||||||
@@ -99,10 +101,10 @@ childrenBedroomButtonController :: HASS (Event Value) ()
|
|||||||
childrenBedroomButtonController = proc x -> do
|
childrenBedroomButtonController = proc x -> do
|
||||||
ev <- childrenBedroomButton >>> traceEvent -< x
|
ev <- childrenBedroomButton >>> traceEvent -< x
|
||||||
case ev of
|
case ev of
|
||||||
Event (OnButton ShortRelease) -> callService (activateScene "scene.lasten_nukkuvalmistelu") -< ()
|
Event (OnButton ShortRelease) -> callService "scene.lasten_nukkuvalmistelu" (activateScene "scene.lasten_nukkuvalmistelu") -< ()
|
||||||
Event (OnButton DoubleClick) -> callService (activateScene "scene.lasten_luku") -< ()
|
Event (OnButton DoubleClick) -> callService "scene.lasten_luku" (activateScene "scene.lasten_luku") -< ()
|
||||||
Event (OnButton LongClick) -> callService (activateScene "scene.lasten_kirkas") -< ()
|
Event (OnButton LongClick) -> callService "scene.lasten_kirkas" (activateScene "scene.lasten_kirkas") -< ()
|
||||||
Event (OffButton _) -> callService (light [AreaId "lasten_makuuhuone"] Off) -< ()
|
Event (OffButton _) -> callService "Lights off" (light [AreaId "lasten_makuuhuone"] [LabelId "decoration"] Off) -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
|
|
||||||
newtype PM25 = PM25 Float
|
newtype PM25 = PM25 Float
|
||||||
@@ -153,13 +155,14 @@ childrenAirFilterController = proc ev -> do
|
|||||||
humidifier <- humidifierOperatingState >>> AFRP.holdKnown >>> arr join -< ev
|
humidifier <- humidifierOperatingState >>> AFRP.holdKnown >>> arr join -< ev
|
||||||
case level of
|
case level of
|
||||||
Event PM25High ->
|
Event PM25High ->
|
||||||
AFRP.whenA (== Just Idle) (callService (fanOnTo (Percentage 80))) -< humidifier
|
AFRP.whenA (== Just Idle) (callService "Fan strong" (fanOnTo (Percentage 80))) -< humidifier
|
||||||
Event PM25Low -> callService (fanOnTo (Percentage 20)) -< ()
|
Event PM25Low -> callService "Fan low" (fanOnTo (Percentage 20)) -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
where
|
where
|
||||||
fanOnTo percentage = Service
|
fanOnTo percentage = Service
|
||||||
{ serviceDomain = "fan"
|
{ serviceDomain = "fan"
|
||||||
, serviceName = "set_percentage"
|
, serviceName = "set_percentage"
|
||||||
, serviceTarget = [EntityId "fan.children_fan"]
|
, serviceTarget = [EntityId "fan.children_fan"]
|
||||||
|
, serviceExclusions = []
|
||||||
, serviceData = Just $ toJSON percentage
|
, serviceData = Just $ toJSON percentage
|
||||||
}
|
}
|
||||||
@@ -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,5 +1,6 @@
|
|||||||
{-# LANGUAGE Arrows #-}
|
{-# LANGUAGE Arrows #-}
|
||||||
{-# LANGUAGE GADTs #-}
|
{-# LANGUAGE GADTs #-}
|
||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
module HomeAssistant.Controller.Effect
|
module HomeAssistant.Controller.Effect
|
||||||
( HASSEff(..)
|
( HASSEff(..)
|
||||||
@@ -13,9 +14,10 @@ module HomeAssistant.Controller.Effect
|
|||||||
, traceValue
|
, traceValue
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import AFRP (Mealy, eff, Event (..), Request)
|
import AFRP (Mealy, eff, Event (..), Request, named)
|
||||||
import Control.Arrow (returnA)
|
import Control.Arrow (returnA)
|
||||||
import HomeAssistant.Controller.Service (Service)
|
import HomeAssistant.Controller.Service (Service (..))
|
||||||
|
import qualified Data.Text as T
|
||||||
|
|
||||||
data HASSEff a where
|
data HASSEff a where
|
||||||
CallService :: Request -> Service -> HASSEff ()
|
CallService :: Request -> Service -> HASSEff ()
|
||||||
@@ -25,17 +27,20 @@ data HASSEff a where
|
|||||||
|
|
||||||
type HASS a b = Mealy HASSEff a b
|
type HASS a b = Mealy HASSEff a b
|
||||||
|
|
||||||
callService :: Service -> HASS a ()
|
serviceLabel :: T.Text -> HASS a b -> HASS a b
|
||||||
callService service = eff (\req _ -> CallService req service)
|
serviceLabel lbl = named ("Service: " <> lbl)
|
||||||
|
|
||||||
callServices :: [Service] -> HASS a ()
|
callService :: T.Text -> Service -> HASS a ()
|
||||||
callServices service = eff (\req _ -> CallServices req service)
|
callService lbl service = serviceLabel lbl $ eff (\req _ -> CallService req service)
|
||||||
|
|
||||||
callServiceDyn :: (a -> Service) -> HASS a ()
|
callServices :: T.Text -> [Service] -> HASS a ()
|
||||||
callServiceDyn mkService = eff (\req a -> CallService req (mkService a))
|
callServices lbl service = serviceLabel lbl $ eff (\req _ -> CallServices req service)
|
||||||
|
|
||||||
callServicesDyn :: (a -> [Service]) -> HASS a ()
|
callServiceDyn :: T.Text -> (a -> Service) -> HASS a ()
|
||||||
callServicesDyn mkService = eff (\req a -> CallServices req (mkService a))
|
callServiceDyn lbl mkService = serviceLabel lbl $ eff (\req a -> CallService req (mkService a))
|
||||||
|
|
||||||
|
callServicesDyn :: T.Text -> (a -> [Service]) -> HASS a ()
|
||||||
|
callServicesDyn lbl mkService = serviceLabel lbl $ eff (\req a -> CallServices req (mkService a))
|
||||||
|
|
||||||
debug :: Show a => HASS a a
|
debug :: Show a => HASS a a
|
||||||
debug = proc x -> do
|
debug = proc x -> do
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ module HomeAssistant.Controller.Entity
|
|||||||
, entityBool'
|
, entityBool'
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import AFRP (Mealy (..), Event, events, filterA, (>>|), toEvent)
|
import AFRP (Mealy (..), Event, events, filterA, (>>|), toEvent, named)
|
||||||
import Control.Arrow (arr)
|
import Control.Arrow (arr)
|
||||||
import Control.Category ((>>>))
|
import Control.Category ((>>>))
|
||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value)
|
||||||
@@ -19,12 +19,13 @@ import qualified Data.Text as T
|
|||||||
import qualified Data.Set as S
|
import qualified Data.Set as S
|
||||||
import Control.Lens (has, only, (^?), to)
|
import Control.Lens (has, only, (^?), to)
|
||||||
import qualified Data.Text.Lens as TL
|
import qualified Data.Text.Lens as TL
|
||||||
|
import AFRP.Diagram (emptyDiagram)
|
||||||
|
|
||||||
entityChangeEvent :: T.Text -> Mealy eff (Event Value) (Event Value)
|
entityChangeEvent :: T.Text -> Mealy eff (Event Value) (Event Value)
|
||||||
entityChangeEvent entityId = entityChangeEvent' entityId >>> toEvent
|
entityChangeEvent entityId = entityChangeEvent' entityId >>> toEvent
|
||||||
|
|
||||||
entityChangeEvent' :: T.Text -> Mealy eff (Event Value) (Either () Value)
|
entityChangeEvent' :: T.Text -> Mealy eff (Event Value) (Either () Value)
|
||||||
entityChangeEvent' entityId = Mealy (S.singleton entityId) $ runMealy (events >>| filterA isEntity)
|
entityChangeEvent' entityId = named entityId $ Mealy (S.singleton entityId) emptyDiagram $ runMealy (events >>| filterA isEntity)
|
||||||
where
|
where
|
||||||
isEntity :: Value -> Bool
|
isEntity :: Value -> Bool
|
||||||
isEntity = has (key "event" . key "variables" . key "trigger" . key "entity_id" . _String . only entityId)
|
isEntity = has (key "event" . key "variables" . key "trigger" . key "entity_id" . _String . only entityId)
|
||||||
|
|||||||
@@ -1,31 +1,100 @@
|
|||||||
{-# 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 (..), callService)
|
||||||
import HomeAssistant.Controller.Light.Mode (LightingMode (..), lightingModeEvents)
|
import HomeAssistant.Controller.Bedroom (readyForSleep)
|
||||||
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
|
||||||
|
, bedroomReadyForSleep :: Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
mode :: HASS (Event Value) Mode
|
||||||
|
mode = roomState >>> arr sleepMode
|
||||||
|
where
|
||||||
|
sleepMode :: ModeInput -> Mode
|
||||||
|
sleepMode ModeInput{..} = sleep
|
||||||
|
where
|
||||||
|
-- An open parents' bedroom door only leaks into someone's sleep while
|
||||||
|
-- that someone is actually ready to sleep; an open door into an
|
||||||
|
-- empty or awake room does not need the hallway dimmed.
|
||||||
|
bedroomForLeakage = case bedroomDoor of
|
||||||
|
Just Open | not bedroomReadyForSleep -> Just Closed
|
||||||
|
door -> door
|
||||||
|
sleep
|
||||||
|
| Just Closed <- bedroomForLeakage, Just Closed <- childrenBedroomDoor = Regular
|
||||||
|
| roomTimeOfDay > TimeOfDay 20 30 0 || roomTimeOfDay < TimeOfDay 7 30 0 = Quiet
|
||||||
|
| otherwise = Regular
|
||||||
|
roomState = ModeInput <$> timeOfDay <*> masterBedroom <*> childrenBedroom <*> readyForSleep
|
||||||
|
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 (light [EntityId "light.hallway_lights"]) -< On def
|
|
||||||
Event LightingOff -> callServiceDyn (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
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
{-# LANGUAGE Arrows #-}
|
{-# LANGUAGE Arrows #-}
|
||||||
module HomeAssistant.Controller.Kitchen where
|
module HomeAssistant.Controller.Kitchen where
|
||||||
import HomeAssistant.Controller
|
import HomeAssistant.Controller
|
||||||
import AFRP (Event (..))
|
import AFRP (Event (..), (>>||))
|
||||||
import qualified AFRP
|
import qualified AFRP
|
||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value)
|
||||||
import Control.Arrow ((>>>), Arrow (..), returnA)
|
import Control.Arrow ((>>>), Arrow (..), returnA)
|
||||||
@@ -23,8 +23,8 @@ kitchenCeilingController = proc x -> do
|
|||||||
ev <- lightingModeEvents -< p
|
ev <- lightingModeEvents -< p
|
||||||
traceEvent -< ev
|
traceEvent -< ev
|
||||||
case ev of
|
case ev of
|
||||||
Event LightingOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< On def
|
Event LightingOn | lightsAllowed now -> callServiceDyn "light.kitchen_ceiling on" (light [EntityId "light.kitchen_ceiling"] []) -< On def
|
||||||
Event LightingOff -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< Off
|
Event LightingOff -> callServiceDyn "light.kitchen_ceiling off" (light [EntityId "light.kitchen_ceiling"] []) -< Off
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
where
|
where
|
||||||
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
|
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
|
||||||
@@ -36,44 +36,39 @@ dinnerLightLevel = entityRead "sensor.sijainti_keittio_light_level" >>> AFRP.hol
|
|||||||
dinnerPresence :: HASS (Event Value) Presence
|
dinnerPresence :: HASS (Event Value) Presence
|
||||||
dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
|
dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
|
||||||
|
|
||||||
dinnerLightEvents :: HASS (Event Value) (Event LightingMode)
|
|
||||||
dinnerLightEvents =
|
dinnerTableController :: HASS (Event Value) ()
|
||||||
|
dinnerTableController =
|
||||||
((,) <$> dinnerLightLevel <*> dinnerPresence)
|
((,) <$> dinnerLightLevel <*> dinnerPresence)
|
||||||
>>> arr lightWanted
|
>>> arr lightWanted
|
||||||
>>> (sleepEvent &&& offEvent &&& onEvent)
|
-- These are done "in parallel", there is a chance that two services are called in one go
|
||||||
>>> arr (\(s, (o, n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
|
>>> 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
|
where
|
||||||
lightWanted (lightLevel, occ) = occ == Occupied && lightLevel < 13
|
lightWanted (lightLevel, occ) = occ == Occupied && lightLevel < 13
|
||||||
|
|
||||||
onEvent =
|
lightsOn =
|
||||||
AFRP.edge
|
AFRP.edge
|
||||||
>>> arr (fmap (const LightingOn))
|
>>|| sleep "sleep off" False
|
||||||
|
>>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] [] $ On def)
|
||||||
|
|
||||||
sleepEvent =
|
lightsSleep =
|
||||||
arr not
|
arr not
|
||||||
>>> AFRP.edge
|
>>> AFRP.edge
|
||||||
>>> arr (fmap (const LightingSleep))
|
>>|| sleep "sleep on" True
|
||||||
|
|
||||||
offEvent =
|
lightsOff =
|
||||||
arr not
|
arr not
|
||||||
>>> AFRP.waitFor 300
|
>>> AFRP.waitFor 300
|
||||||
>>> arr (fmap (const LightingOff))
|
>>|| sleep "sleep off" False
|
||||||
|
>>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] [] Off)
|
||||||
|
|
||||||
|
|
||||||
|
sleep lbl b = callService lbl (switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] b)
|
||||||
|
|
||||||
dinnerTableController :: HASS (Event Value) ()
|
|
||||||
dinnerTableController = proc x -> do
|
|
||||||
ev <- dinnerLightEvents -< x
|
|
||||||
case ev of
|
|
||||||
Event LightingOn -> do
|
|
||||||
sleep -< False
|
|
||||||
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On def
|
|
||||||
Event LightingOff -> do
|
|
||||||
sleep -< False
|
|
||||||
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< Off
|
|
||||||
Event LightingSleep -> do
|
|
||||||
sleep -< True
|
|
||||||
_ -> returnA -< ()
|
|
||||||
where
|
|
||||||
sleep = callServiceDyn (switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"])
|
|
||||||
|
|
||||||
kitchenMotionController :: HASS (Event Value) ()
|
kitchenMotionController :: HASS (Event Value) ()
|
||||||
kitchenMotionController = kitchenCeilingController <> dinnerTableController
|
kitchenMotionController = kitchenCeilingController <> dinnerTableController
|
||||||
@@ -47,16 +47,19 @@ data LightCommand
|
|||||||
= Off
|
= Off
|
||||||
| On LightAttributes
|
| On LightAttributes
|
||||||
|
|
||||||
light :: [Target] -> LightCommand -> Service
|
light :: [Target] -> [Target] -> LightCommand -> Service
|
||||||
light targets (On settings) = Service
|
light targets exclusions = \case
|
||||||
|
(On settings) -> Service
|
||||||
{ serviceDomain="light"
|
{ serviceDomain="light"
|
||||||
, serviceName= "turn_on"
|
, serviceName= "turn_on"
|
||||||
, serviceData= formatLightAttributes settings
|
, serviceData= formatLightAttributes settings
|
||||||
, serviceTarget=targets
|
, serviceTarget=targets
|
||||||
|
, serviceExclusions = exclusions
|
||||||
}
|
}
|
||||||
light targets Off = Service
|
Off -> Service
|
||||||
{ serviceDomain="light"
|
{ serviceDomain="light"
|
||||||
, serviceName= "turn_off"
|
, serviceName= "turn_off"
|
||||||
, serviceData=Nothing
|
, serviceData=Nothing
|
||||||
, serviceTarget=targets
|
, serviceTarget=targets
|
||||||
|
, serviceExclusions = exclusions
|
||||||
}
|
}
|
||||||
@@ -39,8 +39,8 @@ livingroomPresenceController = proc x -> do
|
|||||||
ev <- lightingModeEvents . livingroomPresence -< x
|
ev <- lightingModeEvents . livingroomPresence -< x
|
||||||
traceEvent -< ev
|
traceEvent -< ev
|
||||||
case ev of
|
case ev of
|
||||||
AFRP.Event LightingOn -> callServiceDyn (light livingroomLightTargets) -< On def
|
AFRP.Event LightingOn -> callServiceDyn "Lights on" (light livingroomLightTargets []) -< On def
|
||||||
AFRP.Event LightingOff -> callServiceDyn (light livingroomLightTargets) -< Off
|
AFRP.Event LightingOff -> callServiceDyn "Lights off" (light livingroomLightTargets []) -< Off
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
returnA -< ()
|
returnA -< ()
|
||||||
|
|
||||||
@@ -88,6 +88,6 @@ livingroomPlantLights = (season &&& tod)
|
|||||||
where
|
where
|
||||||
setLights = proc mode -> do
|
setLights = proc mode -> do
|
||||||
case mode of
|
case mode of
|
||||||
AFRP.Event Growth -> callService (activateScene "scene.olohuoneen_kasvivalo") -< ()
|
AFRP.Event Growth -> callService "scene.olohuoneen_kasvivalo" (activateScene "scene.olohuoneen_kasvivalo") -< ()
|
||||||
AFRP.Event Ambience -> callService (activateScene "scene.kasvivalo_iltatila") -< ()
|
AFRP.Event Ambience -> callService "scene.kasvivalo_iltatila" (activateScene "scene.kasvivalo_iltatila") -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
@@ -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
|
||||||
@@ -18,4 +18,5 @@ activateSceneWith sceneId d = Service
|
|||||||
, serviceName= "turn_on"
|
, serviceName= "turn_on"
|
||||||
, serviceTarget= [EntityId sceneId]
|
, serviceTarget= [EntityId sceneId]
|
||||||
, serviceData = d
|
, serviceData = d
|
||||||
|
, serviceExclusions = []
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,10 @@ module HomeAssistant.Controller.Service
|
|||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value)
|
||||||
import qualified Data.Text as T
|
import qualified Data.Text as T
|
||||||
|
|
||||||
data Target = EntityId !T.Text | AreaId !T.Text
|
data Target
|
||||||
|
= EntityId !T.Text
|
||||||
|
| AreaId !T.Text
|
||||||
|
| LabelId !T.Text
|
||||||
deriving (Show,Eq,Ord)
|
deriving (Show,Eq,Ord)
|
||||||
|
|
||||||
data Service = Service
|
data Service = Service
|
||||||
@@ -14,5 +17,6 @@ data Service = Service
|
|||||||
, serviceName :: T.Text
|
, serviceName :: T.Text
|
||||||
, serviceData :: Maybe Value
|
, serviceData :: Maybe Value
|
||||||
, serviceTarget :: [Target]
|
, serviceTarget :: [Target]
|
||||||
|
, serviceExclusions :: [Target]
|
||||||
}
|
}
|
||||||
deriving (Show, Eq)
|
deriving (Show, Eq)
|
||||||
@@ -5,10 +5,11 @@ module HomeAssistant.Controller.Switch (switchService) where
|
|||||||
import Data.Bool (bool)
|
import Data.Bool (bool)
|
||||||
import HomeAssistant.Controller.Service (Service (..), Target)
|
import HomeAssistant.Controller.Service (Service (..), Target)
|
||||||
|
|
||||||
switchService :: [Target] -> Bool -> Service
|
switchService :: [Target] -> [Target] -> Bool -> Service
|
||||||
switchService targets b = Service
|
switchService targets exclusions b = Service
|
||||||
{ serviceDomain="switch"
|
{ serviceDomain="switch"
|
||||||
, serviceName= bool "turn_off" "turn_on" b
|
, serviceName= bool "turn_off" "turn_on" b
|
||||||
, serviceData=Nothing
|
, serviceData=Nothing
|
||||||
, serviceTarget=targets
|
, serviceTarget=targets
|
||||||
|
, serviceExclusions=exclusions
|
||||||
}
|
}
|
||||||
@@ -42,12 +42,13 @@ 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
|
||||||
import Control.Monad.Catch (MonadCatch)
|
import Control.Monad.Catch (MonadCatch)
|
||||||
import Control.Exception.Annotated (checkpoint, Annotation (..))
|
import Control.Exception.Annotated (checkpoint, Annotation (..))
|
||||||
|
import AFRP.Diagram (renderF)
|
||||||
|
|
||||||
step :: (MonadIO m) => FilePath -> T.Text -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
|
step :: (MonadIO m) => FilePath -> T.Text -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
|
||||||
step path name trace st a = do
|
step path name trace st a = do
|
||||||
@@ -80,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
|
||||||
@@ -122,6 +123,8 @@ defaultMain =
|
|||||||
rrdtool <- fromMaybe "rrdtool" <$> liftIO (lookupEnv "HA_RRDTOOL")
|
rrdtool <- fromMaybe "rrdtool" <$> liftIO (lookupEnv "HA_RRDTOOL")
|
||||||
metricsPort <- lookupPort
|
metricsPort <- lookupPort
|
||||||
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
|
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
|
||||||
|
forM_ controllers $ \(Controller n m) ->
|
||||||
|
logLocM InfoS $ ls $ n <> ": " <> fromMaybe "" (runDiagramC m renderF)
|
||||||
let ents = foldMap (\(Controller _ m) -> entities m) controllers
|
let ents = foldMap (\(Controller _ m) -> entities m) controllers
|
||||||
workers =
|
workers =
|
||||||
[ ("reader", readerAction host 8123 token ents bus),
|
[ ("reader", readerAction host 8123 token ents bus),
|
||||||
|
|||||||
@@ -146,17 +146,21 @@ encodeService callId Service{..} = object $
|
|||||||
, "type" .= ("call_service" :: T.Text)
|
, "type" .= ("call_service" :: T.Text)
|
||||||
, "domain" .= serviceDomain
|
, "domain" .= serviceDomain
|
||||||
, "service" .= serviceName
|
, "service" .= serviceName
|
||||||
, "target" .= targetObject serviceTarget
|
, "target" .= targetObject serviceTarget serviceExclusions
|
||||||
] <> maybe [] (\d -> ["service_data" .= d]) serviceData
|
] <> maybe [] (\d -> ["service_data" .= d]) serviceData
|
||||||
|
|
||||||
|
|
||||||
-- | A single target encodes as a scalar; multiple encode as a list. Empty
|
-- | A single target encodes as a scalar; multiple encode as a list. Empty
|
||||||
-- lists are omitted so Home Assistant receives only populated keys.
|
-- lists are omitted so Home Assistant receives only populated keys. Exclusions
|
||||||
targetObject :: [Target] -> Value
|
-- nest under "exclude".
|
||||||
targetObject targets = object $ entityPart <> areaPart
|
targetObject :: [Target] -> [Target] -> Value
|
||||||
|
targetObject targets exclusions = object $
|
||||||
|
targetKeys targets
|
||||||
|
<> [ "exclude" .= object (targetKeys exclusions) | not (null exclusions) ]
|
||||||
where
|
where
|
||||||
entityPart = emit "entity_id" [e | EntityId e <- targets]
|
targetKeys ts = emit "entity_id" [e | EntityId e <- ts]
|
||||||
areaPart = emit "area_id" [a | AreaId a <- targets]
|
<> emit "area_id" [a | AreaId a <- ts]
|
||||||
|
<> emit "label_id" [l | LabelId l <- ts]
|
||||||
emit _ [] = []
|
emit _ [] = []
|
||||||
emit k [x] = [k .= x]
|
emit k [x] = [k .= x]
|
||||||
emit k many = [k .= many]
|
emit k many = [k .= many]
|
||||||
+3
-2
@@ -20,6 +20,7 @@ import qualified Hedgehog.Range as Range
|
|||||||
import Test.Hspec
|
import Test.Hspec
|
||||||
import Test.Hspec.Hedgehog
|
import Test.Hspec.Hedgehog
|
||||||
import Data.Maybe (listToMaybe)
|
import Data.Maybe (listToMaybe)
|
||||||
|
import AFRP.Diagram (emptyDiagram)
|
||||||
|
|
||||||
fakeRequest :: Request
|
fakeRequest :: Request
|
||||||
fakeRequest = Request (sec 0) utc nil "test"
|
fakeRequest = Request (sec 0) utc nil "test"
|
||||||
@@ -536,11 +537,11 @@ sampleSpec = describe "sample" $ do
|
|||||||
|
|
||||||
-- | A stateless arrow carrying a fixed entity set, for testing propagation.
|
-- | A stateless arrow carrying a fixed entity set, for testing propagation.
|
||||||
subscribed :: S.Set T.Text -> Mealy Identity Int Int
|
subscribed :: S.Set T.Text -> Mealy Identity Int Int
|
||||||
subscribed ents = Mealy ents $ \_ -> Fun $ \_ a -> a
|
subscribed ents = Mealy ents emptyDiagram $ \_ -> Fun $ \_ a -> a
|
||||||
|
|
||||||
-- | Same as 'subscribed' but yields a function, for testing '<*>'.
|
-- | Same as 'subscribed' but yields a function, for testing '<*>'.
|
||||||
subscribedF :: S.Set T.Text -> Mealy Identity Int (Int -> Int)
|
subscribedF :: S.Set T.Text -> Mealy Identity Int (Int -> Int)
|
||||||
subscribedF ents = Mealy ents $ \_ -> Fun $ \_ a -> (a +)
|
subscribedF ents = Mealy ents emptyDiagram $ \_ -> Fun $ \_ a -> (a +)
|
||||||
|
|
||||||
entitiesSpec :: Spec
|
entitiesSpec :: Spec
|
||||||
entitiesSpec = describe "entities" $ do
|
entitiesSpec = describe "entities" $ do
|
||||||
|
|||||||
+110
-8
@@ -5,7 +5,10 @@ module BedroomSpec (spec) where
|
|||||||
import AFRP (Event (..), entities)
|
import AFRP (Event (..), entities)
|
||||||
import qualified Data.Set as S
|
import qualified Data.Set as S
|
||||||
import qualified Data.Text as T
|
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
|
||||||
import HomeAssistant.Controller.Bedroom
|
import HomeAssistant.Controller.Bedroom
|
||||||
import Support
|
import Support
|
||||||
@@ -20,11 +23,31 @@ enishenButton = Event . buttonEvent "event.bedroom_quick_jemina_action"
|
|||||||
drawerState :: T.Text -> Event Value
|
drawerState :: T.Text -> Event Value
|
||||||
drawerState = Event . stateEvent "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contact"
|
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 :: Spec
|
||||||
spec = describe "Bedroom" $ do
|
spec = describe "Bedroom" $ do
|
||||||
entitySpec
|
entitySpec
|
||||||
drawerSpec
|
drawerSpec
|
||||||
buttonSpec
|
buttonSpec
|
||||||
|
presenceSpec
|
||||||
|
|
||||||
entitySpec :: Spec
|
entitySpec :: Spec
|
||||||
entitySpec = describe "entities" $ do
|
entitySpec = describe "entities" $ do
|
||||||
@@ -62,18 +85,18 @@ drawerSpec = describe "bedroomDrawerController" $ do
|
|||||||
|
|
||||||
it "turns the drawer light on when the drawer opens" $
|
it "turns the drawer light on when the drawer opens" $
|
||||||
services (runHASS bedroomDrawerController [drawerState "on"])
|
services (runHASS bedroomDrawerController [drawerState "on"])
|
||||||
`shouldBe` [[switchService [entity] True]]
|
`shouldBe` [[switchService [entity] [] True]]
|
||||||
|
|
||||||
it "turns the drawer light off when the drawer closes" $
|
it "turns the drawer light off when the drawer closes" $
|
||||||
services (runHASS bedroomDrawerController [drawerState "off"])
|
services (runHASS bedroomDrawerController [drawerState "off"])
|
||||||
`shouldBe` [[switchService [entity] False]]
|
`shouldBe` [[switchService [entity] [] False]]
|
||||||
|
|
||||||
it "toggles the light as the drawer opens and closes" $
|
it "toggles the light as the drawer opens and closes" $
|
||||||
services (runHASS bedroomDrawerController
|
services (runHASS bedroomDrawerController
|
||||||
[ drawerState "on", drawerState "off", drawerState "on" ])
|
[ drawerState "on", drawerState "off", drawerState "on" ])
|
||||||
`shouldBe` [ [switchService [entity] True]
|
`shouldBe` [ [switchService [entity] [] True]
|
||||||
, [switchService [entity] False]
|
, [switchService [entity] [] False]
|
||||||
, [switchService [entity] True]
|
, [switchService [entity] [] True]
|
||||||
]
|
]
|
||||||
|
|
||||||
it "ignores state events for other entities" $
|
it "ignores state events for other entities" $
|
||||||
@@ -85,6 +108,73 @@ drawerSpec = describe "bedroomDrawerController" $ do
|
|||||||
services (runHASS bedroomDrawerController [Tick])
|
services (runHASS bedroomDrawerController [Tick])
|
||||||
`shouldBe` [[]]
|
`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 :: Spec
|
||||||
buttonSpec = describe "bedroomButtonController" $ do
|
buttonSpec = describe "bedroomButtonController" $ do
|
||||||
let area = AreaId "makuuhuone"
|
let area = AreaId "makuuhuone"
|
||||||
@@ -103,7 +193,15 @@ buttonSpec = describe "bedroomButtonController" $ do
|
|||||||
|
|
||||||
it "Masse off click turns the bedroom lights off" $
|
it "Masse off click turns the bedroom lights off" $
|
||||||
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
|
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
|
||||||
`shouldContain` [light [area] Off]
|
`shouldContain` [light [area] [] Off]
|
||||||
|
|
||||||
|
it "Masse long off click also turns the hallway lights off" $
|
||||||
|
concat (services (runHASS bedroomButtonController [masseButton "2_long_press"]))
|
||||||
|
`shouldContain` [light [EntityId "light.hallway_lights"] [] Off]
|
||||||
|
|
||||||
|
it "Masse short off click leaves the hallway lights alone" $
|
||||||
|
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
|
||||||
|
`shouldNotContain` [light [EntityId "light.hallway_lights"] [] Off]
|
||||||
|
|
||||||
it "Enishen single click turns on her nightstand scene (lowest)" $
|
it "Enishen single click turns on her nightstand scene (lowest)" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
|
||||||
@@ -119,7 +217,11 @@ buttonSpec = describe "bedroomButtonController" $ do
|
|||||||
|
|
||||||
it "Enishen off click turns the bedroom lights off" $
|
it "Enishen off click turns the bedroom lights off" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
|
||||||
`shouldContain` [light [area] Off]
|
`shouldContain` [light [area] [] Off]
|
||||||
|
|
||||||
|
it "Enishen long off click also turns the hallway lights off" $
|
||||||
|
concat (services (runHASS bedroomButtonController [enishenButton "2_long_press"]))
|
||||||
|
`shouldContain` [light [EntityId "light.hallway_lights"] [] Off]
|
||||||
|
|
||||||
it "ignores the initial press (scene only fires on release)" $
|
it "ignores the initial press (scene only fires on release)" $
|
||||||
services (runHASS bedroomButtonController [masseButton "1_initial_press"])
|
services (runHASS bedroomButtonController [masseButton "1_initial_press"])
|
||||||
|
|||||||
+2
-2
@@ -40,7 +40,7 @@ spec = describe "Bus" $ do
|
|||||||
|
|
||||||
it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do
|
it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do
|
||||||
let req = Request (UTCTime (toEnum 0) 0) utc nil "test"
|
let req = Request (UTCTime (toEnum 0) 0) utc nil "test"
|
||||||
svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"]
|
svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"] []
|
||||||
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
|
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
|
||||||
channelHassEval bus (CallService req svc)
|
channelHassEval bus (CallService req svc)
|
||||||
(_, svc') <- atomically $ readTChan (busOutbound bus)
|
(_, svc') <- atomically $ readTChan (busOutbound bus)
|
||||||
@@ -50,7 +50,7 @@ spec = describe "Bus" $ do
|
|||||||
withTestFlagsBus $ \bus -> do
|
withTestFlagsBus $ \bus -> do
|
||||||
setEnabled (busFlags bus) "test-handler" False
|
setEnabled (busFlags bus) "test-handler" False
|
||||||
let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler"
|
let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler"
|
||||||
svc = Service "light" "turn_on" Nothing [EntityId "light.test"]
|
svc = Service "light" "turn_on" Nothing [EntityId "light.test"] []
|
||||||
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
|
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
|
||||||
channelHassEval bus (CallService req svc)
|
channelHassEval bus (CallService req svc)
|
||||||
result <- timeout 1000000 $ atomically $ readTChan (busOutbound bus)
|
result <- timeout 1000000 $ atomically $ readTChan (busOutbound bus)
|
||||||
|
|||||||
+16
-3
@@ -27,7 +27,7 @@ spec :: Spec
|
|||||||
spec = do
|
spec = do
|
||||||
describe "encodeService" $ do
|
describe "encodeService" $ do
|
||||||
it "encodes a call_service message" $
|
it "encodes a call_service message" $
|
||||||
encodeService 7 (Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"])
|
encodeService 7 (Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"] [])
|
||||||
`shouldBe` object
|
`shouldBe` object
|
||||||
[ "id" .= (7 :: Int)
|
[ "id" .= (7 :: Int)
|
||||||
, "type" .= ("call_service" :: Text)
|
, "type" .= ("call_service" :: Text)
|
||||||
@@ -37,7 +37,7 @@ spec = do
|
|||||||
]
|
]
|
||||||
|
|
||||||
it "includes service_data when present" $
|
it "includes service_data when present" $
|
||||||
encodeService 8 (Service "light" "turn_on" (Just (object ["brightness" .= (200 :: Int)])) [EntityId "light.bedroom_masse"])
|
encodeService 8 (Service "light" "turn_on" (Just (object ["brightness" .= (200 :: Int)])) [EntityId "light.bedroom_masse"] [])
|
||||||
`shouldBe` object
|
`shouldBe` object
|
||||||
[ "id" .= (8 :: Int)
|
[ "id" .= (8 :: Int)
|
||||||
, "type" .= ("call_service" :: Text)
|
, "type" .= ("call_service" :: Text)
|
||||||
@@ -47,6 +47,19 @@ spec = do
|
|||||||
, "service_data" .= object ["brightness" .= (200 :: Int)]
|
, "service_data" .= object ["brightness" .= (200 :: Int)]
|
||||||
]
|
]
|
||||||
|
|
||||||
|
it "encodes target exclusions" $
|
||||||
|
encodeService 9 (Service "light" "turn_off" Nothing [AreaId "lasten_makuuhuone"] [LabelId "decoration"])
|
||||||
|
`shouldBe` object
|
||||||
|
[ "id" .= (9 :: Int)
|
||||||
|
, "type" .= ("call_service" :: Text)
|
||||||
|
, "domain" .= ("light" :: Text)
|
||||||
|
, "service" .= ("turn_off" :: Text)
|
||||||
|
, "target" .= object
|
||||||
|
[ "area_id" .= ("lasten_makuuhuone" :: Text)
|
||||||
|
, "exclude" .= object ["label_id" .= ("decoration" :: Text)]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
describe "isTriggerEvent" $ do
|
describe "isTriggerEvent" $ do
|
||||||
it "is true for event frames" $
|
it "is true for event frames" $
|
||||||
isTriggerEvent (object ["type" .= ("event" :: Text)]) `shouldBe` True
|
isTriggerEvent (object ["type" .= ("event" :: Text)]) `shouldBe` True
|
||||||
@@ -80,5 +93,5 @@ req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
|
|||||||
uuid = "00000000-0000-0000-0000-" <> pad n
|
uuid = "00000000-0000-0000-0000-" <> pad n
|
||||||
|
|
||||||
lightOn :: [Target] -> Service
|
lightOn :: [Target] -> Service
|
||||||
lightOn = Service "light" "turn_on" Nothing
|
lightOn targets = Service "light" "turn_on" Nothing targets []
|
||||||
|
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
|
module HallwaySpec (spec) where
|
||||||
|
|
||||||
|
import AFRP (Event (..))
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import Data.Aeson (Value, object, (.=))
|
||||||
|
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"
|
||||||
|
|
||||||
|
bedroomPresenceSensor :: T.Text -> Event Value
|
||||||
|
bedroomPresenceSensor = Event . stateEvent "binary_sensor.presence_sensor_bedroom_occupancy"
|
||||||
|
|
||||||
|
-- A light turning on with a raw brightness value (0-255)
|
||||||
|
bedroomLightEvent :: T.Text -> Int -> Event Value
|
||||||
|
bedroomLightEvent entityId brightness = Event . object $
|
||||||
|
[ "event" .= object
|
||||||
|
[ "variables" .= object
|
||||||
|
[ "trigger" .= object
|
||||||
|
[ "entity_id" .= (entityId :: T.Text)
|
||||||
|
, "to_state" .= object
|
||||||
|
[ "state" .= ("on" :: T.Text)
|
||||||
|
, "attributes" .= object [ "brightness" .= brightness ]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
-- 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
|
||||||
|
| BedroomPresence Bool -- ^ @True@ is someone in the parents' bedroom
|
||||||
|
| BedroomLight (Maybe Int) -- ^ @Nothing@ is off, otherwise the brightness
|
||||||
|
| 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)
|
||||||
|
,(1, BedroomPresence <$> Gen.bool)
|
||||||
|
,(1, BedroomLight <$> Gen.choice [pure Nothing, pure (Just 25), pure (Just 230)])
|
||||||
|
,(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 (BedroomPresence b) = Event $ stateEvent "binary_sensor.presence_sensor_bedroom_occupancy" (bool "off" "on" b)
|
||||||
|
modeEventValue (BedroomLight b) = case b of
|
||||||
|
Nothing -> Event $ stateEvent "light.bedroom_ceiling" "off"
|
||||||
|
Just n -> bedroomLightEvent "light.bedroom_ceiling" n
|
||||||
|
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 "leaves the lights unchanged when an empty bedroom door opens during sleep hours" $
|
||||||
|
services (runHASSTimed hallwayLightsController
|
||||||
|
[ (night, masterDoor "off") -- closed
|
||||||
|
, (night, childrenDoor "off") -- closed
|
||||||
|
, (night, motionSensor "on")
|
||||||
|
, (night, masterDoor "on") -- opens, but nobody is ready to sleep there
|
||||||
|
])
|
||||||
|
`shouldBe` [ []
|
||||||
|
, []
|
||||||
|
, [light [EntityId "light.hallway_lights"] [] (On def)]
|
||||||
|
, []
|
||||||
|
]
|
||||||
|
|
||||||
|
it "keeps the full lights when an awake bedroom sits behind an open door" $
|
||||||
|
services (runHASSTimed hallwayLightsController
|
||||||
|
[ (night, masterDoor "on") -- open for the cats
|
||||||
|
, (night, childrenDoor "off") -- closed
|
||||||
|
, (night, bedroomPresenceSensor "on")
|
||||||
|
, (night, bedroomLightEvent "light.bedroom_ceiling" 230)
|
||||||
|
, (night, motionSensor "on")
|
||||||
|
])
|
||||||
|
`shouldBe` [ [], [], [], []
|
||||||
|
, [light [EntityId "light.hallway_lights"] [] (On def)]
|
||||||
|
]
|
||||||
|
|
||||||
|
it "protects an open bedroom door as soon as its light is dimmed down" $
|
||||||
|
services (runHASSTimed hallwayLightsController
|
||||||
|
[ (night, masterDoor "on") -- open for the cats
|
||||||
|
, (night, childrenDoor "off") -- closed
|
||||||
|
, (night, bedroomLightEvent "light.bedroom_ceiling" 230) -- still bright
|
||||||
|
, (night, bedroomPresenceSensor "on")
|
||||||
|
, (night, motionSensor "on")
|
||||||
|
, (night, bedroomLightEvent "light.bedroom_ceiling" 25)
|
||||||
|
])
|
||||||
|
`shouldBe` [ [], [], [], []
|
||||||
|
, [light [EntityId "light.hallway_lights"] [] (On def)]
|
||||||
|
, [light [EntityId "light.hallway_ceiling"] [] Off]
|
||||||
|
]
|
||||||
|
|
||||||
|
it "counts a barely lit bedroom as ready to sleep" $
|
||||||
|
services (runHASSTimed hallwayLightsController
|
||||||
|
[ (night, masterDoor "off") -- closed
|
||||||
|
, (night, childrenDoor "off") -- closed
|
||||||
|
, (night, bedroomPresenceSensor "on")
|
||||||
|
, (night, bedroomLightEvent "light.bedroom_ceiling" 25)
|
||||||
|
, (night, motionSensor "on")
|
||||||
|
, (night, masterDoor "on") -- opens for the cats, someone ready to sleep
|
||||||
|
])
|
||||||
|
`shouldBe` [ [], [], [], []
|
||||||
|
, [light [EntityId "light.hallway_lights"] [] (On def)]
|
||||||
|
, [light [EntityId "light.hallway_ceiling"] [] Off]
|
||||||
|
]
|
||||||
|
|
||||||
|
it "dims the lower light when an occupied bedroom door opens during sleep hours" $
|
||||||
|
services (runHASSTimed hallwayLightsController
|
||||||
|
[ (night, masterDoor "off") -- closed
|
||||||
|
, (night, childrenDoor "off") -- closed
|
||||||
|
, (night, bedroomPresenceSensor "on")
|
||||||
|
, (night, motionSensor "on")
|
||||||
|
, (night, masterDoor "on") -- opens for the cats, someone ready to sleep
|
||||||
|
])
|
||||||
|
`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)]
|
||||||
|
]
|
||||||
+12
-5
@@ -11,6 +11,7 @@ import HomeAssistant.Controller.Kitchen
|
|||||||
import Support
|
import Support
|
||||||
import Test.Hspec
|
import Test.Hspec
|
||||||
import Data.Default (def)
|
import Data.Default (def)
|
||||||
|
import Data.Time (getCurrentTime, addUTCTime)
|
||||||
|
|
||||||
-- Helper functions for creating test events
|
-- Helper functions for creating test events
|
||||||
testDinnerLightLevel :: Int -> Event Value
|
testDinnerLightLevel :: Int -> Event Value
|
||||||
@@ -35,12 +36,18 @@ dinnerTableSpec = describe "dinnerTableController" $ do
|
|||||||
|
|
||||||
it "turns lights on when presence is occupied and light level is low" $ do
|
it "turns lights on when presence is occupied and light level is low" $ do
|
||||||
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"])
|
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"])
|
||||||
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] (On def)]]
|
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] True], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] False, light [EntityId "light.kitchen_dining_large"] [] (On def)]]
|
||||||
|
|
||||||
it "turns lights off when presence is unoccupied" $ do
|
it "turns lights to sleep when presence is unoccupied" $ do
|
||||||
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "off"])
|
now <- getCurrentTime
|
||||||
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], []]
|
services (runHASSTimed dinnerTableController [(now, testDinnerLightLevel 10), (now, testDinnerPresence "off")])
|
||||||
|
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] True], []]
|
||||||
|
it "turns lights off when no presence for 300 seconds" $ do
|
||||||
|
now <- getCurrentTime
|
||||||
|
let later = 305 `addUTCTime` now
|
||||||
|
services (runHASSTimed dinnerTableController [(now, testDinnerLightLevel 10), (now, testDinnerPresence "off"), (later, Tick)])
|
||||||
|
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] True], [], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] False, light [EntityId "light.kitchen_dining_large"] [] Off]]
|
||||||
|
|
||||||
it "does nothing on Tick" $ do
|
it "does nothing on Tick" $ do
|
||||||
services (runHASS dinnerTableController [Tick])
|
services (runHASS dinnerTableController [Tick])
|
||||||
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True]]
|
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] True]]
|
||||||
@@ -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