Compare commits
55
Commits
771d702abd
...
servant
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6f785662b | ||
|
|
5d16bf4ade | ||
|
|
05bd609c7e | ||
|
|
9c47bbcb42 | ||
|
|
6063aafe8b | ||
|
|
fafc7111bb | ||
|
|
69cac934ec | ||
|
|
b2a74cbee4 | ||
|
|
769ab43fd2 | ||
|
|
15f3fe7c9e | ||
|
|
416a9484a5 | ||
|
|
e3bc25ce54 | ||
|
|
036473ab81 | ||
|
|
27f271691c | ||
|
|
73d546395b | ||
|
|
a969730de1 | ||
|
|
213f9d5d2a | ||
|
|
2cb8035ef4 | ||
|
|
1ec8c7211f | ||
|
|
3d7f6cb3c6 | ||
|
|
64561718a5 | ||
|
|
7570711768 | ||
|
|
7c2cfde814 | ||
|
|
9fda48f589 | ||
|
|
319104641b | ||
|
|
9861266c1e | ||
|
|
0893862f3a | ||
|
|
6078a64d00 | ||
|
|
7d08acec9d | ||
|
|
2a477b4977 | ||
|
|
09479b5c48 | ||
|
|
a19e5afd5e | ||
|
|
af46776bb0 | ||
|
|
d1bdd2eb67 | ||
|
|
9108ba9c8f | ||
|
|
0f7c6ff98a | ||
|
|
aaba917a9b | ||
|
|
a3dd63f26c | ||
|
|
b20320c779 | ||
|
|
e16010bf2f | ||
|
|
1f786815e6 | ||
|
|
54ef6b5cc3 | ||
|
|
1edb2ac5a2 | ||
|
|
d3518e8ff2 | ||
|
|
e30a28c9ef | ||
|
|
f7849ac889 | ||
|
|
0a4b7dbb01 | ||
|
|
88af6a3139 | ||
|
|
055c02d0f2 | ||
|
|
7b6b529120 | ||
|
|
ef4811f89b | ||
|
|
9fadbae777 | ||
|
|
3f5aa4735c | ||
|
|
6bb96833e1 | ||
|
|
2730657952 |
No files matched your search
@@ -5,3 +5,8 @@ dist-newstyle
|
||||
.worktrees/
|
||||
|
||||
docs/superpowers
|
||||
|
||||
*.hp
|
||||
*.eventlog
|
||||
*.eventlog.html
|
||||
*.rrd
|
||||
+13
-6
@@ -1,6 +1,9 @@
|
||||
{ mkDerivation, aeson, annotated-exception, async, base, bytestring
|
||||
, hedgehog, hspec, hspec-hedgehog, katip, lens, lens-aeson, lib
|
||||
, network, stm, text, time, uuid, websockets
|
||||
, cereal, cereal-conduit, conduit, containers, directory, ekg-core
|
||||
, exceptions, filepath, hedgehog, hspec, hspec-hedgehog, http-types
|
||||
, katip, lens, lens-aeson, lib, network, process, retry, scotty
|
||||
, servant, servant-server, stm, text, time, unliftio
|
||||
, unordered-containers, uuid, wai, warp, websockets
|
||||
}:
|
||||
mkDerivation {
|
||||
pname = "home-assistant-controller";
|
||||
@@ -9,13 +12,17 @@ mkDerivation {
|
||||
isLibrary = true;
|
||||
isExecutable = true;
|
||||
libraryHaskellDepends = [
|
||||
aeson annotated-exception async base bytestring katip lens
|
||||
lens-aeson network stm text time uuid websockets
|
||||
aeson annotated-exception async base bytestring cereal
|
||||
cereal-conduit conduit containers directory ekg-core exceptions
|
||||
filepath http-types katip lens lens-aeson network process retry
|
||||
scotty servant servant-server stm text time unliftio
|
||||
unordered-containers uuid wai warp websockets
|
||||
];
|
||||
executableHaskellDepends = [ base ];
|
||||
testHaskellDepends = [
|
||||
aeson annotated-exception async base hedgehog hspec hspec-hedgehog
|
||||
katip stm text time uuid
|
||||
aeson annotated-exception async base bytestring cereal containers
|
||||
directory ekg-core hedgehog hspec hspec-hedgehog katip process stm
|
||||
text time unordered-containers uuid
|
||||
];
|
||||
license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause";
|
||||
mainProgram = "home-assistant-controller";
|
||||
|
||||
@@ -20,7 +20,15 @@
|
||||
});
|
||||
});
|
||||
in rec {
|
||||
packages.home-assistant-controller = pkgs.haskell.lib.justStaticExecutables hp.home-assistant-controller;
|
||||
packages.home-assistant-controller = pkgs.symlinkJoin {
|
||||
name = "home-assistant-controller";
|
||||
paths = [ (pkgs.haskell.lib.justStaticExecutables hp.home-assistant-controller) ];
|
||||
nativeBuildInputs = [ pkgs.makeWrapper ];
|
||||
postBuild = ''
|
||||
wrapProgram $out/bin/home-assistant-controller \
|
||||
--set HA_RRDTOOL ${pkgs.lib.getBin pkgs.rrdtool}/bin/rrdtool
|
||||
'';
|
||||
};
|
||||
defaultPackage = packages.home-assistant-controller;
|
||||
devShell = hp.shellFor {
|
||||
packages = h: [h.home-assistant-controller];
|
||||
@@ -34,6 +42,8 @@
|
||||
hp.graphmod
|
||||
|
||||
hp.haskell-language-server
|
||||
|
||||
rrdtool
|
||||
];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -62,12 +62,19 @@ library
|
||||
exposed-modules: AFRP
|
||||
, HomeAssistant.Controller
|
||||
, HomeAssistant.Controller.Bedroom
|
||||
, HomeAssistant.Controller.Hallway
|
||||
, HomeAssistant.Controller.Kitchen
|
||||
, HomeAssistant.Controller.Children
|
||||
, HomeAssistant.Controller.Livingroom
|
||||
, HomeAssistant.Controller.Ruuvi
|
||||
, HomeAssistant.Runtime
|
||||
, HomeAssistant.Runtime.Bus
|
||||
, HomeAssistant.Runtime.Connection
|
||||
, HomeAssistant.Runtime.Graphing
|
||||
, HomeAssistant.Runtime.Metrics
|
||||
, HomeAssistant.Runtime.Supervisor
|
||||
, HomeAssistant.Runtime.RateLimit
|
||||
, HttpServer
|
||||
|
||||
-- Modules included in this library but not exported.
|
||||
-- other-modules:
|
||||
@@ -78,10 +85,13 @@ library
|
||||
-- Other library packages from which modules are imported.
|
||||
build-depends: base ^>=4.20.2.0
|
||||
, websockets
|
||||
, http-media
|
||||
, aeson
|
||||
, lens-aeson
|
||||
, lens
|
||||
, exceptions
|
||||
, text
|
||||
, unliftio
|
||||
, network
|
||||
, bytestring
|
||||
, time
|
||||
@@ -90,6 +100,22 @@ library
|
||||
, annotated-exception
|
||||
, uuid
|
||||
, katip
|
||||
, containers
|
||||
, ekg-core
|
||||
, unordered-containers
|
||||
, process
|
||||
, directory
|
||||
, cereal
|
||||
, containers
|
||||
, filepath
|
||||
, conduit
|
||||
, cereal-conduit
|
||||
, servant
|
||||
, servant-server
|
||||
, http-types
|
||||
, warp
|
||||
, wai
|
||||
, retry
|
||||
|
||||
-- Directories containing source files.
|
||||
hs-source-dirs: src
|
||||
@@ -120,7 +146,7 @@ executable home-assistant-controller
|
||||
|
||||
-- Base language which the package is written in.
|
||||
default-language: GHC2024
|
||||
ghc-options: -threaded
|
||||
ghc-options: -threaded -with-rtsopts=-T
|
||||
|
||||
test-suite home-assistant-controller-test
|
||||
-- Import common warning flags.
|
||||
@@ -130,13 +156,14 @@ test-suite home-assistant-controller-test
|
||||
default-language: GHC2024
|
||||
|
||||
-- Modules included in this executable, other than Main.
|
||||
other-modules: AFRPSpec
|
||||
, BackoffProp
|
||||
other-modules: AFRPLawsSpec
|
||||
, AFRPSpec
|
||||
, BedroomSpec
|
||||
, BusSpec
|
||||
, ConnectionSpec
|
||||
, GraphingSpec
|
||||
, MetricsSpec
|
||||
, RuntimeSpec
|
||||
, SupervisorSpec
|
||||
, Support
|
||||
|
||||
-- LANGUAGE extensions used by modules in this package.
|
||||
@@ -155,9 +182,12 @@ test-suite home-assistant-controller-test
|
||||
build-depends:
|
||||
base ^>=4.20.2.0,
|
||||
home-assistant-controller,
|
||||
bytestring,
|
||||
hspec,
|
||||
stm,
|
||||
servant,
|
||||
aeson,
|
||||
cereal,
|
||||
text,
|
||||
async,
|
||||
hedgehog,
|
||||
@@ -165,4 +195,9 @@ test-suite home-assistant-controller-test
|
||||
annotated-exception,
|
||||
time,
|
||||
uuid,
|
||||
katip
|
||||
katip,
|
||||
containers,
|
||||
ekg-core,
|
||||
unordered-containers,
|
||||
process,
|
||||
directory
|
||||
+443
-120
@@ -1,12 +1,16 @@
|
||||
{-# LANGUAGE LambdaCase #-}
|
||||
{-# LANGUAGE Arrows #-}
|
||||
|
||||
module AFRP
|
||||
( Mealy(..)
|
||||
, Auto(..)
|
||||
, DecodedAuto(..)
|
||||
, eff
|
||||
, withEntities
|
||||
, Event(..)
|
||||
, hold
|
||||
, events
|
||||
, switch
|
||||
-- , switch
|
||||
, preMapAccum
|
||||
, preMapAccumRequest
|
||||
, mapAccum
|
||||
@@ -18,8 +22,12 @@ module AFRP
|
||||
, (>>|)
|
||||
, toEvent
|
||||
, lMerge
|
||||
, Pair(..)
|
||||
, Request(..)
|
||||
, SerializeUTCTime(..)
|
||||
, SerializeLocalTime(..)
|
||||
, edge
|
||||
, waitFor
|
||||
, duration
|
||||
, tag
|
||||
, isEvent
|
||||
@@ -27,79 +35,295 @@ module AFRP
|
||||
, sample
|
||||
, rollup
|
||||
, sliding
|
||||
, fixed
|
||||
, debounce
|
||||
, currentTime
|
||||
, onEvent
|
||||
, save
|
||||
, load
|
||||
, stepAuto
|
||||
, stepAutoSerializing
|
||||
) where
|
||||
|
||||
import Control.Category (Category(..), (>>>))
|
||||
import Prelude hiding ((.), id)
|
||||
import Control.Arrow (Arrow(..), ArrowChoice(..), ArrowLoop(..))
|
||||
import Data.Time (UTCTime, NominalDiffTime, diffUTCTime, addUTCTime)
|
||||
import Control.Monad.Fix (MonadFix (mfix))
|
||||
import Control.Arrow (Arrow(..), ArrowChoice(..))
|
||||
import Data.Time (UTCTime (UTCTime), NominalDiffTime, diffUTCTime, addUTCTime, TimeZone, LocalTime (LocalTime), utcToLocalTime, Day (..), diffTimeToPicoseconds, picosecondsToDiffTime, TimeOfDay (TimeOfDay), diffLocalTime)
|
||||
import Data.Either (fromLeft)
|
||||
import Data.Bool (bool)
|
||||
import Data.Monoid (Endo(..))
|
||||
import Data.UUID (UUID)
|
||||
import qualified Data.Set as S
|
||||
import qualified Data.Text as T
|
||||
import Data.Serialize (Get, Putter, Serialize (put), runGet, get)
|
||||
import qualified Data.ByteString as B
|
||||
import Control.Exception (IOException, handle, throwIO)
|
||||
import System.IO.Error (isDoesNotExistError)
|
||||
import GHC.Generics (Generic)
|
||||
import Data.Sequence (Seq, (|>))
|
||||
import qualified Data.Foldable as F
|
||||
import Control.Monad.IO.Class (MonadIO, liftIO)
|
||||
import Conduit (ConduitT, (.|))
|
||||
import qualified Data.Conduit.Cereal as CC
|
||||
import qualified Conduit as C
|
||||
|
||||
|
||||
data Codec s = Codec { getter :: !(Get s), putter :: !(Putter s) }
|
||||
|
||||
data State s = State {state :: !s, dirty :: !Bool}
|
||||
deriving Functor
|
||||
|
||||
|
||||
instance Semigroup s => Semigroup (State s) where
|
||||
s1 <> s2 = State (state s1 <> state s2) (dirty s1 || dirty s2)
|
||||
|
||||
instance Monoid s => Monoid (State s) where
|
||||
mempty = State mempty False
|
||||
|
||||
instance Applicative State where
|
||||
pure a = State a False
|
||||
s1 <*> s2 = State
|
||||
{ state =
|
||||
let a = state s2
|
||||
f = state s1
|
||||
in f a
|
||||
, dirty = dirty s1 || dirty s2
|
||||
}
|
||||
|
||||
mergeState :: State s1 -> State s2 -> State (s1, s2)
|
||||
mergeState s1 s2 = (,) <$> s1 <*> s2
|
||||
|
||||
|
||||
mergeCodec :: Codec s -> Codec s1 -> Codec (s, s1)
|
||||
mergeCodec (Codec agetter aputter) (Codec bgetter bputter) = Codec (mergeGet agetter bgetter) (mergePut aputter bputter)
|
||||
where
|
||||
mergePut :: Putter s -> Putter s1 -> Putter (s, s1)
|
||||
mergePut p1 p2 (s, s1) = p1 s >> p2 s1
|
||||
mergeGet :: Get s -> Get s' -> Get (s, s')
|
||||
mergeGet g1 g2 = (,) <$> g1 <*> g2
|
||||
|
||||
data Pair a b = Pair !a !b
|
||||
|
||||
data Request = Request
|
||||
{ requestTime :: !UTCTime
|
||||
, requestTimeZone :: !TimeZone
|
||||
, requestTraceId :: !UUID
|
||||
}
|
||||
deriving Show
|
||||
} deriving (Show, Eq)
|
||||
|
||||
newtype Mealy eff a b = Mealy
|
||||
{ runMealy :: forall m. MonadFix m => (forall x. eff x -> m x) -> Request -> a -> m (b, Mealy eff a b) }
|
||||
|
||||
data Auto m a b
|
||||
= Fun (Request -> a -> b) -- Stateless variant, needed at least for 'id'
|
||||
| forall s. Stateful !(Codec s) !(State s) !(State s -> Request -> a -> m (b, State s)) -- State is explicitly part of it
|
||||
|
||||
|
||||
instance Monad m => Functor (Auto m a) where
|
||||
fmap f = \case
|
||||
Fun x -> Fun $ \req -> f . x req
|
||||
Stateful codec s x -> Stateful codec s $ \s' req a -> do
|
||||
(a',s'') <- x s' req a
|
||||
pure (f a', s'')
|
||||
|
||||
instance Monad m => Applicative (Auto m a) where
|
||||
pure a = Fun (\_req -> const a)
|
||||
fa <*> fb =
|
||||
case (fa,fb) of
|
||||
(Fun af, Fun bf) -> Fun $ \req -> (af req <*> bf req)
|
||||
(Stateful codec s af, Fun bf) -> Stateful codec s
|
||||
(\s' req x -> do
|
||||
let a = bf req x
|
||||
(h, s'') <- af s' req x
|
||||
pure (h a, s'')
|
||||
)
|
||||
(Fun af, Stateful codec s bf) -> Stateful codec s
|
||||
(\s' req x -> do
|
||||
(a, s'') <- bf s' req x
|
||||
let h = af req x
|
||||
pure (h a, s'')
|
||||
)
|
||||
(Stateful acodec as af, Stateful bcodec bs bf) -> Stateful (mergeCodec acodec bcodec) (mergeState as bs)
|
||||
(\s' req x -> do
|
||||
(a, as') <- bf (snd <$> s') req x
|
||||
(h, bs') <- af (fst <$> s') req x
|
||||
pure (h a, mergeState bs' as')
|
||||
)
|
||||
|
||||
|
||||
instance (Monad m, Semigroup b) => Semigroup (Auto m a b) where
|
||||
fa <> fb =
|
||||
case (fa,fb) of
|
||||
(Fun af, Fun bf) -> Fun (af <> bf)
|
||||
(Stateful codec s af, Fun bf) -> Stateful codec s
|
||||
(\s' req a -> do
|
||||
(ab, s'') <- af s' req a
|
||||
let bb = bf req a
|
||||
pure (ab <> bb, s'')
|
||||
)
|
||||
(Fun af, Stateful codec s bf) -> Stateful codec s
|
||||
(\s' req a -> do
|
||||
let ab = af req a
|
||||
(bb, s'') <- bf s' req a
|
||||
pure (ab <> bb, s'')
|
||||
)
|
||||
(Stateful acodec as af , Stateful bcodec bs bf) -> Stateful (mergeCodec acodec bcodec) (mergeState as bs)
|
||||
(\s req a -> do
|
||||
(ab, as'') <- af (fst <$> s) req a
|
||||
(bb, bs'') <- bf (snd <$> s) req a
|
||||
pure (ab <> bb, mergeState as'' bs'')
|
||||
)
|
||||
|
||||
|
||||
instance (Monad m, Monoid b) => Monoid (Auto m a b) where
|
||||
mempty = Fun $ \_req _ -> mempty
|
||||
|
||||
|
||||
instance Monad m => Category (Auto m) where
|
||||
id = Fun $ \_ -> id
|
||||
af . ag =
|
||||
case (af, ag) of
|
||||
(Fun f, Fun g) -> Fun (\req -> f req . g req)
|
||||
(Stateful codec s f, Fun g) -> Stateful codec s (\s' req -> f s' req . g req)
|
||||
(Fun f, Stateful codec s g) -> Stateful codec s (\s' req -> fmap (first (f req)) . g s' req)
|
||||
(Stateful fcodec fs f , Stateful gcodec gs g) ->
|
||||
Stateful (mergeCodec fcodec gcodec) (mergeState fs gs) (\s req a -> do
|
||||
(b, s') <- g (snd <$> s) req a
|
||||
(c, s'') <- f (fst <$> s) req b
|
||||
pure (c, mergeState s'' s'))
|
||||
|
||||
|
||||
|
||||
instance Monad m => Arrow (Auto m) where
|
||||
arr f = Fun $ const f
|
||||
first = \case
|
||||
Fun f -> Fun $ \req -> first (f req)
|
||||
Stateful codec s f -> Stateful codec s $ \s' req (b,d) -> do
|
||||
(c, s'') <- f s' req b
|
||||
pure ((c,d), s'')
|
||||
|
||||
instance Monad m => ArrowChoice (Auto m) where
|
||||
left = \case
|
||||
Fun f -> Fun $ \req ->
|
||||
\case
|
||||
Left b -> Left $ f req b
|
||||
Right d -> Right d
|
||||
Stateful codec s f -> Stateful codec s $ \s' req -> \case
|
||||
Right d -> pure (Right d, s')
|
||||
Left b -> do
|
||||
(c, s'') <- f s' req b
|
||||
pure (Left c, s'')
|
||||
|
||||
|
||||
serialize :: Monad m => Auto eff a b -> ConduitT i B.ByteString m ()
|
||||
serialize = \case
|
||||
Fun _ -> CC.sourcePut (put ())
|
||||
Stateful Codec{putter} s _ -> CC.sourcePut (putter (state s))
|
||||
|
||||
data DecodedAuto m a b
|
||||
= Decoded (Auto m a b) -- decoded from serialized state
|
||||
| FailDecode String (Auto m a b) -- gives back the original + errmsg
|
||||
|
||||
deserialize :: B.ByteString -> Auto m a b -> DecodedAuto m a b
|
||||
deserialize bs = \case
|
||||
Fun f -> Decoded (Fun f) -- no state to decode, success by default
|
||||
Stateful codec s f ->
|
||||
either
|
||||
(\err -> FailDecode err (Stateful codec s f))
|
||||
(\s' -> Decoded $ Stateful codec (pure s') f)
|
||||
$ runGet (getter codec) bs
|
||||
|
||||
|
||||
save :: FilePath -> Auto m a b -> IO (Auto m a b)
|
||||
save path s
|
||||
| isDirty s = do
|
||||
-- Using conduit machinery as it handles the exception handling for me
|
||||
() <- C.runResourceT $ C.runConduit (serialize s .| C.sinkFileCautious path)
|
||||
pure $ cleanDirty s
|
||||
| otherwise = pure s
|
||||
where
|
||||
cleanDirty :: Auto m a b -> Auto m a b
|
||||
cleanDirty (Stateful codec s' f) = Stateful codec s'{dirty=False} f
|
||||
cleanDirty a = a
|
||||
isDirty :: Auto m a b -> Bool
|
||||
isDirty (Stateful _ s' _) = dirty s'
|
||||
isDirty _ = False
|
||||
|
||||
|
||||
load :: forall m a b. FilePath -> Auto m a b -> IO (DecodedAuto m a b)
|
||||
load path a = handle defaultOnMissingFile (flip deserialize a <$> B.readFile path)
|
||||
where
|
||||
defaultOnMissingFile :: IOException -> IO (DecodedAuto m a b)
|
||||
defaultOnMissingFile e
|
||||
| isDoesNotExistError e = pure $ FailDecode "State doesn't exist yet" a
|
||||
| otherwise = throwIO e
|
||||
|
||||
-- | 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
|
||||
-- trigger subscriptions.
|
||||
data Mealy eff a b = Mealy
|
||||
{ entities :: S.Set T.Text
|
||||
, runMealy :: forall m. Monad m => (forall x. eff x -> m x) -> Auto m a b
|
||||
}
|
||||
|
||||
|
||||
instance Semigroup b => Semigroup (Mealy eff a b) where
|
||||
Mealy ast af <> Mealy bst bf = Mealy (ast <> bst) $ \nt -> af nt <> bf nt
|
||||
|
||||
|
||||
instance Monoid b => Monoid (Mealy eff a b) where
|
||||
mempty = Mealy mempty $ \_nt -> mempty
|
||||
-- where
|
||||
-- m = Mealy mempty $ \_ _ _ -> pure (Pair mempty m)
|
||||
|
||||
eff :: (Request -> a -> eff b) -> Mealy eff a b
|
||||
eff f = Mealy $ \nt req x ->
|
||||
nt (f req x) >>= \b -> pure (b, eff f)
|
||||
eff f = Mealy mempty $ \nt -> do
|
||||
Stateful (Codec get put) (State () False) $ \s req a -> do
|
||||
b <- nt (f req a)
|
||||
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
|
||||
id = Mealy (\_ _ x -> pure (x, id))
|
||||
(Mealy f) . (Mealy g) = Mealy $ \nt t a -> do
|
||||
(b, g') <- g nt t a
|
||||
(c, f') <- f nt t b
|
||||
pure (c, f' . g')
|
||||
id = Mealy mempty (\_ -> id)
|
||||
(Mealy ast f) . (Mealy bst g) = Mealy (ast <> bst) $ \nt -> do
|
||||
f nt . g nt
|
||||
|
||||
instance Arrow (Mealy eff) where
|
||||
arr f = Mealy $ \_ _ b -> pure (f b, arr f)
|
||||
first (Mealy f) = Mealy $ \nt t (b,d) -> do
|
||||
(c, f') <- f nt t b
|
||||
pure ((c, d), first f')
|
||||
arr f = Mealy mempty $ \_nt -> arr f
|
||||
first (Mealy st f) = Mealy st $ \nt -> first (f nt)
|
||||
|
||||
instance ArrowChoice (Mealy eff) where
|
||||
left (Mealy f) = Mealy $ \nt t -> \case
|
||||
Left b -> do
|
||||
(c, f') <- f nt t b
|
||||
pure (Left c, left f')
|
||||
Right d -> pure (Right d, left (Mealy f))
|
||||
left (Mealy st f) = Mealy st $ \nt -> left (f nt)
|
||||
|
||||
instance ArrowLoop (Mealy eff) where
|
||||
loop (Mealy f) = Mealy $ \nt t b -> do
|
||||
((c,_), f') <- mfix $ \((_,d), _) -> f nt t (b,d)
|
||||
pure (c, loop f')
|
||||
|
||||
instance Functor (Mealy eff a) where
|
||||
fmap f (Mealy g) = Mealy $ \nt t a -> do
|
||||
(b, g') <- g nt t a
|
||||
pure (f b, fmap f g')
|
||||
fmap f (Mealy st g) = Mealy st $ \nt -> fmap f (g nt)
|
||||
|
||||
instance Applicative (Mealy eff a) where
|
||||
pure b = Mealy $ \_ _ _ -> pure (b, pure b)
|
||||
Mealy f <*> Mealy x = Mealy $ \nt t a -> do
|
||||
(f', fNext) <- f nt t a
|
||||
(x', xNext) <- x nt t a
|
||||
pure (f' x', fNext <*> xNext)
|
||||
pure b = Mealy mempty $ \_ -> pure b
|
||||
Mealy ast f <*> Mealy bst x = Mealy (ast <> bst) $ \nt ->
|
||||
f nt <*> x nt
|
||||
|
||||
data Event a
|
||||
= Tick
|
||||
| Event a
|
||||
deriving (Show, Eq, Functor, Foldable, Traversable)
|
||||
deriving (Show, Eq, Functor, Foldable, Traversable, Generic)
|
||||
|
||||
instance Serialize a => Serialize (Event a)
|
||||
|
||||
instance Semigroup (Event a) where
|
||||
(<>) = lMerge
|
||||
|
||||
instance Monoid (Event a) where
|
||||
mempty = Tick
|
||||
|
||||
hold :: (Serialize a, Eq a) => a -> Mealy m (Event a) a
|
||||
hold def = mapAccum step def id
|
||||
where
|
||||
step prev = \case
|
||||
Tick -> prev
|
||||
Event new -> new
|
||||
|
||||
hold :: a -> Mealy eff (Event a) a
|
||||
hold a = Mealy $ \_ _ -> \case
|
||||
Tick -> pure (a, hold a)
|
||||
Event a' -> pure (a', hold a')
|
||||
|
||||
events :: Mealy eff (Event a) (Either () a)
|
||||
events = arr $ \case
|
||||
@@ -113,51 +337,89 @@ isEvent _ = True
|
||||
tag :: b -> Event a -> Event b
|
||||
tag b ev = b <$ ev
|
||||
|
||||
switch :: Mealy eff a (b, Event c) -> (c -> Mealy eff a b) -> Mealy eff a b
|
||||
switch (Mealy f) s = Mealy $ \nt t a -> do
|
||||
((b, ev), f') <- f nt t a
|
||||
case ev of
|
||||
Tick -> pure (b, switch f' s)
|
||||
Event x -> runMealy (s x) nt t a
|
||||
-- switch :: Mealy eff a (b, Event c) -> (c -> Mealy eff a b) -> Mealy eff a b
|
||||
-- switch (Mealy st f) s = Mealy st $ \nt t a -> do
|
||||
-- Pair (b, ev) f' <- f nt t a
|
||||
-- case ev of
|
||||
-- Tick -> pure (Pair b (switch f' s))
|
||||
-- Event x -> runMealy (s x) nt t a
|
||||
|
||||
sample :: Mealy eff (a, Event b) (Event a)
|
||||
sample = arr (uncurry tag)
|
||||
|
||||
preMapAccum :: (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
||||
preMapAccum f x extract = go x
|
||||
where
|
||||
go b = Mealy $ \_ _ a ->
|
||||
let next = f b a
|
||||
in pure (extract b, go next)
|
||||
|
||||
preMapAccumRequest :: (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
||||
preMapAccumRequest f x extract = go x
|
||||
preMapAccum' :: forall m x a b. (Monad m, Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Auto m a b
|
||||
preMapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure $ step s a)
|
||||
where
|
||||
go b = Mealy $ \_ t a ->
|
||||
let next = f t b a
|
||||
in pure (extract b, go next)
|
||||
step :: State x -> a -> (b, State x)
|
||||
step s a = let s' = f (state s) a in (extract (state s), State s' (dirty s || state s /= s'))
|
||||
|
||||
mapAccum :: (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
||||
mapAccum f x extract = go x
|
||||
where
|
||||
go b = Mealy $ \_ _ a ->
|
||||
let next = f b a
|
||||
in pure (extract next, go next)
|
||||
|
||||
mapAccumRequest :: (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
|
||||
mapAccumRequest f x extract = go x
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
where
|
||||
go b = Mealy $ \_ t a ->
|
||||
let next = f t b a
|
||||
in pure (extract next, go next)
|
||||
step :: State x -> a -> (b, State x)
|
||||
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 step x extract = Mealy mempty $ \_ -> 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' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
|
||||
where
|
||||
step :: State x -> Request -> a -> (b, State x)
|
||||
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 step x extract = Mealy mempty $ \_ -> 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' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
|
||||
where
|
||||
step :: State x -> Request -> a -> (b, State x)
|
||||
step s req a = let s' = f req (state s) a in (extract s', State s' (dirty s || state s /= s'))
|
||||
|
||||
data DelayState x a = DelayState
|
||||
{ pending :: x
|
||||
, output :: !(Event a)
|
||||
}
|
||||
deriving (Generic, Eq)
|
||||
|
||||
instance (Serialize x, Serialize a) => Serialize (DelayState x a)
|
||||
|
||||
delayEvent :: NominalDiffTime -> Mealy eff (Event a) (Event a)
|
||||
newtype SerializeUTCTime = SerializeUTCTime UTCTime
|
||||
deriving (Eq, Show)
|
||||
|
||||
instance Serialize SerializeUTCTime where
|
||||
put (SerializeUTCTime (UTCTime day time)) = do
|
||||
put (toModifiedJulianDay day)
|
||||
put (diffTimeToPicoseconds time)
|
||||
|
||||
get = do
|
||||
day <- ModifiedJulianDay <$> get
|
||||
time <- picosecondsToDiffTime <$> get
|
||||
pure $ SerializeUTCTime (UTCTime day time)
|
||||
|
||||
newtype SerializeLocalTime = SerializeLocalTime LocalTime
|
||||
deriving (Eq, Show)
|
||||
|
||||
instance Serialize SerializeLocalTime where
|
||||
put (SerializeLocalTime (LocalTime day time)) = do
|
||||
put (toModifiedJulianDay day)
|
||||
let TimeOfDay h m s = time
|
||||
put (h,m, toRational s)
|
||||
get = do
|
||||
day <- ModifiedJulianDay <$> get
|
||||
(h,m,s) <- get
|
||||
pure $ SerializeLocalTime (LocalTime day (TimeOfDay h m (fromRational s)))
|
||||
|
||||
delayEvent :: (Eq a, Serialize a) => NominalDiffTime -> Mealy eff (Event a) (Event a)
|
||||
delayEvent delay =
|
||||
mapAccumRequest step initial output
|
||||
where
|
||||
@@ -169,17 +431,17 @@ delayEvent delay =
|
||||
queued =
|
||||
case input of
|
||||
Tick -> pending st
|
||||
Event x -> pending st ++ [(delay `addUTCTime` now, x)]
|
||||
Event x -> pending st ++ [(SerializeUTCTime $ delay `addUTCTime` now, x)]
|
||||
|
||||
in case queued of
|
||||
(due, x) : rest
|
||||
(SerializeUTCTime due, x) : rest
|
||||
| due <= now ->
|
||||
DelayState rest (Event x)
|
||||
|
||||
_ ->
|
||||
DelayState queued Tick
|
||||
|
||||
debounce :: NominalDiffTime -> Mealy eff (Event a) (Event a)
|
||||
debounce :: (Serialize a, Eq a) => NominalDiffTime -> Mealy eff (Event a) (Event a)
|
||||
debounce delay =
|
||||
mapAccumRequest step initial output
|
||||
where
|
||||
@@ -188,13 +450,13 @@ debounce delay =
|
||||
let now = requestTime req
|
||||
held = case input of
|
||||
Tick -> pending st
|
||||
Event x -> Just (delay `addUTCTime` now, x)
|
||||
Event x -> Just (SerializeUTCTime $ delay `addUTCTime` now, x)
|
||||
in case held of
|
||||
Just (due, x)
|
||||
Just (SerializeUTCTime due, x)
|
||||
| due <= now -> DelayState Nothing (Event x)
|
||||
_ -> DelayState held Tick
|
||||
|
||||
changes :: Eq a => Mealy eff a (Event a)
|
||||
changes :: (Serialize a, Eq a) => Mealy eff a (Event a)
|
||||
changes = mapAccum go Nothing (maybe Tick snd)
|
||||
where
|
||||
go :: Eq a => Maybe (a, Event a) -> a -> Maybe (a, Event a)
|
||||
@@ -227,65 +489,126 @@ lMerge (Event a) _ = Event a
|
||||
lMerge Tick (Event a) = Event a
|
||||
|
||||
edge :: Mealy eff Bool (Event ())
|
||||
edge = go False
|
||||
where
|
||||
go True = Mealy $ \_ _ -> \case
|
||||
True -> pure (Tick, go True)
|
||||
False -> pure (Tick, go False)
|
||||
go False = Mealy $ \_ _ -> \case
|
||||
True -> pure (Event (), go True)
|
||||
False -> pure (Tick, go False)
|
||||
edge =
|
||||
mapAccum
|
||||
(\(_, current) new -> (current, new))
|
||||
(False, False)
|
||||
(\(old, current) ->
|
||||
if not old && current
|
||||
then Event ()
|
||||
else Tick)
|
||||
|
||||
|
||||
|
||||
data WaitingFor
|
||||
= Waiting
|
||||
| Pending { waitingForStart :: SerializeLocalTime, waitingForCurrent :: SerializeLocalTime }
|
||||
deriving (Show, Eq, Generic)
|
||||
|
||||
instance Serialize WaitingFor
|
||||
|
||||
waitFor :: NominalDiffTime -> Mealy eff Bool (Event ())
|
||||
waitFor delta =
|
||||
mapAccumRequest step Waiting extract >>> edge
|
||||
where
|
||||
extract :: WaitingFor -> Bool
|
||||
extract Waiting = False
|
||||
extract Pending{waitingForStart=SerializeLocalTime s, waitingForCurrent=SerializeLocalTime e} =
|
||||
e `diffLocalTime` s >= delta
|
||||
step :: Request -> WaitingFor -> Bool -> WaitingFor
|
||||
step _req _prev False = Waiting
|
||||
step req prev True =
|
||||
let now = SerializeLocalTime $ requestLocalTime req
|
||||
in case prev of
|
||||
Waiting -> Pending now now
|
||||
pending -> pending{waitingForCurrent = now}
|
||||
|
||||
duration :: forall eff a. Mealy eff a NominalDiffTime
|
||||
duration = mapAccumRequest go (Nothing @(UTCTime, NominalDiffTime)) (maybe 0 snd)
|
||||
duration = mapAccumRequest go (Nothing @(SerializeUTCTime, SerializeUTCTime)) (maybe 0 delta)
|
||||
where
|
||||
go :: Request -> Maybe (UTCTime, NominalDiffTime) -> a -> Maybe (UTCTime, NominalDiffTime)
|
||||
go req Nothing _ = Just (requestTime req, requestTime req `diffUTCTime` requestTime req)
|
||||
go req (Just (startTime, _)) _ = Just (startTime, requestTime req `diffUTCTime` startTime)
|
||||
|
||||
delta :: (SerializeUTCTime, SerializeUTCTime) -> NominalDiffTime
|
||||
delta (SerializeUTCTime start, SerializeUTCTime end) = end `diffUTCTime` start
|
||||
go :: Request -> Maybe (SerializeUTCTime, SerializeUTCTime) -> a -> Maybe (SerializeUTCTime, SerializeUTCTime)
|
||||
go req Nothing _ = Just (SerializeUTCTime $ requestTime req, SerializeUTCTime $ requestTime req)
|
||||
go req (Just (startTime, _)) _ = Just (startTime, SerializeUTCTime $ requestTime req)
|
||||
|
||||
|
||||
-- | Rollup, hold back bursty messages
|
||||
--
|
||||
-- Consider a case where you have a bursty set of data. You care to get an immediate response,
|
||||
-- but don't want to spam the output
|
||||
-- but don't want to spam the output.
|
||||
rollup
|
||||
:: Int -- ^ How many items to pass through before burst protection
|
||||
-> Int -- ` How many seconds to collect the bursty data
|
||||
:: (Serialize a, Eq a)
|
||||
=> Int -- ^ How many items to pass through before burst protection
|
||||
-> Int -- ^ How many seconds to collect the bursty data
|
||||
-> Mealy eff (Event a) (Event [a])
|
||||
rollup limit seconds = mapAccumRequest go (Left Tick) (either id (\(_, _, _, ev) -> ev))
|
||||
rollup limit seconds =
|
||||
mapAccumRequest
|
||||
go
|
||||
(Left Tick)
|
||||
(either id (\(_, _, _, ev) -> ev))
|
||||
where
|
||||
e a = Endo ([a] ++)
|
||||
go :: Request -> Either (Event [a]) (UTCTime, Int, Endo [a], Event [a]) -> Event a -> Either (Event [a]) (UTCTime, Int, Endo [a], Event [a])
|
||||
go _ (Left _) Tick = Left Tick
|
||||
go req (Left _) (Event a) = Right (addUTCTime (fromIntegral seconds) (requestTime req), 1, mempty, Event [a])
|
||||
go req (Right (end, n, acc, _)) Tick
|
||||
| requestTime req >= end = Left (Event $ appEndo acc [])
|
||||
| otherwise = Right (end, n, acc, Tick)
|
||||
go req (Right (end, n, acc, _)) (Event a)
|
||||
| requestTime req >= end = Left (Event $ appEndo acc [a])
|
||||
| n < limit = Right (end, n+1, acc, Event [a])
|
||||
| otherwise = Right (end, n+1, acc <> e a, Tick)
|
||||
go
|
||||
:: Request
|
||||
-> Either (Event [a]) (SerializeUTCTime, Int, Seq a, Event [a])
|
||||
-> Event a
|
||||
-> Either (Event [a]) (SerializeUTCTime, Int, Seq a, Event [a])
|
||||
|
||||
go _ (Left _) Tick =
|
||||
Left Tick
|
||||
|
||||
go req (Left _) (Event a) =
|
||||
Right
|
||||
( SerializeUTCTime $ addUTCTime (fromIntegral seconds) (requestTime req)
|
||||
, 1
|
||||
, mempty
|
||||
, Event [a]
|
||||
)
|
||||
|
||||
go req (Right (SerializeUTCTime end, n, acc, _)) Tick
|
||||
| requestTime req >= end =
|
||||
Left (Event $ F.toList acc)
|
||||
| otherwise =
|
||||
Right (SerializeUTCTime end, n, acc, Tick)
|
||||
|
||||
go req (Right (SerializeUTCTime end, n, acc, _)) (Event a)
|
||||
| requestTime req >= end =
|
||||
Left (Event $ F.toList (acc |> a))
|
||||
| n < limit =
|
||||
Right (SerializeUTCTime end, n + 1, acc, Event [a])
|
||||
| otherwise =
|
||||
Right (SerializeUTCTime end, n + 1, acc |> a, Tick)
|
||||
|
||||
|
||||
-- Sliding window into the events
|
||||
sliding :: Int -> Mealy eff (Event a) [a]
|
||||
sliding :: (Serialize a, Eq a) => Int -> Mealy eff (Event a) [a]
|
||||
sliding size = mapAccum go [] id
|
||||
where
|
||||
go :: [a] -> Event a -> [a]
|
||||
go acc Tick = acc
|
||||
go acc (Event a) = let xs = acc ++ [a] in drop (max 0 (length xs - size)) xs
|
||||
|
||||
fixed :: Int -> Mealy eff (Event a) [a]
|
||||
fixed seconds = mapAccumRequest go Nothing (maybe [] ((`appEndo` []) . snd))
|
||||
where
|
||||
e a = Endo ([a] ++)
|
||||
go :: Request -> Maybe (UTCTime, Endo [a]) -> Event a -> Maybe (UTCTime, Endo [a])
|
||||
go req Nothing Tick = Just (addUTCTime (fromIntegral seconds) (requestTime req), mempty)
|
||||
go req Nothing (Event a) = Just (addUTCTime (fromIntegral seconds) (requestTime req), e a)
|
||||
go req (Just (end, acc)) ev =
|
||||
case ev of
|
||||
Tick | requestTime req >= end -> Just (addUTCTime (fromIntegral seconds) end, mempty)
|
||||
| otherwise -> Just (end, acc)
|
||||
Event a | requestTime req >= end -> Just (addUTCTime (fromIntegral seconds) end, e a)
|
||||
| otherwise -> Just (end, acc <> e a)
|
||||
|
||||
requestLocalTime :: Request -> LocalTime
|
||||
requestLocalTime Request{requestTime, requestTimeZone} = utcToLocalTime requestTimeZone requestTime
|
||||
|
||||
currentTime :: Mealy eff a LocalTime
|
||||
currentTime = Mealy mempty $ \_nt -> Fun $ \req _ ->
|
||||
requestLocalTime req
|
||||
|
||||
|
||||
stepAuto :: Monad m => Auto m a b -> Request -> a -> m (b, Auto m a b)
|
||||
stepAuto (Fun f) req a = pure (f req a, Fun f)
|
||||
stepAuto (Stateful codec s f) req a = do
|
||||
(b, s') <- f s req a
|
||||
pure (b, Stateful codec s' f)
|
||||
|
||||
|
||||
stepAutoSerializing :: MonadIO m => FilePath -> Auto m a b -> Request -> a -> m (b, Auto m a b)
|
||||
stepAutoSerializing path f req a = do
|
||||
(b,x) <- stepAuto f req a
|
||||
y <- liftIO $ save path x
|
||||
pure (b,y)
|
||||
|
||||
onEvent :: Mealy eff a () -> Mealy eff (Event a) ()
|
||||
onEvent f = events >>> (arr (const ()) ||| f)
|
||||
+152
-18
@@ -8,6 +8,7 @@ module HomeAssistant.Controller
|
||||
, HASSEff(..)
|
||||
, HASS
|
||||
, callService
|
||||
, callServiceDyn
|
||||
, entityChangeEvent
|
||||
, entityChangeEvent'
|
||||
, entityRead
|
||||
@@ -18,25 +19,39 @@ module HomeAssistant.Controller
|
||||
, light
|
||||
, Presence(..)
|
||||
, presence
|
||||
, motion
|
||||
, motionToPresence
|
||||
, debug
|
||||
, traceEvent
|
||||
, traceValue
|
||||
, switch
|
||||
, Target(..)
|
||||
, brightness
|
||||
, Light(..)
|
||||
, ikeaQuickButton
|
||||
, IkeaButton(..)
|
||||
, IkeaGesture(..)
|
||||
, activateScene
|
||||
, ikeaBoxRemote
|
||||
, IkeaController(..)
|
||||
) where
|
||||
|
||||
import AFRP (Mealy (..), eff, Event(..), events, filterA, (>>|), toEvent, Request)
|
||||
import AFRP (Mealy (..), eff, Event(..), events, filterA, (>>|), toEvent, Request, hold, lMerge, waitFor, tag, edge)
|
||||
import Control.Arrow (Arrow(..), returnA)
|
||||
import Control.Category ((>>>))
|
||||
import Data.Aeson (Value)
|
||||
import Data.Aeson (Value, object, (.=))
|
||||
import qualified Data.Text as T
|
||||
import Control.Lens (has, only, (^?), to)
|
||||
import Data.Aeson.Lens (key, _String)
|
||||
import qualified Data.Set as S
|
||||
import Control.Lens (has, only, (^?), to, traversed)
|
||||
import Data.Aeson.Lens (key, _String, _Integral)
|
||||
import qualified Data.Text.Lens as TL
|
||||
import Data.Bool (bool)
|
||||
import Data.Serialize (Serialize)
|
||||
import GHC.Generics (Generic)
|
||||
import Data.Time (NominalDiffTime)
|
||||
|
||||
data Target = EntityId !T.Text | AreaId !T.Text
|
||||
deriving (Show,Eq)
|
||||
deriving (Show,Eq,Ord)
|
||||
|
||||
data Service = Service
|
||||
{ serviceDomain :: T.Text
|
||||
@@ -56,15 +71,20 @@ type HASS a b = Mealy HASSEff a b
|
||||
callService :: Service -> HASS a ()
|
||||
callService service = eff (\req _ -> CallService req service)
|
||||
|
||||
callServiceDyn :: (a -> Service) -> HASS a ()
|
||||
callServiceDyn mkService = eff (\req a -> CallService req (mkService a))
|
||||
|
||||
debug :: Show a => HASS a a
|
||||
debug = proc x -> do
|
||||
eff (const Debug) -< x
|
||||
returnA -< x
|
||||
|
||||
traceEvent :: Show a => HASS (Event a) (Event a)
|
||||
traceEvent = Mealy $ \nt req -> \case
|
||||
Event a -> nt (Trace req a) >>= \() -> pure (Event a, traceEvent)
|
||||
Tick -> pure (Tick, traceEvent)
|
||||
traceEvent = proc ev -> do
|
||||
case ev of
|
||||
Event a -> eff Trace -< a
|
||||
Tick -> returnA -< ()
|
||||
returnA -< ev
|
||||
|
||||
traceValue :: Show a => HASS a a
|
||||
traceValue = proc x -> do
|
||||
@@ -72,23 +92,61 @@ traceValue = proc x -> do
|
||||
returnA -< x
|
||||
|
||||
data DoorState = Open | Closed
|
||||
deriving (Show, Eq)
|
||||
deriving (Show, Eq, Generic)
|
||||
|
||||
instance Serialize DoorState
|
||||
|
||||
data Presence = Occupied | Unoccupied
|
||||
deriving (Show, Eq)
|
||||
deriving (Show, Eq, Generic)
|
||||
|
||||
instance Serialize Presence
|
||||
|
||||
presence :: T.Text -> HASS (Event Value) (Event Presence)
|
||||
presence entityId =entityBool entityId
|
||||
presence entityId = entityBool entityId
|
||||
>>> arr (fmap (bool Unoccupied Occupied))
|
||||
|
||||
|
||||
data Motion = MotionDetected | MotionNotDetected | MotionUnknown
|
||||
deriving (Show, Eq, Generic)
|
||||
|
||||
|
||||
motion :: T.Text -> HASS (Event Value) Motion
|
||||
motion entityId = entityBool entityId
|
||||
>>> arr (fmap (bool MotionNotDetected MotionDetected))
|
||||
>>> hold MotionUnknown
|
||||
|
||||
|
||||
-- Convert a motion status into a simulated presence
|
||||
--
|
||||
-- A motion tracker detects _motion_, but if you are still, it can't detect you.
|
||||
-- A simple and cheap heuristic is to assume the person is a bit longer there
|
||||
motionToPresence :: NominalDiffTime -> HASS Motion Presence
|
||||
motionToPresence delay = (eventOccupied &&& eventUnoccupied)
|
||||
>>> arr (uncurry lMerge)
|
||||
>>> AFRP.hold Unoccupied
|
||||
where
|
||||
eventOccupied :: HASS Motion (Event Presence)
|
||||
eventOccupied = arr (== MotionDetected) >>> edge >>> arr (fmap (const Occupied))
|
||||
eventUnoccupied :: HASS Motion (Event Presence)
|
||||
eventUnoccupied = arr (== MotionNotDetected) >>> waitFor delay >>> arr (tag Unoccupied)
|
||||
|
||||
instance Serialize Motion
|
||||
|
||||
data Light
|
||||
= Off
|
||||
| On { brightnessPercentage :: Maybe Double }
|
||||
|
||||
-- Turn off lights when door is closed
|
||||
light :: [Target] -> Bool -> Service
|
||||
light targets b = Service
|
||||
light :: [Target] -> Light -> Service
|
||||
light targets (On {brightnessPercentage}) = Service
|
||||
{ serviceDomain="light"
|
||||
, serviceName= bool "turn_off" "turn_on" b
|
||||
, serviceName= "turn_on"
|
||||
, serviceData=fmap (\pct -> object ["brightness_pct" .= pct]) brightnessPercentage
|
||||
, serviceTarget=targets
|
||||
}
|
||||
light targets Off = Service
|
||||
{ serviceDomain="light"
|
||||
, serviceName= "turn_off"
|
||||
, serviceData=Nothing
|
||||
, serviceTarget=targets
|
||||
}
|
||||
@@ -107,20 +165,20 @@ entityChangeEvent :: T.Text -> Mealy eff (Event Value) (Event Value)
|
||||
entityChangeEvent entityId = entityChangeEvent' entityId >>> toEvent
|
||||
|
||||
entityChangeEvent' :: T.Text -> Mealy eff (Event Value) (Either () Value)
|
||||
entityChangeEvent' entityId = events >>| filterA isEntity
|
||||
entityChangeEvent' entityId = Mealy (S.singleton entityId) $ runMealy (events >>| filterA isEntity)
|
||||
where
|
||||
isEntity :: Value -> Bool
|
||||
isEntity = has (key "event" . key "data" . key "entity_id" . _String . only entityId)
|
||||
isEntity = has (key "event" . key "variables" . key "trigger" . key "entity_id" . _String . only entityId)
|
||||
|
||||
entityRead' :: (Read a) => T.Text -> Mealy eff (Event Value) (Either () a)
|
||||
entityRead' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
|
||||
where
|
||||
state v = v ^? key "event" . key "data" . key "new_state" . key "state" . _String . TL.unpacked . to read
|
||||
state v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to read
|
||||
|
||||
entityBool' :: T.Text -> Mealy eff (Event Value) (Either () Bool)
|
||||
entityBool' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
|
||||
where
|
||||
state v = v ^? key "event" . key "data" . key "new_state" . key "state" . _String . TL.unpacked . to toBool
|
||||
state v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to toBool
|
||||
toBool = \case
|
||||
"on" -> True
|
||||
"off" -> False
|
||||
@@ -131,3 +189,79 @@ entityRead entityId = entityRead' entityId >>> toEvent
|
||||
|
||||
entityBool :: T.Text -> Mealy eff (Event Value) (Event Bool)
|
||||
entityBool entityId = entityBool' entityId >>> toEvent
|
||||
|
||||
brightness :: T.Text -> HASS (Event Value) (Event Int)
|
||||
brightness entityId =
|
||||
entityChangeEvent' entityId
|
||||
>>| arr (maybe (Left ()) Right . eventBrightness)
|
||||
>>> AFRP.toEvent
|
||||
where
|
||||
eventBrightness v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "brightness" . _Integral
|
||||
|
||||
data IkeaGesture
|
||||
= ShortClick
|
||||
| ShortRelease
|
||||
| DoubleClick
|
||||
| LongClick
|
||||
deriving Show
|
||||
|
||||
data IkeaButton a = OnButton !a | OffButton !a
|
||||
deriving Show
|
||||
|
||||
|
||||
toIkeaQuickButton :: T.Text -> Maybe (IkeaButton IkeaGesture)
|
||||
toIkeaQuickButton = \case
|
||||
-- 1 is on, 2 is off side of the button
|
||||
"1_initial_press" -> Just $ OnButton ShortClick
|
||||
"1_short_release" -> Just $ OnButton ShortRelease
|
||||
"1_double_press" -> Just $ OnButton DoubleClick
|
||||
"1_long_press" -> Just $ OnButton LongClick
|
||||
"2_initial_press" -> Just $ OffButton ShortClick
|
||||
"2_short_release" -> Just $ OffButton ShortRelease
|
||||
"2_double_press" -> Just $ OffButton DoubleClick
|
||||
"2_long_press" -> Just $ OffButton LongClick
|
||||
_ -> Nothing
|
||||
|
||||
ikeaQuickButton :: T.Text -> HASS (Event Value) (Event (IkeaButton IkeaGesture))
|
||||
ikeaQuickButton entityId =
|
||||
entityChangeEvent' entityId
|
||||
>>| arr (maybe (Left ()) Right . eventType)
|
||||
>>> toEvent
|
||||
where
|
||||
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaQuickButton . traversed
|
||||
|
||||
data IkeaController
|
||||
= ControllerOn -- Short press on
|
||||
| ControllerOff -- Short press off
|
||||
| ControllerBrighnessUp -- Turn brightness up
|
||||
| ControllerBrighnessDown -- Turn brighness down
|
||||
| ControllerArrowRight -- Turn brighness down
|
||||
| ControllerArrowLeft -- Turn brighness down
|
||||
| ControllerBrighnessStop
|
||||
deriving Show
|
||||
|
||||
toIkeaController :: T.Text -> Maybe IkeaController
|
||||
toIkeaController = \case
|
||||
"on" -> Just ControllerOn
|
||||
"off" -> Just ControllerOff
|
||||
"brightness_move_up" -> Just ControllerBrighnessUp
|
||||
"brightness_move_down" -> Just ControllerBrighnessDown
|
||||
"brightness_stop" -> Just ControllerBrighnessStop
|
||||
"arrow_right_click" -> Just ControllerArrowRight
|
||||
"arrow_left_click" -> Just ControllerArrowLeft
|
||||
_ -> Nothing
|
||||
|
||||
ikeaBoxRemote :: T.Text -> HASS (Event Value) (Event IkeaController)
|
||||
ikeaBoxRemote entityId = entityChangeEvent' entityId
|
||||
>>| arr (maybe (Left ()) Right . eventType)
|
||||
>>> toEvent
|
||||
where
|
||||
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaController . traversed
|
||||
|
||||
activateScene :: T.Text -> Service
|
||||
activateScene sceneId = Service
|
||||
{ serviceDomain="scene"
|
||||
, serviceName= "turn_on"
|
||||
, serviceTarget= [EntityId sceneId]
|
||||
, serviceData = Nothing
|
||||
}
|
||||
@@ -4,11 +4,9 @@ module HomeAssistant.Controller.Bedroom where
|
||||
|
||||
import HomeAssistant.Controller
|
||||
import qualified Data.Text as T
|
||||
import AFRP (Event (..), (>>|), toEvent, lMerge, duration, edge)
|
||||
import AFRP (Event (..), lMerge, duration, edge)
|
||||
import Data.Aeson (Value, object, (.=))
|
||||
import Control.Arrow ((>>>), returnA, arr, Arrow (..))
|
||||
import Control.Lens ((^?), to, traversed)
|
||||
import Data.Aeson.Lens (key, _String)
|
||||
import Data.Bool (bool)
|
||||
import Data.Time (NominalDiffTime)
|
||||
import qualified AFRP
|
||||
@@ -29,84 +27,108 @@ createBedroomScene = Service
|
||||
, serviceTarget= []
|
||||
}
|
||||
|
||||
|
||||
activateScene :: T.Text -> Service
|
||||
activateScene sceneId = Service
|
||||
{ serviceDomain="scene"
|
||||
, serviceName= "turn_on"
|
||||
, serviceTarget= [EntityId sceneId]
|
||||
, serviceData = Nothing
|
||||
}
|
||||
data PresenceLights
|
||||
= LightsOn -- Restore lights
|
||||
| LightsOff -- Timer expired, darkness
|
||||
| LightsSleep -- No presence detected, sleep mode
|
||||
deriving Show
|
||||
|
||||
-- Bedroom presence
|
||||
bedroomPresence :: HASS (Event Value) (Event Presence)
|
||||
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
|
||||
|
||||
presenceLightEvents :: HASS (Event Value) (Event PresenceLights)
|
||||
presenceLightEvents =
|
||||
bedroomPresence >>> AFRP.hold Unoccupied
|
||||
>>> arr lightWanted
|
||||
>>> (sleepEvent &&& offEvent &&& onEvent)
|
||||
>>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
|
||||
where
|
||||
lightWanted o = o == Occupied
|
||||
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightsSleep)
|
||||
onEvent = AFRP.edge >>> arr (AFRP.tag LightsOn)
|
||||
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightsOff)
|
||||
|
||||
bedroomPresenceController :: HASS (Event Value) ()
|
||||
bedroomPresenceController = proc x -> do
|
||||
p <- bedroomPresence -< x
|
||||
p <- presenceLightEvents >>> traceEvent -< x
|
||||
case p of
|
||||
Event Unoccupied -> callService createBedroomScene >>> callService (light bedroomLights False) -< ()
|
||||
Event Occupied -> callService (activateScene "makuuhuone_lights_snapshot") -< ()
|
||||
Event LightsOff -> do
|
||||
callService (light bedroomLights Off) -< ()
|
||||
Event LightsOn -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
callService (activateScene "scene.makuuhuone_lights_snapshot") -< ()
|
||||
Event LightsSleep -> do
|
||||
callService createBedroomScene -< ()
|
||||
adaptiveMode -< True
|
||||
sleepMode -< True
|
||||
_ -> returnA -< ()
|
||||
|
||||
data IkeaGesture
|
||||
= ShortClick
|
||||
| ShortRelease
|
||||
| DoubleClick
|
||||
| LongClick
|
||||
deriving Show
|
||||
data IkeaButton a = OnButton !a | OffButton !a
|
||||
deriving Show
|
||||
|
||||
|
||||
toIkeaQuickButton :: T.Text -> Maybe (IkeaButton IkeaGesture)
|
||||
toIkeaQuickButton = \case
|
||||
-- 1 is on, 2 is off side of the button
|
||||
"1_initial_press" -> Just $ OnButton ShortClick
|
||||
"1_short_release" -> Just $ OnButton ShortRelease
|
||||
"1_double_press" -> Just $ OnButton DoubleClick
|
||||
"1_long_press" -> Just $ OnButton LongClick
|
||||
"2_initial_press" -> Just $ OffButton ShortClick
|
||||
"2_short_release" -> Just $ OffButton ShortRelease
|
||||
"2_double_press" -> Just $ OffButton DoubleClick
|
||||
"2_long_press" -> Just $ OffButton LongClick
|
||||
_ -> Nothing
|
||||
|
||||
ikeaQuickButton :: T.Text -> HASS (Event Value) (Event (IkeaButton IkeaGesture))
|
||||
ikeaQuickButton entityId =
|
||||
entityChangeEvent' entityId
|
||||
>>| arr (maybe (Left ()) Right . eventType)
|
||||
>>> toEvent
|
||||
where
|
||||
eventType v = v ^? key "event" . key "data" . key "new_state" . key "attributes" . key "event_type" . _String . to toIkeaQuickButton . traversed
|
||||
sleepMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot_sleep_mode"] )
|
||||
adaptiveMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot"] )
|
||||
|
||||
|
||||
data BedroomControls
|
||||
= Masse (IkeaButton IkeaGesture)
|
||||
| Enishen (IkeaButton IkeaGesture)
|
||||
| Central IkeaController
|
||||
deriving Show
|
||||
|
||||
|
||||
bedroomButton :: HASS (Event Value) (Event BedroomControls)
|
||||
bedroomButton = (masseButton &&& enishenButton) >>> arr (uncurry lMerge)
|
||||
bedroomButton = (masseButton &&& enishenButton &&& centralButton)
|
||||
>>> arr (\(a,(b,c)) -> a `lMerge` b `lMerge` c)
|
||||
where
|
||||
masseButton = fmap Masse <$> ikeaQuickButton "event.bedroom_quick_remote_masse_action"
|
||||
enishenButton = fmap Enishen <$> ikeaQuickButton "event.bedroom_quick_jemina_action"
|
||||
centralButton = fmap Central <$> ikeaBoxRemote "event.bedroom_remote_action"
|
||||
|
||||
bedroomButtonController :: HASS (Event Value) ()
|
||||
bedroomButtonController = proc x -> do
|
||||
ev <- bedroomButton >>> traceEvent -< x
|
||||
-- Any event will cause the sleep mode to be turned off
|
||||
case ev of
|
||||
Event (Masse (OnButton ShortRelease)) -> callService (activateScene "scene.makuuhuone_masse") -< ()
|
||||
Event (Masse (OnButton DoubleClick)) -> callService (activateScene "scene.makuuhuone_keski") -< ()
|
||||
Event (Masse (OnButton LongClick)) -> callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
||||
Event (Masse (OffButton _)) -> callService (light [AreaId "makuuhuone"] False) -< ()
|
||||
Event (Enishen (OnButton ShortRelease)) -> callService (activateScene "scene.makuuhuone_jemina") -< ()
|
||||
Event (Enishen (OnButton DoubleClick)) -> callService (activateScene "scene.makuuhuone_keski") -< ()
|
||||
Event (Enishen (OnButton LongClick)) -> callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
||||
Event (Enishen (OffButton _)) -> callService (light [AreaId "makuuhuone"] False) -< ()
|
||||
Event (Masse (OnButton ShortRelease)) -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
callService (activateScene "scene.makuuhuone_masse") -< ()
|
||||
Event (Masse (OnButton DoubleClick)) -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
callService (activateScene "scene.makuuhuone_keski") -< ()
|
||||
Event (Masse (OnButton LongClick)) -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
||||
Event (Masse (OffButton _)) -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
callService (light [AreaId "makuuhuone"] Off) -< ()
|
||||
Event (Enishen (OnButton ShortRelease)) -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
callService (activateScene "scene.makuuhuone_jemina") -< ()
|
||||
Event (Enishen (OnButton DoubleClick)) -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
callService (activateScene "scene.makuuhuone_keski") -< ()
|
||||
Event (Enishen (OnButton LongClick)) -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
||||
Event (Enishen (OffButton _)) -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
callService (light [AreaId "makuuhuone"] Off) -< ()
|
||||
Event (Central _) -> do
|
||||
sleepMode -< False
|
||||
adaptiveMode -< False
|
||||
_ -> returnA -< ()
|
||||
where
|
||||
sleepMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot_sleep_mode"] )
|
||||
adaptiveMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot"] )
|
||||
|
||||
|
||||
|
||||
@@ -131,12 +153,12 @@ door = entityBool "binary_sensor.makuuhuone_ovi_contact"
|
||||
waitFor :: NominalDiffTime -> HASS a (Event ())
|
||||
waitFor n = duration >>> arr (> n) >>> edge
|
||||
|
||||
|
||||
delayedDoor :: HASS (Event Value) (Event DoorState)
|
||||
delayedDoor = door
|
||||
>>> AFRP.debounce 15
|
||||
>>> AFRP.hold Open
|
||||
>>> AFRP.changes
|
||||
>>> traceEvent
|
||||
|
||||
humidifierController :: HASS (Event Value) ()
|
||||
humidifierController = proc x -> do
|
||||
|
||||
@@ -1,14 +1,96 @@
|
||||
{-# LANGUAGE Arrows #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
module HomeAssistant.Controller.Children where
|
||||
import HomeAssistant.Controller (HASS)
|
||||
import AFRP (Event)
|
||||
import HomeAssistant.Controller (HASS, callService, Target (AreaId), light, Light(..), ikeaQuickButton, IkeaGesture (..), IkeaButton (..), traceEvent, activateScene)
|
||||
import AFRP (Event (..))
|
||||
import qualified AFRP
|
||||
import Control.Arrow (Arrow(..), (>>>), returnA)
|
||||
import Data.Time (Day, TimeOfDay (..), localDay, LocalTime (..))
|
||||
import Data.Time.Calendar.OrdinalDate (WeekOfYear, mondayStartWeek)
|
||||
import Data.Functor.Contravariant (Predicate (..), (>$<))
|
||||
import Data.Aeson (Value)
|
||||
import Control.Arrow (Arrow(..))
|
||||
|
||||
-- Let's see building some reasonable interface for utctime
|
||||
dow :: Day -> (WeekOfYear, Int)
|
||||
dow = mondayStartWeek
|
||||
|
||||
|
||||
weekday :: Predicate Day
|
||||
weekday = Predicate (betweenInclusive 1 5 . snd . dow)
|
||||
where
|
||||
betweenInclusive a b c = c >= a && c <= b
|
||||
|
||||
time :: (Int, Int) -> Predicate TimeOfDay
|
||||
time (h,m) = mconcat
|
||||
[ Predicate (equals h . todHour)
|
||||
, Predicate (equals m . todMin)
|
||||
]
|
||||
where
|
||||
equals a b = a == b
|
||||
|
||||
|
||||
atTime :: Predicate LocalTime -> HASS a (Event ())
|
||||
atTime p = AFRP.currentTime
|
||||
>>> arr (getPredicate p)
|
||||
>>> AFRP.edge
|
||||
|
||||
-- I don't have any proper presence sensors in their bedroom
|
||||
-- and they are notoriously bad at changing clothes in complete darkness
|
||||
-- So I have set up an automation that attempts to turn on the lights sometime
|
||||
-- before they leave for school and turns them off a bit later
|
||||
--
|
||||
-- I don't have enough primitives for this yet, leaving as a placeholder
|
||||
schoolLightController :: HASS (Event Value) ()
|
||||
schoolLightController = arr (const ())
|
||||
|
||||
-- Don't mconcat these predicates they have && behavior
|
||||
-- if you mconcat the actual arrows, they combine the behaviors of the separate branches
|
||||
-- essentially becoming || behavior
|
||||
timersOff :: [Predicate LocalTime]
|
||||
timersOff =
|
||||
[ day 1 <> at (08,15)
|
||||
, day 2 <> at (09,15)
|
||||
, day 3 <> at (08,15)
|
||||
, day 4 <> at (08,15)
|
||||
, day 5 <> at (08,15)
|
||||
, at (18,57) -- debug
|
||||
]
|
||||
where
|
||||
dayOfWeek = snd . mondayStartWeek . localDay
|
||||
at (h,m) = localTimeOfDay >$< Predicate (\TimeOfDay{todHour, todMin} -> todHour == h && todMin == m)
|
||||
day n = dayOfWeek >$< Predicate (== n)
|
||||
|
||||
timersOn :: [Predicate LocalTime]
|
||||
timersOn =
|
||||
[ day 1 <> at (07,30)
|
||||
, day 2 <> at (08,30)
|
||||
, day 3 <> at (07,30)
|
||||
, day 4 <> at (07,30)
|
||||
, day 5 <> at (07,30)
|
||||
]
|
||||
where
|
||||
dayOfWeek = snd . mondayStartWeek . localDay
|
||||
at (h,m) = localTimeOfDay >$< Predicate (\TimeOfDay{todHour, todMin} -> todHour == h && todMin == m)
|
||||
day n = dayOfWeek >$< Predicate (== n)
|
||||
|
||||
schoolLightController :: HASS a ()
|
||||
schoolLightController = lightsOn <> lightsOff
|
||||
|
||||
|
||||
lightsOn :: HASS a ()
|
||||
lightsOn = foldMap atTime timersOn
|
||||
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] On{brightnessPercentage = Just 100}))
|
||||
|
||||
lightsOff :: HASS a ()
|
||||
lightsOff = foldMap atTime timersOff
|
||||
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] Off))
|
||||
|
||||
|
||||
bedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
|
||||
bedroomButton = ikeaQuickButton "event.children_quick_remote_action"
|
||||
|
||||
childrenBedroomButtonController :: HASS (Event Value) ()
|
||||
childrenBedroomButtonController = proc x -> do
|
||||
ev <- bedroomButton >>> traceEvent -< x
|
||||
case ev of
|
||||
Event (OnButton ShortRelease) -> callService (activateScene "scene.lasten_nukkuvalmistelu") -< ()
|
||||
Event (OnButton DoubleClick) -> callService (activateScene "scene.lasten_luku") -< ()
|
||||
Event (OnButton LongClick) -> callService (activateScene "scene.lasten_kirkas") -< ()
|
||||
Event (OffButton _) -> callService (light [AreaId "lasten_makuuhuone"] Off) -< ()
|
||||
_ -> returnA -< ()
|
||||
@@ -0,0 +1,38 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE Arrows #-}
|
||||
module HomeAssistant.Controller.Hallway where
|
||||
|
||||
import HomeAssistant.Controller (Presence (..), HASS, motion, motionToPresence, traceEvent, callServiceDyn, light, Target (..), Light (..))
|
||||
import AFRP (Event (..))
|
||||
import qualified AFRP
|
||||
import Data.Aeson (Value)
|
||||
import Control.Arrow ((>>>), Arrow (..), returnA)
|
||||
import Data.Time (LocalTime(..), TimeOfDay (..))
|
||||
|
||||
|
||||
|
||||
hallwayPresence :: HASS (Event Value) Presence
|
||||
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
|
||||
|
||||
data Lights = LightsOn | LightsOff
|
||||
deriving (Show)
|
||||
|
||||
eventLights :: HASS Presence (Event Lights)
|
||||
eventLights = AFRP.changes >>> arr (fmap presenceLights)
|
||||
where
|
||||
presenceLights Occupied = LightsOn
|
||||
presenceLights Unoccupied = LightsOff
|
||||
|
||||
hallwayLightsController :: HASS (Event Value) ()
|
||||
hallwayLightsController = proc x -> do
|
||||
now <- AFRP.currentTime -< ()
|
||||
p <- hallwayPresence -< x
|
||||
ev <- eventLights -< p
|
||||
traceEvent -< ev
|
||||
case ev of
|
||||
-- The lights entity is a "group of lights" in hass
|
||||
Event LightsOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< On Nothing
|
||||
Event LightsOff -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< Off
|
||||
_ -> returnA -< ()
|
||||
where
|
||||
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
|
||||
@@ -0,0 +1,87 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE Arrows #-}
|
||||
module HomeAssistant.Controller.Kitchen where
|
||||
import HomeAssistant.Controller
|
||||
import AFRP (Event (..))
|
||||
import qualified AFRP
|
||||
import Data.Aeson (Value)
|
||||
import Control.Arrow ((>>>), Arrow (..), returnA)
|
||||
import Prelude hiding (id)
|
||||
import Data.Time (LocalTime(..), TimeOfDay (..))
|
||||
|
||||
|
||||
-- Kitchen has two "presence" sensors. One IKEA motion sensor and one SwitchBot presence sensor
|
||||
|
||||
data Lights = LightsOn | LightsOff | LightsSleep
|
||||
deriving (Show)
|
||||
|
||||
kitchenPresence :: HASS (Event Value) Presence
|
||||
kitchenPresence = motion "binary_sensor.kitchen_movement_occupancy" >>> motionToPresence 500
|
||||
|
||||
eventLights :: HASS Presence (Event Lights)
|
||||
eventLights = AFRP.changes >>> arr (fmap presenceLights)
|
||||
where
|
||||
presenceLights Occupied = LightsOn
|
||||
presenceLights Unoccupied = LightsOff
|
||||
|
||||
kitchenCeilingController :: HASS (Event Value) ()
|
||||
kitchenCeilingController = proc x -> do
|
||||
now <- AFRP.currentTime -< ()
|
||||
p <- kitchenPresence -< x
|
||||
ev <- eventLights -< p
|
||||
traceEvent -< ev
|
||||
case ev of
|
||||
Event LightsOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< On Nothing
|
||||
Event LightsOff -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< Off
|
||||
_ -> returnA -< ()
|
||||
where
|
||||
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
|
||||
|
||||
|
||||
dinnerLightLevel :: HASS (Event Value) Int
|
||||
dinnerLightLevel = entityRead "sensor.sijainti_keittio_light_level" >>> AFRP.hold 0
|
||||
|
||||
dinnerPresence :: HASS (Event Value) Presence
|
||||
dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
|
||||
|
||||
dinnerLightEvents :: HASS (Event Value) (Event Lights)
|
||||
dinnerLightEvents =
|
||||
((,) <$> dinnerLightLevel <*> dinnerPresence)
|
||||
>>> arr lightWanted
|
||||
>>> (sleepEvent &&& offEvent &&& onEvent)
|
||||
>>> arr (\(s, (o, n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
|
||||
where
|
||||
lightWanted (lightLevel, occ) = occ == Occupied && lightLevel < 13
|
||||
|
||||
onEvent =
|
||||
AFRP.edge
|
||||
>>> arr (fmap (const LightsOn))
|
||||
|
||||
sleepEvent =
|
||||
arr not
|
||||
>>> AFRP.edge
|
||||
>>> arr (fmap (const LightsSleep))
|
||||
|
||||
offEvent =
|
||||
arr not
|
||||
>>> AFRP.waitFor 300
|
||||
>>> arr (fmap (const LightsOff))
|
||||
|
||||
dinnerTableController :: HASS (Event Value) ()
|
||||
dinnerTableController = proc x -> do
|
||||
ev <- dinnerLightEvents -< x
|
||||
case ev of
|
||||
Event LightsOn -> do
|
||||
sleep -< False
|
||||
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On Nothing
|
||||
Event LightsOff -> do
|
||||
sleep -< False
|
||||
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< Off
|
||||
Event LightsSleep -> do
|
||||
sleep -< True
|
||||
_ -> returnA -< ()
|
||||
where
|
||||
sleep = callServiceDyn (switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"])
|
||||
|
||||
kitchenMotionController :: HASS (Event Value) ()
|
||||
kitchenMotionController = kitchenCeilingController <> dinnerTableController
|
||||
@@ -0,0 +1,51 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE Arrows #-}
|
||||
module HomeAssistant.Controller.Livingroom where
|
||||
|
||||
import HomeAssistant.Controller (HASS, Presence (..), Target (..), presence, callServiceDyn, light, Light (..), traceEvent)
|
||||
import qualified AFRP
|
||||
import Control.Arrow ((>>>), Arrow (..), returnA)
|
||||
import Data.Aeson (Value)
|
||||
import Prelude hiding ((.))
|
||||
import Control.Category ((.))
|
||||
|
||||
data Lights = LightsOn | LightsOff
|
||||
deriving (Show)
|
||||
|
||||
livingroomPresence :: HASS (AFRP.Event Value) Presence
|
||||
livingroomPresence = presence "binary_sensor.occupancy_olohuone_derived" >>> AFRP.hold Unoccupied
|
||||
|
||||
eventLights :: HASS Presence (AFRP.Event Lights)
|
||||
eventLights = AFRP.changes >>> arr (fmap presenceLights)
|
||||
where
|
||||
presenceLights Occupied = LightsOn
|
||||
presenceLights Unoccupied = LightsOff
|
||||
|
||||
|
||||
-- There's a small race condition / corner case bug in the og implementation
|
||||
-- I have a couple of lights in the Livingroom
|
||||
--
|
||||
-- - Ceiling ilght
|
||||
-- - "Sofa light", a small reading nook light
|
||||
-- - A few strong lights at a plant corner
|
||||
--
|
||||
-- The plant corner lights are not started by the automation. They are started by a separate schedule
|
||||
-- But, they are turned off by the automation
|
||||
-- So their status gets messed if their schedule turns on while there is nobody in the room
|
||||
--
|
||||
--
|
||||
-- With that in mind, I'll be explicitly controlling the two lights, without any scene shenanigans
|
||||
|
||||
|
||||
lights :: [Target]
|
||||
lights = [EntityId "light.livingroom_ceiling", EntityId "light.livingroom_sofa"]
|
||||
|
||||
livingroomPresenceController :: HASS (AFRP.Event Value) ()
|
||||
livingroomPresenceController = proc x -> do
|
||||
ev <- eventLights . livingroomPresence -< x
|
||||
traceEvent -< ev
|
||||
case ev of
|
||||
AFRP.Event LightsOn -> callServiceDyn (light lights) -< On Nothing
|
||||
AFRP.Event LightsOff -> callServiceDyn (light lights) -< Off
|
||||
_ -> returnA -< ()
|
||||
returnA -< ()
|
||||
@@ -13,6 +13,8 @@ import Control.Category ((>>>))
|
||||
import Data.Aeson (Value)
|
||||
import HomeAssistant.Controller (entityRead, traceEvent, HASS)
|
||||
import Control.Arrow (Arrow(..))
|
||||
import GHC.Generics (Generic)
|
||||
import Data.Serialize (Serialize)
|
||||
|
||||
ruuviTemperatures :: Mealy eff (Event Value) Double
|
||||
ruuviTemperatures = entityRead @Double "sensor.ruuvitag_b168_temperature" >>> hold 0
|
||||
@@ -21,7 +23,9 @@ ruuviPressures :: Mealy eff (Event Value) Double
|
||||
ruuviPressures = entityRead "sensor.ruuvitag_b168_pressure" >>> hold 0
|
||||
|
||||
data Ruuvi = Ruuvi { ruuviTemperature :: Double, ruuviPressure :: Double }
|
||||
deriving (Show, Eq)
|
||||
deriving (Show, Eq, Generic)
|
||||
|
||||
instance Serialize Ruuvi
|
||||
|
||||
ruuvi :: Mealy eff (Event Value) (Event Ruuvi)
|
||||
ruuvi = (Ruuvi <$> ruuviTemperatures <*> ruuviPressures) >>> changes
|
||||
|
||||
@@ -13,17 +13,15 @@ module HomeAssistant.Runtime
|
||||
, runController
|
||||
) where
|
||||
|
||||
import AFRP (Event (..), Mealy (..), Request (..))
|
||||
import Control.Concurrent.Async (async, waitAny)
|
||||
import AFRP (Event (..), Mealy (..), Request (..), Auto, stepAutoSerializing, load, DecodedAuto (..))
|
||||
import Control.Concurrent.STM (atomically, dupTChan, readTChan)
|
||||
import Data.Aeson (Value)
|
||||
import qualified Data.Text as T
|
||||
import Data.Time (getCurrentTime)
|
||||
import Data.Void (Void, absurd)
|
||||
import Data.Time (getCurrentTime, getCurrentTimeZone)
|
||||
import Data.Void (Void)
|
||||
import HomeAssistant.Controller (HASS, HASSEff (..))
|
||||
import HomeAssistant.Runtime.Bus
|
||||
import HomeAssistant.Runtime.Connection (readerAction, writerAction)
|
||||
import HomeAssistant.Runtime.Supervisor (defaultBackoff, supervised)
|
||||
import HomeAssistant.Runtime.Connection (writerAction, readerAction)
|
||||
import Network.Socket (withSocketsDo)
|
||||
import System.Environment (getEnv, lookupEnv)
|
||||
import HomeAssistant.Controller.Bedroom (bedroomPresenceController, bedroomButtonController, bedroomDrawerController, humidifierController)
|
||||
@@ -31,53 +29,96 @@ import Data.UUID (UUID, toText)
|
||||
import qualified Data.UUID.V4 as UUID.V4
|
||||
import Katip (runKatipT, logF, sl, Severity (..), ls, Namespace (Namespace), runKatipContextT)
|
||||
import Control.Monad.IO.Class (liftIO, MonadIO)
|
||||
import Control.Monad.Fix (MonadFix)
|
||||
import HomeAssistant.Controller.Ruuvi (ruuviController)
|
||||
import HomeAssistant.Controller.Children (schoolLightController, childrenBedroomButtonController)
|
||||
import Data.Maybe (fromMaybe)
|
||||
import qualified System.Metrics
|
||||
import qualified HomeAssistant.Runtime.Metrics
|
||||
import System.FilePath ((</>))
|
||||
import Text.Read (readMaybe)
|
||||
import HomeAssistant.Controller.Kitchen (kitchenMotionController)
|
||||
import HomeAssistant.Controller.Livingroom (livingroomPresenceController)
|
||||
import HomeAssistant.Runtime.RateLimit (slidingWindowLimiter, registerRateLimitMetrics)
|
||||
import UnliftIO.Async
|
||||
import HomeAssistant.Runtime.Supervisor (supervised)
|
||||
import HomeAssistant.Controller.Hallway (hallwayLightsController)
|
||||
import qualified HttpServer
|
||||
|
||||
step :: (MonadFix m, MonadIO m) => (forall x. eff x -> m x) -> UUID -> Mealy eff a b -> a -> m (b, Mealy eff a b)
|
||||
step nt trace (Mealy f) a = do
|
||||
step :: (MonadIO m) => FilePath -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
|
||||
step path trace st a = do
|
||||
now <- liftIO getCurrentTime
|
||||
f nt (Request now trace) a
|
||||
tz <- liftIO getCurrentTimeZone
|
||||
let req = Request now tz trace
|
||||
stepAutoSerializing path st req a
|
||||
|
||||
data Controller = forall b. Controller T.Text (HASS (Event Value) b) Bool
|
||||
data Controller = forall b. Controller Bool T.Text (HASS (Event Value) b)
|
||||
|
||||
controllers :: [Controller]
|
||||
controllers =
|
||||
[ Controller "bedroom-presence" bedroomPresenceController False
|
||||
, Controller "bedroom-button" bedroomButtonController False -- This works but leaving for vacation
|
||||
, Controller "bedroom-drawer" bedroomDrawerController True
|
||||
, Controller "bedroom-humidifier" humidifierController False
|
||||
, Controller "ruuvi-controller" ruuviController False
|
||||
[ Controller True "bedroom-presence" bedroomPresenceController
|
||||
, Controller True "bedroom-button" bedroomButtonController
|
||||
, Controller True "bedroom-drawer" bedroomDrawerController
|
||||
, Controller True "bedroom-humidifier" humidifierController
|
||||
, Controller True "school-light-controller" schoolLightController
|
||||
, Controller True "kitchen-motion-controller" kitchenMotionController
|
||||
, Controller True "livingroom-presence" livingroomPresenceController
|
||||
, Controller True "hallway-motion-controller" hallwayLightsController
|
||||
, Controller True "children-button" childrenBedroomButtonController
|
||||
]
|
||||
|
||||
-- | Steps the machine for every inbound message; service calls go to the
|
||||
-- bus. A restart re-dups the inbound channel and starts from the machine's
|
||||
-- initial state; messages broadcast during the restart window are lost.
|
||||
runController :: Bus -> Controller -> IO Void
|
||||
runController bus (Controller name machine _enabled) = do
|
||||
runController :: MonadIO m => FilePath -> Bus -> Controller -> m Void
|
||||
runController rootDir bus (Controller _enabled name machine ) = liftIO $ do
|
||||
inbound <- atomically (dupTChan (busInbound bus))
|
||||
go inbound machine
|
||||
let ns = Namespace [name]
|
||||
let workerDefinition = runMealy machine (runKatipContextT (busLogEnv bus) () ns . channelHassEval bus)
|
||||
let path = rootDir </> T.unpack name
|
||||
worker <- load path workerDefinition >>= \case
|
||||
Decoded a -> pure a
|
||||
FailDecode err a -> a <$ putStrLn ("Failed to load (" <> T.unpack name <> "): " <> err)
|
||||
go path inbound worker
|
||||
where
|
||||
go inbound f = do
|
||||
go path inbound f = do
|
||||
msg <- atomically (readTChan inbound)
|
||||
uuid <- UUID.V4.nextRandom
|
||||
let ns = Namespace [name]
|
||||
(_, f') <- step (runKatipContextT (busLogEnv bus) () ns . channelHassEval bus) uuid f (Event msg)
|
||||
go inbound f'
|
||||
(_, next) <- step path uuid f msg
|
||||
go path inbound next
|
||||
|
||||
lookupPort :: IO Int
|
||||
lookupPort = do
|
||||
m <- lookupEnv "HA_METRICS_PORT"
|
||||
case m of
|
||||
Nothing -> pure 8124
|
||||
Just s -> case readMaybe s of
|
||||
Just p | p >= 1 && p <= 65535 -> pure p
|
||||
_ -> fail ("HA_METRICS_PORT must be a port in 1..65535: " <> s)
|
||||
|
||||
defaultMain :: IO ()
|
||||
defaultMain = withSocketsDo $ do
|
||||
severity <- maybe InfoS (const DebugS) <$> lookupEnv "HA_DEBUG"
|
||||
withBus severity $ \bus -> do
|
||||
store <- System.Metrics.newStore
|
||||
System.Metrics.registerGcMetrics store
|
||||
appMetrics <- HomeAssistant.Runtime.Metrics.registerAppMetrics store
|
||||
rateLimitMetrics <- registerRateLimitMetrics store
|
||||
withBus severity appMetrics $ \bus -> do
|
||||
token <- getEnv "HA_TOKEN"
|
||||
host <- getEnv "HA_HOST"
|
||||
let workers =
|
||||
[ ("reader", readerAction host 8123 token bus)
|
||||
, ("writer", writerAction bus)
|
||||
] ++ [ (name, runController bus c) | c@(Controller name _ True) <- controllers ]
|
||||
as <- mapM (\(name, act) -> async (supervised name defaultBackoff act)) workers
|
||||
(_, v) <- waitAny as
|
||||
absurd v
|
||||
rootPath <- fromMaybe "/tmp/" <$> lookupEnv "HA_LIB_DIR"
|
||||
rrdPath <- fromMaybe "hass-controller.rrd" <$> lookupEnv "HA_RRD_PATH"
|
||||
rrdtool <- fromMaybe "rrdtool" <$> lookupEnv "HA_RRDTOOL"
|
||||
metricsPort <- lookupPort
|
||||
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
|
||||
let active = [c | c@(Controller True _ _) <- controllers]
|
||||
ents = foldMap (\(Controller _ _ m) -> entities m) active
|
||||
workers =
|
||||
[ ("reader", readerAction host 8123 token ents bus)
|
||||
, ("writer", writerAction writerLimiter bus)
|
||||
, ("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool)
|
||||
, ("metrics-http", HttpServer.runHttpServer (busLogEnv bus) rrdPath rrdtool metricsPort)
|
||||
] ++ [ (name, runController rootPath bus c) | c@(Controller True name _) <- active ]
|
||||
runKatipContextT (busLogEnv bus) () mempty $
|
||||
mapConcurrently_ (uncurry supervised) workers
|
||||
|
||||
dryRunHassEval :: Namespace -> Bus -> HASSEff a -> IO a
|
||||
dryRunHassEval ns bus = \case
|
||||
|
||||
@@ -6,6 +6,8 @@ module HomeAssistant.Runtime.Bus
|
||||
, CallIdGen(..)
|
||||
, mkCallIdGen
|
||||
, withBus
|
||||
, recordInbound
|
||||
, recordOutbound
|
||||
, channelHassEval
|
||||
) where
|
||||
|
||||
@@ -21,27 +23,30 @@ import Control.Concurrent.STM
|
||||
import Data.Aeson (Value)
|
||||
import Data.IORef (atomicModifyIORef', newIORef)
|
||||
import HomeAssistant.Controller (HASSEff (..), Service)
|
||||
import HomeAssistant.Runtime.Metrics (AppMetrics (..))
|
||||
import Network.WebSockets (Connection)
|
||||
import Katip (LogEnv, closeScribes, mkHandleScribe, ColorStrategy (..), permitItem, Severity (..), Verbosity (V2), registerScribe, defaultScribeSettings, initLogEnv, ls, sl, logFM, katipAddContext, KatipContext)
|
||||
import Control.Exception (bracket)
|
||||
import System.IO (stdout)
|
||||
import System.Metrics.Counter (inc)
|
||||
import Data.UUID (toText)
|
||||
import AFRP (Request(..))
|
||||
import AFRP (Request(..), Event(..))
|
||||
import Control.Monad.IO.Class (MonadIO, liftIO)
|
||||
|
||||
-- | Shared runtime state: inbound is a broadcast channel (controllers
|
||||
-- read from 'dupTChan' copies), outbound queues service calls for the
|
||||
-- writer, conn holds the current websocket (Nothing before first connect).
|
||||
data Bus = Bus
|
||||
{ busInbound :: TChan Value
|
||||
{ busInbound :: TChan (Event Value)
|
||||
, busOutbound :: TChan (Request, Service)
|
||||
, busConn :: TVar (Maybe Connection)
|
||||
, busGen :: CallIdGen
|
||||
, busLogEnv :: LogEnv
|
||||
, busMetrics :: AppMetrics
|
||||
}
|
||||
|
||||
withBus :: Severity -> (Bus -> IO a) -> IO a
|
||||
withBus severity callback = do
|
||||
withBus :: Severity -> AppMetrics -> (Bus -> IO a) -> IO a
|
||||
withBus severity metrics callback = do
|
||||
handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem severity) V2
|
||||
let makeLogEnv = registerScribe "stdout" handleScribe defaultScribeSettings =<< initLogEnv "hass-controller" "production"
|
||||
-- closeScribes will stop accepting new logs, flush existing ones and clean up resources
|
||||
@@ -52,8 +57,15 @@ withBus severity callback = do
|
||||
<*> newTVarIO Nothing
|
||||
<*> mkCallIdGen 0
|
||||
<*> pure le
|
||||
<*> pure metrics
|
||||
callback bus
|
||||
|
||||
recordInbound :: Bus -> IO ()
|
||||
recordInbound bus = inc (amTriggersIn (busMetrics bus))
|
||||
|
||||
recordOutbound :: Bus -> IO ()
|
||||
recordOutbound bus = inc (amServicesOut (busMetrics bus))
|
||||
|
||||
channelHassEval :: (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a
|
||||
channelHassEval bus = \case
|
||||
CallService req svc -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ do
|
||||
|
||||
@@ -5,6 +5,7 @@ module HomeAssistant.Runtime.Connection
|
||||
( readerAction
|
||||
, writerAction
|
||||
, encodeService
|
||||
, isTriggerEvent
|
||||
) where
|
||||
|
||||
import Control.Concurrent.STM
|
||||
@@ -15,31 +16,36 @@ import Control.Concurrent.STM
|
||||
, writeTChan
|
||||
, writeTVar
|
||||
)
|
||||
import Control.Concurrent.Async (race)
|
||||
import Control.Concurrent (threadDelay)
|
||||
import Control.Exception (onException)
|
||||
import Control.Exception.Annotated (throw)
|
||||
import Control.Lens ((^?))
|
||||
import Control.Monad (forever)
|
||||
import Control.Monad (forever, forM_, when)
|
||||
import Data.Aeson (Value, eitherDecode, encode, object, (.=))
|
||||
import Data.Aeson.Lens (key, _String)
|
||||
import qualified Data.ByteString.Lazy as BL
|
||||
import qualified Data.Set as S
|
||||
import qualified Data.Text as T
|
||||
import Data.Void (Void)
|
||||
import HomeAssistant.Controller (Service (..), Target (..))
|
||||
import HomeAssistant.Runtime.Bus
|
||||
import HomeAssistant.Runtime.Supervisor (Fatal (..))
|
||||
import qualified Network.WebSockets as WS
|
||||
import Katip (runKatipContextT, sl, logFM, Severity (..), ls)
|
||||
import Katip (sl, logFM, Severity (..), ls, KatipContext, katipAddNamespace, katipAddContext)
|
||||
import Data.UUID (toText)
|
||||
import AFRP (Request(..))
|
||||
import AFRP (Request(..), Event(..))
|
||||
import Control.Monad.IO.Class (liftIO, MonadIO)
|
||||
import HomeAssistant.Runtime.RateLimit (RateLimited, RateLimiter, runRateLimited)
|
||||
import Control.Monad.Catch (MonadCatch)
|
||||
|
||||
-- | Connect, authenticate, subscribe, then receive and broadcast forever.
|
||||
-- Restarting this action reconnects. All setup sends happen before the
|
||||
-- connection is published in the bus, so only the writer sends afterwards.
|
||||
readerAction :: String -> Int -> String -> Bus -> IO Void
|
||||
readerAction host port token bus =
|
||||
readerAction :: MonadIO m => String -> Int -> String -> S.Set T.Text -> Bus -> m Void
|
||||
readerAction host port token ents bus = liftIO $
|
||||
WS.runClient host port "/api/websocket" $ \conn -> do
|
||||
handshake conn token
|
||||
subscribe bus conn
|
||||
subscribe bus conn ents
|
||||
atomically $ writeTVar (busConn bus) (Just conn)
|
||||
putStrLn "[reader] connected"
|
||||
-- Unpublish on exit so the writer blocks and the backlog survives the outage.
|
||||
@@ -62,23 +68,39 @@ expectType expected msg =
|
||||
Just t | t == expected -> pure ()
|
||||
_ -> throw (Fatal $ "expected " <> expected <> ", got: " <> T.pack (show msg))
|
||||
|
||||
subscribe :: Bus -> WS.Connection -> IO ()
|
||||
subscribe bus conn = do
|
||||
isTriggerEvent :: Value -> Bool
|
||||
isTriggerEvent v = v ^? key "type" . _String == Just "event"
|
||||
|
||||
subscribe :: Bus -> WS.Connection -> S.Set T.Text -> IO ()
|
||||
subscribe bus conn ents =
|
||||
forM_ (S.toList ents) $ \entityId -> do
|
||||
print entityId
|
||||
sid <- generateCallId (busGen bus)
|
||||
WS.sendTextData conn $ encode $ object
|
||||
[ "id" .= sid
|
||||
, "type" .= ("subscribe_events" :: T.Text)
|
||||
, "event_type" .= ("state_changed" :: T.Text)
|
||||
, "type" .= ("subscribe_trigger" :: T.Text)
|
||||
, "trigger" .= object
|
||||
[ "platform" .= ("state" :: T.Text)
|
||||
, "entity_id" .= entityId
|
||||
]
|
||||
]
|
||||
|
||||
-- | Undecodable messages are skipped: reconnecting cannot fix a decode
|
||||
-- problem, so crashing here would only produce a hot restart loop.
|
||||
--
|
||||
-- Each read races a one-second timeout: a timeout broadcasts 'Tick' so
|
||||
-- time-based primitives (debounce, rollup, fixed, ...) keep advancing
|
||||
-- even when no state changes arrive.
|
||||
receiveLoop :: Bus -> WS.Connection -> IO Void
|
||||
receiveLoop bus conn = forever $ do
|
||||
msg <- WS.receiveData conn :: IO BL.ByteString
|
||||
case eitherDecode msg of
|
||||
winner <- race (threadDelay 1_000_000) (WS.receiveData conn)
|
||||
case winner of
|
||||
Left () -> atomically $ writeTChan (busInbound bus) Tick
|
||||
Right msg -> case eitherDecode msg of
|
||||
Left err -> putStrLn $ "[reader] skipping undecodable message: " <> err
|
||||
Right v -> atomically $ writeTChan (busInbound bus) v
|
||||
Right v -> do
|
||||
when (isTriggerEvent v) (recordInbound bus)
|
||||
atomically $ writeTChan (busInbound bus) (Event v)
|
||||
|
||||
receiveJSON :: WS.Connection -> IO Value
|
||||
receiveJSON conn = do
|
||||
@@ -87,15 +109,23 @@ receiveJSON conn = do
|
||||
Left err -> throw (Fatal $ "Invalid JSON from Home Assistant: " <> T.pack err)
|
||||
Right x -> pure x
|
||||
|
||||
writerAction :: Bus -> IO Void
|
||||
writerAction bus = forever $ do
|
||||
(request, svc) <- atomically $ readTChan (busOutbound bus)
|
||||
conn <- atomically $ readTVar (busConn bus) >>= maybe retry pure
|
||||
callId <- generateCallId (busGen bus)
|
||||
|
||||
|
||||
sendWithId :: (MonadIO m, KatipContext m) => Bus -> WS.Connection -> Service -> RateLimited m ()
|
||||
sendWithId bus conn svc = katipAddNamespace "connection" $ do
|
||||
callId <- liftIO $ generateCallId (busGen bus)
|
||||
let textData = encode $ encodeService callId svc
|
||||
runKatipContextT (busLogEnv bus) (sl "traceId" (toText (requestTraceId request))) "connection" $
|
||||
logFM DebugS (ls textData)
|
||||
WS.sendTextData conn textData
|
||||
liftIO $ recordOutbound bus
|
||||
liftIO $ WS.sendTextData conn textData
|
||||
|
||||
writerAction :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> Bus -> m Void
|
||||
writerAction rateLimiter bus = forever $ do
|
||||
(request, svc) <- liftIO $ atomically $ readTChan (busOutbound bus)
|
||||
katipAddContext (sl "traceId" (toText (requestTraceId request))) $ do
|
||||
conn <- liftIO $ atomically $ readTVar (busConn bus) >>= maybe retry pure
|
||||
-- runRateLimited rateLimiter $ sendWithId bus conn request svc
|
||||
runRateLimited rateLimiter $ sendWithId bus conn svc
|
||||
|
||||
encodeService :: Int -> Service -> Value
|
||||
encodeService callId Service{..} = object $
|
||||
@@ -106,6 +136,7 @@ encodeService callId Service{..} = object $
|
||||
, "target" .= targetObject serviceTarget
|
||||
] <> maybe [] (\d -> ["service_data" .= d]) serviceData
|
||||
|
||||
|
||||
-- | A single target encodes as a scalar; multiple encode as a list. Empty
|
||||
-- lists are omitted so Home Assistant receives only populated keys.
|
||||
targetObject :: [Target] -> Value
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module HomeAssistant.Runtime.Graphing
|
||||
( Range (..)
|
||||
, parseRange
|
||||
, rangeStart
|
||||
, Series (..)
|
||||
, GraphSpec (..)
|
||||
, graphs
|
||||
, lookupGraph
|
||||
, parseNameParam
|
||||
, buildGraphArgs
|
||||
, readProcessBytes
|
||||
, Graph(..)
|
||||
, renderGraph
|
||||
) where
|
||||
|
||||
import Control.Exception (evaluate)
|
||||
import Control.Monad.IO.Class (liftIO, MonadIO)
|
||||
import qualified Data.ByteString as BS
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import System.Exit (ExitCode (..))
|
||||
import System.IO (hGetContents)
|
||||
import System.Process (CreateProcess (..), StdStream (..), proc, waitForProcess, withCreateProcess)
|
||||
import Servant.API (FromHttpApiData (..), ToHttpApiData (..))
|
||||
|
||||
data Range = TenMinutes | OneHour | OneDay | OneWeek | OneMonth
|
||||
deriving (Eq, Show, Bounded, Enum)
|
||||
|
||||
rangeSuffix :: Range -> String
|
||||
rangeSuffix TenMinutes = "10m"
|
||||
rangeSuffix OneHour = "1h"
|
||||
rangeSuffix OneDay = "24h"
|
||||
rangeSuffix OneWeek = "7d"
|
||||
rangeSuffix OneMonth = "30d"
|
||||
|
||||
parseRange :: Text -> Maybe Range
|
||||
parseRange t = lookup t [(T.pack (rangeSuffix r), r) | r <- [minBound .. maxBound]]
|
||||
|
||||
instance ToHttpApiData Range where
|
||||
toQueryParam = T.pack . rangeSuffix
|
||||
|
||||
instance FromHttpApiData Range where
|
||||
parseQueryParam x = maybe (Left ("Could not parse '" <> x <> "' as Range")) Right $ parseRange x
|
||||
|
||||
rangeStart :: Range -> String
|
||||
rangeStart r = "end-" ++ rangeSuffix r
|
||||
|
||||
data CF = Average | Minimum | Maximum | Last
|
||||
deriving (Eq, Show)
|
||||
|
||||
data Source = Source
|
||||
{ srcDs :: String
|
||||
, srcCF :: CF
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
data Transform
|
||||
= Identity
|
||||
| Multiply Double
|
||||
deriving (Eq, Show)
|
||||
|
||||
data Series = Series
|
||||
{ serSource :: Source
|
||||
, serTransform :: Transform
|
||||
, serAlias :: String
|
||||
, serColor :: String
|
||||
, serLabel :: String
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
data Plot
|
||||
= Line Int Series
|
||||
| Area Series
|
||||
deriving (Eq, Show)
|
||||
|
||||
data GraphSpec = GraphSpec
|
||||
{ gsName :: Text
|
||||
, gsTitle :: String
|
||||
, gsPlots :: [Plot]
|
||||
, gsIdentifier :: Graph
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
average :: String -> Source
|
||||
average ds = Source ds Average
|
||||
|
||||
maximumCF :: String -> Source
|
||||
maximumCF ds = Source ds Maximum
|
||||
|
||||
line :: String -> String -> Source -> Plot
|
||||
line alias color source =
|
||||
Line 2 Series
|
||||
{ serSource = source
|
||||
, serTransform = Identity
|
||||
, serAlias = alias
|
||||
, serColor = color
|
||||
, serLabel = alias
|
||||
}
|
||||
|
||||
area :: String -> String -> Source -> Plot
|
||||
area alias color source =
|
||||
Area Series
|
||||
{ serSource = source
|
||||
, serTransform = Identity
|
||||
, serAlias = alias
|
||||
, serColor = color
|
||||
, serLabel = alias
|
||||
}
|
||||
|
||||
ratelimitGraph :: GraphSpec
|
||||
ratelimitGraph =
|
||||
GraphSpec
|
||||
{ gsName = "ratelimit"
|
||||
, gsTitle = "Rate limiting"
|
||||
, gsPlots =
|
||||
[ Line 2 Series
|
||||
{ serSource = Source "ratelimit_retry" Average
|
||||
, serTransform = Multiply 60
|
||||
, serAlias = "retry"
|
||||
, serColor = "#0066cc"
|
||||
, serLabel = "Requests retried/min"
|
||||
}
|
||||
, Line 2 Series
|
||||
{ serSource = Source "ratelimit_exhausted" Average
|
||||
, serTransform = Multiply 60
|
||||
, serAlias = "exhaust"
|
||||
, serColor = "#cc0000"
|
||||
, serLabel = "Requests exhausted/min"
|
||||
}
|
||||
]
|
||||
, gsIdentifier = RateLimit
|
||||
}
|
||||
|
||||
trafficGraph :: GraphSpec
|
||||
trafficGraph =
|
||||
GraphSpec
|
||||
{ gsName = "traffic"
|
||||
, gsTitle = "Hass triggers in / services out"
|
||||
, gsPlots =
|
||||
[ Line 2 Series
|
||||
{ serSource = Source "hass_trigger_in" Average
|
||||
, serTransform = Multiply 60
|
||||
, serAlias = "in"
|
||||
, serColor = "#0066cc"
|
||||
, serLabel = "Triggers in/min"
|
||||
}
|
||||
, Line 2 Series
|
||||
{ serSource = Source "hass_service_out" Average
|
||||
, serTransform = Multiply 60
|
||||
, serAlias = "out"
|
||||
, serColor = "#cc0000"
|
||||
, serLabel = "Service calls out/min"
|
||||
}
|
||||
]
|
||||
, gsIdentifier = Traffic
|
||||
}
|
||||
|
||||
memoryGraph :: GraphSpec
|
||||
memoryGraph =
|
||||
GraphSpec
|
||||
"memory"
|
||||
"Memory use"
|
||||
[ area "live" "#99ccff" (average "rts_gc_current__a7a")
|
||||
, line "peak" "#cc0000" (maximumCF "rts_gc_current__a7a")
|
||||
]
|
||||
Memory
|
||||
|
||||
graphs :: [GraphSpec]
|
||||
graphs = [memoryGraph, ratelimitGraph, trafficGraph]
|
||||
|
||||
-- XXX: Proper lookup..?
|
||||
lookupGraph :: [GraphSpec] -> Graph -> Maybe GraphSpec
|
||||
lookupGraph specs graphMode = case [g | g <- specs, gsIdentifier g == graphMode] of
|
||||
(g : _) -> Just g
|
||||
[] -> Nothing
|
||||
|
||||
parseNameParam :: [GraphSpec] -> Text -> Maybe GraphSpec
|
||||
parseNameParam specs t = rightToMaybe (parseQueryParam t) >>= lookupGraph specs
|
||||
where
|
||||
rightToMaybe = either (const Nothing) Just
|
||||
|
||||
cfName :: CF -> String
|
||||
cfName = \case
|
||||
Average -> "AVERAGE"
|
||||
Minimum -> "MIN"
|
||||
Maximum -> "MAX"
|
||||
Last -> "LAST"
|
||||
|
||||
defArgs :: FilePath -> Series -> [String]
|
||||
defArgs rrdPath series =
|
||||
[ "DEF:" ++ rawF ++ "=" ++ rrdPath ++ ":"
|
||||
++ srcDs source ++ ":" ++ cfName (srcCF source)
|
||||
]
|
||||
++ transformArgs
|
||||
where
|
||||
source = serSource series
|
||||
alias = serAlias series
|
||||
rawF = alias ++ "_raw"
|
||||
|
||||
transformArgs = case serTransform series of
|
||||
Identity ->
|
||||
[ "CDEF:" ++ alias ++ "=" ++ rawF ]
|
||||
|
||||
Multiply factor ->
|
||||
[ "CDEF:" ++ alias ++ "=" ++ rawF
|
||||
++ "," ++ show factor ++ ",*"
|
||||
]
|
||||
|
||||
plotArg :: Plot -> String
|
||||
plotArg = \case
|
||||
Line width series ->
|
||||
"LINE" ++ show width ++ ":" ++ serAlias series
|
||||
++ serColor series ++ ":" ++ serLabel series
|
||||
|
||||
Area series ->
|
||||
"AREA:" ++ serAlias series
|
||||
++ serColor series ++ ":" ++ serLabel series
|
||||
|
||||
plotSeries :: Plot -> Series
|
||||
plotSeries = \case
|
||||
Line _ series -> series
|
||||
Area series -> series
|
||||
|
||||
buildGraphArgs :: FilePath -> GraphSpec -> Range -> [String]
|
||||
buildGraphArgs rrdPath spec range =
|
||||
[ "graph"
|
||||
, "-"
|
||||
, "--start", rangeStart range
|
||||
, "--title", gsTitle spec
|
||||
, "--width", "800"
|
||||
, "--height", "250"
|
||||
, "--imgformat", "PNG"
|
||||
]
|
||||
++ concatMap (defArgs rrdPath . plotSeries) (gsPlots spec)
|
||||
++ map plotArg (gsPlots spec)
|
||||
|
||||
|
||||
readProcessBytes :: FilePath -> [String] -> IO (ExitCode, BS.ByteString, String)
|
||||
readProcessBytes cmd args =
|
||||
withCreateProcess (proc cmd args) { std_out = CreatePipe, std_err = CreatePipe } $
|
||||
\_ mout merr ph ->
|
||||
case (mout, merr) of
|
||||
(Just hout, Just herr) -> do
|
||||
out <- BS.hGetContents hout
|
||||
err <- hGetContents herr
|
||||
code <- waitForProcess ph
|
||||
_ <- evaluate (length err)
|
||||
pure (code, out, err)
|
||||
_ -> pure (ExitFailure 1, BS.empty, "failed to create pipes")
|
||||
|
||||
renderGraph :: MonadIO m => FilePath -> FilePath -> GraphSpec -> Range -> m (Either Text BS.ByteString)
|
||||
renderGraph rrdPath rrdtool spec range = do
|
||||
(code, out, err) <- liftIO (readProcessBytes rrdtool (buildGraphArgs rrdPath spec range))
|
||||
case code of
|
||||
ExitSuccess
|
||||
| not (BS.null out) -> pure $ Right out
|
||||
| otherwise -> pure $ Left "empty graph"
|
||||
_ -> pure $ Left (T.pack $ take 200 err)
|
||||
|
||||
|
||||
|
||||
|
||||
data Graph
|
||||
= Memory
|
||||
| Traffic
|
||||
| RateLimit
|
||||
deriving (Show, Eq, Enum, Bounded)
|
||||
|
||||
instance ToHttpApiData Graph where
|
||||
toQueryParam Memory = "memory.png"
|
||||
toQueryParam Traffic = "traffic.png"
|
||||
toQueryParam RateLimit = "ratelimit.png"
|
||||
|
||||
instance FromHttpApiData Graph where
|
||||
parseQueryParam "memory.png" = Right Memory
|
||||
parseQueryParam "traffic.png" = Right Traffic
|
||||
parseQueryParam "ratelimit.png" = Right RateLimit
|
||||
parseQueryParam x = Left ("Can't parse '" <> x <> "' as Graph")
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module HomeAssistant.Runtime.Metrics
|
||||
( DsType (..)
|
||||
, DsSpec (..)
|
||||
, dsTypeOf
|
||||
, sanitizeName
|
||||
, buildSchema
|
||||
, buildCreateArgs
|
||||
, buildUpdateArgs
|
||||
, parseInfoDs
|
||||
, schemaMatches
|
||||
, AppMetrics (..)
|
||||
, registerAppMetrics
|
||||
, ensureRrd
|
||||
, sampleAndUpdate
|
||||
, metricsAction
|
||||
) where
|
||||
|
||||
import Control.Concurrent (threadDelay)
|
||||
import Control.Monad (forever, unless)
|
||||
import Data.Char (ord)
|
||||
import Data.Int (Int64)
|
||||
import Data.List (intercalate, sort, sortBy, stripPrefix)
|
||||
import Data.Maybe (mapMaybe)
|
||||
import Data.Ord (comparing)
|
||||
import Data.Text (Text)
|
||||
import Data.Time (defaultTimeLocale, formatTime, getCurrentTime)
|
||||
import Data.Void (Void)
|
||||
import Numeric (showHex)
|
||||
import qualified Data.Text as T
|
||||
import qualified Data.HashMap.Strict as HM
|
||||
import qualified System.Metrics as M (Value (..), Sample, Store, createCounter, sampleAll)
|
||||
import System.Metrics.Counter (Counter)
|
||||
import System.Directory (doesFileExist, renameFile)
|
||||
import System.Exit (ExitCode (..))
|
||||
import System.Process (callProcess, readProcessWithExitCode)
|
||||
import Control.Monad.IO.Class (MonadIO, liftIO)
|
||||
import Control.Exception.Annotated (checkpointCallStack)
|
||||
import Control.Monad.Catch (MonadCatch)
|
||||
|
||||
data DsType = Derive | Gauge
|
||||
deriving (Eq, Ord, Show)
|
||||
|
||||
data DsSpec = DsSpec
|
||||
{ dsEkgName :: Text
|
||||
, dsName :: String
|
||||
, dsType :: DsType
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
dsTypeOf :: M.Value -> Maybe DsType
|
||||
dsTypeOf (M.Counter _) = Just Derive
|
||||
dsTypeOf (M.Gauge _) = Just Gauge
|
||||
dsTypeOf _ = Nothing
|
||||
|
||||
-- | Maps an ekg metric label to a valid rrd DS name (≤19 chars, [A-Za-z0-9_]).
|
||||
-- Long names keep the first 15 chars plus a 3-hex hash suffix for uniqueness.
|
||||
sanitizeName :: Text -> String
|
||||
sanitizeName name
|
||||
| length sanitized <= 19 = sanitized
|
||||
| otherwise = take 15 sanitized ++ "_" ++ paddedHash
|
||||
where
|
||||
sanitized = T.unpack (T.replace "." "_" name)
|
||||
paddedHash = let h = showHex (sum (map ord sanitized) `mod` 4096) ""
|
||||
in replicate (3 - length h) '0' ++ h
|
||||
|
||||
buildSchema :: M.Sample -> [DsSpec]
|
||||
buildSchema sample =
|
||||
sortBy (comparing dsName)
|
||||
[ DsSpec ekgName (sanitizeName ekgName) dt
|
||||
| (ekgName, val) <- HM.toList sample
|
||||
, Just dt <- [dsTypeOf val]
|
||||
]
|
||||
|
||||
data AppMetrics = AppMetrics
|
||||
{ amTriggersIn :: Counter
|
||||
, amServicesOut :: Counter
|
||||
}
|
||||
|
||||
registerAppMetrics :: M.Store -> IO AppMetrics
|
||||
registerAppMetrics store =
|
||||
AppMetrics
|
||||
<$> M.createCounter "hass.trigger.in" store
|
||||
<*> M.createCounter "hass.service.out" store
|
||||
|
||||
|
||||
|
||||
buildCreateArgs :: FilePath -> Int -> [(String, DsType)] -> [String]
|
||||
buildCreateArgs path step specs =
|
||||
["create", path, "--step", show step]
|
||||
++ concatMap dsArg specs
|
||||
++ rras
|
||||
where
|
||||
dsArg (name, Derive) = ["DS:" ++ name ++ ":DERIVE:20:0:U"]
|
||||
dsArg (name, Gauge) = ["DS:" ++ name ++ ":GAUGE:20:0:U"]
|
||||
rras =
|
||||
[ "RRA:AVERAGE:0.5:1:6000"
|
||||
, "RRA:MAX:0.5:1:6000"
|
||||
, "RRA:AVERAGE:0.5:360:1680"
|
||||
, "RRA:MAX:0.5:360:1680"
|
||||
]
|
||||
|
||||
buildUpdateArgs :: FilePath -> [String] -> [Maybe Int64] -> [String]
|
||||
buildUpdateArgs path names values =
|
||||
[ "update"
|
||||
, path
|
||||
, "--template"
|
||||
, intercalate ":" names
|
||||
, "N:" ++ intercalate ":" (map renderValue values)
|
||||
]
|
||||
where
|
||||
renderValue Nothing = "U"
|
||||
renderValue (Just n) = show n
|
||||
|
||||
dsTypeFromString :: String -> Maybe DsType
|
||||
dsTypeFromString "DERIVE" = Just Derive
|
||||
dsTypeFromString "GAUGE" = Just Gauge
|
||||
dsTypeFromString _ = Nothing
|
||||
|
||||
parseInfoDs :: String -> [(String, DsType)]
|
||||
parseInfoDs = mapMaybe parseLine . lines
|
||||
where
|
||||
parseLine line = do
|
||||
rest0 <- stripPrefix "ds[" line
|
||||
let (name, rest1) = break (== ']') rest0
|
||||
rest2 <- stripPrefix "].type = \"" rest1
|
||||
let (ty, _) = break (== '"') rest2
|
||||
dt <- dsTypeFromString ty
|
||||
pure (name, dt)
|
||||
|
||||
schemaMatches :: [DsSpec] -> [(String, DsType)] -> Bool
|
||||
schemaMatches schema existing =
|
||||
sort (map (\s -> (dsName s, dsType s)) schema) == sort existing
|
||||
|
||||
lookupValue :: M.Sample -> Text -> Maybe Int64
|
||||
lookupValue sample name = case HM.lookup name sample of
|
||||
Just (M.Counter n) -> Just n
|
||||
Just (M.Gauge n) -> Just n
|
||||
_ -> Nothing
|
||||
|
||||
readExistingDs :: (MonadCatch m, MonadIO m) => FilePath -> FilePath -> m [(String, DsType)]
|
||||
readExistingDs rrdtool rrdPath = checkpointCallStack $ do
|
||||
(code, out, _) <- liftIO $ readProcessWithExitCode rrdtool ["info", rrdPath] ""
|
||||
pure $ case code of
|
||||
ExitSuccess -> parseInfoDs out
|
||||
_ -> []
|
||||
|
||||
backupPath :: MonadIO m => FilePath -> m FilePath
|
||||
backupPath path = liftIO $ do
|
||||
now <- getCurrentTime
|
||||
pure $ path ++ ".bak-" ++ formatTime defaultTimeLocale "%Y%m%dT%H%M%S" now
|
||||
|
||||
ensureRrd :: (MonadCatch m, MonadIO m) => FilePath -> FilePath -> [DsSpec] -> m ()
|
||||
ensureRrd rrdtool rrdPath schema = checkpointCallStack $ do
|
||||
exists <- liftIO $ doesFileExist rrdPath
|
||||
if not exists
|
||||
then create
|
||||
else do
|
||||
current <- readExistingDs rrdtool rrdPath
|
||||
unless (schemaMatches schema current) $ do
|
||||
backup <- backupPath rrdPath
|
||||
liftIO $ renameFile rrdPath backup
|
||||
create
|
||||
where
|
||||
create = liftIO $ callProcess rrdtool (buildCreateArgs rrdPath 10 (map toPair schema))
|
||||
toPair s = (dsName s, dsType s)
|
||||
|
||||
sampleAndUpdate :: (MonadCatch m, MonadIO m) => M.Store -> FilePath -> FilePath -> [DsSpec] -> m ()
|
||||
sampleAndUpdate store rrdtool rrdPath schema = checkpointCallStack $ do
|
||||
sample <- liftIO $ M.sampleAll store
|
||||
let names = map dsName schema
|
||||
values = map (lookupValue sample . dsEkgName) schema
|
||||
liftIO $ callProcess rrdtool (buildUpdateArgs rrdPath names values)
|
||||
|
||||
metricsAction :: (MonadCatch m, MonadIO m) => M.Store -> FilePath -> FilePath -> m Void
|
||||
metricsAction store rrdPath rrdtool = checkpointCallStack $ do
|
||||
schema <- buildSchema <$> liftIO (M.sampleAll store)
|
||||
ensureRrd rrdtool rrdPath schema
|
||||
forever $ do
|
||||
sampleAndUpdate store rrdtool rrdPath schema
|
||||
liftIO $ threadDelay 10000000
|
||||
@@ -0,0 +1,74 @@
|
||||
{-# Language DerivingVia #-}
|
||||
{-# Language OverloadedStrings #-}
|
||||
module HomeAssistant.Runtime.RateLimit where
|
||||
import Control.Monad.IO.Class (MonadIO, liftIO)
|
||||
import Data.Time (NominalDiffTime)
|
||||
import Control.Concurrent.STM (newTVarIO, atomically, readTVar, writeTVar)
|
||||
import Data.Time.Clock.POSIX (getPOSIXTime)
|
||||
import Katip.Monadic (KatipContext(..))
|
||||
import Control.Retry (fullJitterBackoff, limitRetries, retrying, RetryStatus (..))
|
||||
import Data.Maybe (isNothing)
|
||||
import Control.Exception.Annotated (Exception, checkpointCallStack, throw)
|
||||
import Control.Monad.Catch (MonadCatch)
|
||||
import Katip (Katip, Severity (WarningS), logFM, ls)
|
||||
import Control.Monad (when)
|
||||
import System.Metrics.Counter (Counter)
|
||||
import qualified System.Metrics.Counter as Counter
|
||||
import System.Metrics (Store, createCounter)
|
||||
|
||||
data RateLimitMetrics = RateLimitMetrics
|
||||
{ rlRetries :: Counter
|
||||
, rlRejects :: Counter
|
||||
}
|
||||
|
||||
|
||||
registerRateLimitMetrics :: MonadIO m => Store -> m RateLimitMetrics
|
||||
registerRateLimitMetrics store = liftIO $ RateLimitMetrics
|
||||
<$> createCounter "ratelimit.retry" store
|
||||
<*> createCounter "ratelimit.exhausted" store
|
||||
|
||||
newtype RateLimited m a = RateLimited (m a)
|
||||
deriving (Functor, Applicative, Monad, MonadIO, KatipContext, Katip) via m
|
||||
|
||||
|
||||
data RateLimiter = RateLimiter
|
||||
{ metrics :: RateLimitMetrics
|
||||
, limiter :: forall m a. (KatipContext m, MonadIO m) => RateLimited m a -> m (Maybe a)
|
||||
}
|
||||
|
||||
|
||||
slidingWindowLimiter
|
||||
:: RateLimitMetrics
|
||||
-> NominalDiffTime -- ^ Within how many seconds
|
||||
-> Int -- ^ How many requests we can make
|
||||
-> IO RateLimiter
|
||||
slidingWindowLimiter metrics timeWindow size = do
|
||||
window <- newTVarIO []
|
||||
return $ RateLimiter metrics $ \(RateLimited action) -> do
|
||||
now <- liftIO getPOSIXTime
|
||||
allowed <- liftIO $ atomically $ do
|
||||
elements <- takeWhile (\x -> x > now - timeWindow) <$> readTVar window
|
||||
if length elements >= size
|
||||
then pure False
|
||||
else True <$ writeTVar window (now : elements)
|
||||
if allowed
|
||||
then Just <$> action
|
||||
else pure Nothing
|
||||
|
||||
data RateLimitException = RateLimitExhausted
|
||||
deriving Show
|
||||
|
||||
instance Exception RateLimitException
|
||||
|
||||
runRateLimited :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> RateLimited m a -> m a
|
||||
runRateLimited (RateLimiter metrics run) action = checkpointCallStack $ do
|
||||
x <- retrying retryPolicy (const $ pure . isNothing) $ \RetryStatus{rsIterNumber} -> do
|
||||
when (rsIterNumber > 0) $ do
|
||||
logFM WarningS $ ls $ "Rate limited, attempt no. " <> show rsIterNumber
|
||||
incRetry
|
||||
run action
|
||||
maybe (incReject >> throw RateLimitExhausted) pure x
|
||||
where
|
||||
retryPolicy = fullJitterBackoff 500_000 <> limitRetries 5
|
||||
incRetry = liftIO $ Counter.inc (rlRetries metrics)
|
||||
incReject = liftIO $ Counter.inc (rlRejects metrics)
|
||||
@@ -2,26 +2,23 @@
|
||||
|
||||
module HomeAssistant.Runtime.Supervisor
|
||||
( supervised
|
||||
, Backoff(..)
|
||||
, defaultBackoff
|
||||
, backoffDelay
|
||||
, nextAttempt
|
||||
, Fatal(..)
|
||||
) where
|
||||
|
||||
import Control.Concurrent (threadDelay)
|
||||
import Control.Exception.Annotated
|
||||
( Exception
|
||||
, Handler (..)
|
||||
, SomeException
|
||||
, catches
|
||||
, displayException
|
||||
, throw
|
||||
, checkpoint, Annotation (..)
|
||||
)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Time (NominalDiffTime, diffUTCTime, getCurrentTime)
|
||||
import Data.Void (Void)
|
||||
import Control.Monad.IO.Class (MonadIO)
|
||||
import Control.Monad.Catch (MonadCatch, MonadMask)
|
||||
import Katip (KatipContext, logFM, ls)
|
||||
import Control.Retry (RetryStatus(..), recovering, fullJitterBackoff, capDelay, skipAsyncExceptions)
|
||||
import Control.Monad (when)
|
||||
import Katip.Core (Severity(..))
|
||||
|
||||
-- | A failure that cannot be fixed by restarting; propagates out of
|
||||
-- 'supervised' and terminates the process.
|
||||
@@ -30,28 +27,11 @@ newtype Fatal = Fatal Text
|
||||
|
||||
instance Exception Fatal
|
||||
|
||||
data Backoff = Backoff
|
||||
{ backoffBase :: NominalDiffTime -- ^ Delay before the first restart
|
||||
, backoffCap :: NominalDiffTime -- ^ Maximum delay between restarts
|
||||
, backoffQuiet :: NominalDiffTime -- ^ Uptime after which the delay resets
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
defaultBackoff :: Backoff
|
||||
defaultBackoff = Backoff 0.1 30 30
|
||||
data SupervisorException = RetriesExhausted
|
||||
deriving Show
|
||||
|
||||
-- | Delay before the @attempt@-th restart: doubles from base, clamped at cap.
|
||||
backoffDelay :: Backoff -> Int -> NominalDiffTime
|
||||
backoffDelay (Backoff base cap _) attempt = go (max 0 (attempt - 1)) base
|
||||
where
|
||||
go 0 d = d
|
||||
go n d = go (n - 1) (min cap (d * 2))
|
||||
|
||||
-- | Attempt number to use after a crash that ran for the given uptime.
|
||||
nextAttempt :: Backoff -> NominalDiffTime -> Int -> Int
|
||||
nextAttempt (Backoff _ _ quiet) uptime attempt
|
||||
| uptime >= quiet = 1
|
||||
| otherwise = attempt + 1
|
||||
instance Exception SupervisorException
|
||||
|
||||
-- | Runs the action forever, restarting it with backoff after synchronous
|
||||
-- exceptions; async exceptions propagate. 'Fatal' is rethrown (crashing the
|
||||
@@ -59,22 +39,14 @@ nextAttempt (Backoff _ _ quiet) uptime attempt
|
||||
-- must not be wrapped in checkpoints around 'Fatal'-throwing code: a
|
||||
-- doubly-wrapped 'Fatal' is indistinguishable from a crash and would be
|
||||
-- restarted instead of escalated.
|
||||
supervised :: Text -> Backoff -> IO Void -> IO Void
|
||||
supervised name backoff action = go 1
|
||||
supervised :: (MonadIO m, MonadCatch m, KatipContext m, MonadMask m) => Text -> m Void -> m Void
|
||||
supervised name action = checkpoint (Annotation name) $ do
|
||||
recovering retryPolicy (skipAsyncExceptions ++ handlers) $ \RetryStatus{rsIterNumber} -> do
|
||||
when (rsIterNumber > 0) $ logFM WarningS $ ls $ "Child crashed, retry no " <> show rsIterNumber
|
||||
action
|
||||
where
|
||||
go attempt = do
|
||||
start <- getCurrentTime
|
||||
outcome <- (action >> pure (Nothing :: Maybe (Either Fatal SomeException))) `catches`
|
||||
[ Handler $ \(f :: Fatal) -> pure (Just (Left f))
|
||||
, Handler $ \(e :: SomeException) -> pure (Just (Right e))
|
||||
handlers =
|
||||
[ \_retryStatus -> Handler $ \(_ :: Fatal) -> pure False
|
||||
, \_retryStatus -> Handler $ \(_ :: SomeException) -> pure True
|
||||
]
|
||||
end <- getCurrentTime
|
||||
case outcome of
|
||||
Nothing -> error "unreachable: supervised action returned"
|
||||
Just (Left f) -> throw f
|
||||
Just (Right e) -> do
|
||||
putStrLn $ "[" <> T.unpack name <> "] attempt " <> show attempt <> " crashed: " <> displayException e
|
||||
let delay = backoffDelay backoff attempt
|
||||
putStrLn $ "[" <> T.unpack name <> "] restarting in " <> show delay
|
||||
threadDelay (round (realToFrac delay * 1000000 :: Double))
|
||||
go (nextAttempt backoff (diffUTCTime end start) attempt)
|
||||
retryPolicy = capDelay (15 * 1_000_000) (fullJitterBackoff 50_000)
|
||||
@@ -0,0 +1,64 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE DerivingVia #-}
|
||||
module HttpServer where
|
||||
|
||||
import Control.Monad (forever)
|
||||
import Control.Monad.IO.Class (liftIO, MonadIO)
|
||||
import qualified Data.ByteString as BS
|
||||
import Data.Void (Void)
|
||||
import Network.Wai.Handler.Warp (run)
|
||||
import Servant.API ((:>), Capture, Get, QueryParam, (:-), MimeRender (..), Accept (..), NamedRoutes)
|
||||
import Data.ByteString (ByteString)
|
||||
import GHC.Generics (Generic)
|
||||
import Servant (Handler, err404)
|
||||
import Control.Monad.Catch (throwM, MonadCatch, MonadThrow)
|
||||
import Servant.Server (err500, ServerT)
|
||||
import Data.Maybe (fromMaybe)
|
||||
import Control.Exception.Annotated (checkpoint, Annotation (Annotation))
|
||||
import Servant.Server.Generic (genericServeT)
|
||||
import Network.Wai (Application)
|
||||
import Network.HTTP.Media ((//))
|
||||
import HomeAssistant.Runtime.Graphing (Graph, Range (..), lookupGraph, graphs, renderGraph)
|
||||
import Katip (KatipContextT, Katip, runKatipContextT, LogEnv, KatipContext, ls, Severity (..), logFM)
|
||||
|
||||
data ImagePng
|
||||
|
||||
instance MimeRender ImagePng ByteString where
|
||||
mimeRender _ = BS.fromStrict
|
||||
|
||||
instance Accept ImagePng where
|
||||
contentType _ = "image" // "png"
|
||||
|
||||
|
||||
newtype API mode = API
|
||||
{ getMetrics :: mode :- "metrics" :> Capture "graph" Graph :> QueryParam "range" Range :> Get '[ImagePng] ByteString
|
||||
}
|
||||
deriving Generic
|
||||
|
||||
|
||||
getMetricsHandler :: FilePath -> FilePath -> Graph -> Maybe Range -> LoggingHandler ByteString
|
||||
getMetricsHandler rrdPath rrdtool graphMode mRange = checkpoint (Annotation (graphMode, mRange)) $ do
|
||||
case lookupGraph graphs graphMode of
|
||||
Nothing -> throwM err404
|
||||
Just spec -> do
|
||||
let range = fromMaybe OneDay mRange
|
||||
g <- renderGraph rrdPath rrdtool spec range
|
||||
either (\e -> logFM ErrorS (ls e) >> throwM err500) pure g
|
||||
|
||||
-- server :: FilePath -> FilePath -> API AsServer
|
||||
server :: FilePath -> FilePath -> ServerT (NamedRoutes API) LoggingHandler
|
||||
server rrdPath rrdtool = API { getMetrics = getMetricsHandler rrdPath rrdtool }
|
||||
|
||||
servantApp :: LogEnv -> FilePath -> FilePath -> Application
|
||||
servantApp le rrdPath rrdtool = genericServeT (toHandler le) (server rrdPath rrdtool)
|
||||
|
||||
runHttpServer :: MonadIO m => LogEnv -> FilePath -> FilePath -> Int -> m Void
|
||||
runHttpServer le rrdPath rrdtool port = liftIO $ forever $ run port (servantApp le rrdPath rrdtool)
|
||||
|
||||
newtype LoggingHandler a = LoggingHandler (KatipContextT Handler a)
|
||||
deriving (Functor, Applicative, Monad, MonadIO, Katip, KatipContext, MonadCatch, MonadThrow) via (KatipContextT Handler)
|
||||
|
||||
toHandler :: LogEnv -> (forall a. LoggingHandler a -> Handler a)
|
||||
toHandler le (LoggingHandler k) = runKatipContextT le () "http" k
|
||||
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
module AFRPLawsSpec (spec) where
|
||||
|
||||
import AFRP
|
||||
import Control.Arrow (arr, first, left, (***), (+++))
|
||||
import Control.Category ((>>>))
|
||||
import qualified Control.Category as Cat (id)
|
||||
import Data.Functor.Identity (Identity (..))
|
||||
import Hedgehog (Gen, PropertyT)
|
||||
import qualified Hedgehog.Gen as Gen
|
||||
import qualified Hedgehog.Range as Range
|
||||
import Support (fakeRequest)
|
||||
import Test.Hspec (Spec, describe, it)
|
||||
import Test.Hspec.Hedgehog (forAll, forAllWith, hedgehog, (===))
|
||||
|
||||
-- | Law tests for the Mealy instances. Two machines count as equal when
|
||||
-- they emit equal outputs on every input sequence, so each law runs both
|
||||
-- sides on generated inputs.
|
||||
|
||||
runPure :: Mealy Identity a b -> [a] -> [b]
|
||||
runPure m = go (runMealy m id)
|
||||
where
|
||||
go _ [] = []
|
||||
go w (a : as) = case runIdentity (stepAuto w fakeRequest a) of
|
||||
(b, w') -> b : go w' as
|
||||
|
||||
-- | Machines wrap functions and have no Show; name them for forAll instead.
|
||||
forAllMealy :: Gen (Mealy Identity a b) -> PropertyT IO (Mealy Identity a b)
|
||||
forAllMealy = forAllWith (const "<mealy>")
|
||||
|
||||
intGen :: Gen Int
|
||||
intGen = Gen.int (Range.linear (-5) 5)
|
||||
|
||||
ints :: Gen [Int]
|
||||
ints = Gen.list (Range.linear 0 30) intGen
|
||||
|
||||
intPairs :: Gen [(Int, Int)]
|
||||
intPairs = Gen.list (Range.linear 0 30) ((,) <$> intGen <*> intGen)
|
||||
|
||||
intEithers :: Gen [Either Int Int]
|
||||
intEithers = Gen.list (Range.linear 0 30) $
|
||||
Gen.choice [Left <$> intGen, Right <$> intGen]
|
||||
|
||||
nestedPairs :: Gen [((Int, Int), Int)]
|
||||
nestedPairs = Gen.list (Range.linear 0 30) ((,) <$> ((,) <$> intGen <*> intGen) <*> intGen)
|
||||
|
||||
nestedEithers :: Gen [Either (Either Int Int) Int]
|
||||
nestedEithers = Gen.list (Range.linear 0 30) $
|
||||
Gen.choice
|
||||
[ Left <$> Gen.choice [Left <$> intGen, Right <$> intGen]
|
||||
, Right <$> intGen
|
||||
]
|
||||
|
||||
-- | Stateful Int machines: the arrow variables of the laws.
|
||||
statefulGen :: Gen (Mealy Identity Int Int)
|
||||
statefulGen = Gen.choice
|
||||
[ (\k -> mapAccum (+) k id) <$> intGen
|
||||
, (\k -> preMapAccum (+) k id) <$> intGen
|
||||
, (\k -> mapAccum (*) 1 (+ k)) <$> intGen
|
||||
]
|
||||
|
||||
eventArrowGen :: Gen (Mealy Identity Int (Event Int))
|
||||
eventArrowGen = Gen.choice
|
||||
[ pure changes
|
||||
, (\k -> mapAccum (+) k Event) <$> intGen
|
||||
, (\k -> preMapAccum (+) k (Event . (* 2))) <$> intGen
|
||||
]
|
||||
|
||||
funArrowGen :: Gen (Mealy Identity Int (Int -> Int))
|
||||
funArrowGen = Gen.choice
|
||||
[ (\k -> mapAccum (+) k (*)) <$> intGen
|
||||
, pure (preMapAccum (*) 1 (+))
|
||||
]
|
||||
|
||||
spec :: Spec
|
||||
spec = describe "Mealy laws" $ do
|
||||
semigroupSpec
|
||||
monoidSpec
|
||||
categorySpec
|
||||
arrowSpec
|
||||
arrowChoiceSpec
|
||||
functorSpec
|
||||
applicativeSpec
|
||||
|
||||
semigroupSpec :: Spec
|
||||
semigroupSpec = describe "Semigroup (<>)" $ do
|
||||
it "(a <> b) <> c = a <> (b <> c)" $ hedgehog $ do
|
||||
a <- forAllMealy eventArrowGen
|
||||
b <- forAllMealy eventArrowGen
|
||||
c <- forAllMealy eventArrowGen
|
||||
xs <- forAll ints
|
||||
runPure ((a <> b) <> c) xs === runPure (a <> (b <> c)) xs
|
||||
|
||||
monoidSpec :: Spec
|
||||
monoidSpec = describe "Monoid" $ do
|
||||
it "mempty <> a = a" $ hedgehog $ do
|
||||
a <- forAllMealy eventArrowGen
|
||||
xs <- forAll ints
|
||||
runPure (mempty <> a) xs === runPure a xs
|
||||
|
||||
it "a <> mempty = a" $ hedgehog $ do
|
||||
a <- forAllMealy eventArrowGen
|
||||
xs <- forAll ints
|
||||
runPure (a <> mempty) xs === runPure a xs
|
||||
|
||||
categorySpec :: Spec
|
||||
categorySpec = describe "Category" $ do
|
||||
it "id >>> f = f" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
xs <- forAll ints
|
||||
runPure (Cat.id >>> f) xs === runPure f xs
|
||||
|
||||
it "f >>> id = f" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
xs <- forAll ints
|
||||
runPure (f >>> Cat.id) xs === runPure f xs
|
||||
|
||||
it "(f >>> g) >>> h = f >>> (g >>> h)" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
g <- forAllMealy statefulGen
|
||||
h <- forAllMealy statefulGen
|
||||
xs <- forAll ints
|
||||
runPure ((f >>> g) >>> h) xs === runPure (f >>> (g >>> h)) xs
|
||||
|
||||
arrowSpec :: Spec
|
||||
arrowSpec = describe "Arrow" $ do
|
||||
it "arr id = id" $ hedgehog $ do
|
||||
xs <- forAll ints
|
||||
runPure (arr id :: Mealy Identity Int Int) xs === runPure Cat.id xs
|
||||
|
||||
it "arr (f >>> g) = arr f >>> arr g" $ hedgehog $ do
|
||||
p <- forAll intGen
|
||||
q <- forAll intGen
|
||||
xs <- forAll ints
|
||||
let f = (+ p)
|
||||
g = (* q)
|
||||
runPure (arr (f >>> g)) xs === runPure (arr f >>> arr g) xs
|
||||
|
||||
it "first (arr f) = arr (first f)" $ hedgehog $ do
|
||||
p <- forAll intGen
|
||||
ps <- forAll intPairs
|
||||
let f = (+ p)
|
||||
runPure (first (arr f)) ps === runPure (arr (first f)) ps
|
||||
|
||||
it "first (f >>> g) = first f >>> first g" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
g <- forAllMealy statefulGen
|
||||
ps <- forAll intPairs
|
||||
runPure (first (f >>> g)) ps === runPure (first f >>> first g) ps
|
||||
|
||||
it "first f >>> arr fst = arr fst >>> f" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
ps <- forAll intPairs
|
||||
runPure (first f >>> arr fst) ps === runPure (arr fst >>> f) ps
|
||||
|
||||
it "first f >>> arr (id *** g) = arr (id *** g) >>> first f" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
p <- forAll intGen
|
||||
ps <- forAll intPairs
|
||||
let g = (* p)
|
||||
runPure (first f >>> arr (id *** g)) ps
|
||||
=== runPure (arr (id *** g) >>> first f) ps
|
||||
|
||||
it "first (first f) >>> arr assoc = arr assoc >>> first f" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
ts <- forAll nestedPairs
|
||||
let assoc ((a, b), c) = (a, (b, c))
|
||||
runPure (first (first f) >>> arr assoc) ts
|
||||
=== runPure (arr assoc >>> first f) ts
|
||||
|
||||
arrowChoiceSpec :: Spec
|
||||
arrowChoiceSpec = describe "ArrowChoice" $ do
|
||||
it "left (arr f) = arr (left f)" $ hedgehog $ do
|
||||
p <- forAll intGen
|
||||
es <- forAll intEithers
|
||||
let f = (+ p)
|
||||
runPure (left (arr f)) es === runPure (arr (left f)) es
|
||||
|
||||
it "left (f >>> g) = left f >>> left g" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
g <- forAllMealy statefulGen
|
||||
es <- forAll intEithers
|
||||
runPure (left (f >>> g)) es === runPure (left f >>> left g) es
|
||||
|
||||
it "f >>> arr Left = arr Left >>> left f" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
xs <- forAll ints
|
||||
runPure (f >>> arr (Left @Int @Int)) xs
|
||||
=== runPure (arr (Left @Int @Int) >>> left f) xs
|
||||
|
||||
it "left f >>> arr (id +++ g) = arr (id +++ g) >>> left f" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
p <- forAll intGen
|
||||
es <- forAll intEithers
|
||||
let g = (* p)
|
||||
runPure (left f >>> arr (id +++ g)) es
|
||||
=== runPure (arr (id +++ g) >>> left f) es
|
||||
|
||||
it "left (left f) >>> arr assocsum = arr assocsum >>> left f" $ hedgehog $ do
|
||||
f <- forAllMealy statefulGen
|
||||
es <- forAll nestedEithers
|
||||
let assocsum (Left (Left x)) = Left x
|
||||
assocsum (Left (Right y)) = Right (Left y)
|
||||
assocsum (Right z) = Right (Right z)
|
||||
runPure (left (left f) >>> arr assocsum) es
|
||||
=== runPure (arr assocsum >>> left f) es
|
||||
|
||||
functorSpec :: Spec
|
||||
functorSpec = describe "Functor" $ do
|
||||
it "fmap id = id" $ hedgehog $ do
|
||||
m <- forAllMealy statefulGen
|
||||
xs <- forAll ints
|
||||
runPure (fmap id m) xs === runPure m xs
|
||||
|
||||
it "fmap (f . g) = fmap f . fmap g" $ hedgehog $ do
|
||||
m <- forAllMealy statefulGen
|
||||
p <- forAll intGen
|
||||
q <- forAll intGen
|
||||
xs <- forAll ints
|
||||
let f = (+ p)
|
||||
g = (* q)
|
||||
runPure (fmap (f . g) m) xs === runPure (fmap f (fmap g m)) xs
|
||||
|
||||
applicativeSpec :: Spec
|
||||
applicativeSpec = describe "Applicative" $ do
|
||||
it "pure id <*> v = v" $ hedgehog $ do
|
||||
v <- forAllMealy statefulGen
|
||||
xs <- forAll ints
|
||||
runPure (pure id <*> v) xs === runPure v xs
|
||||
|
||||
it "pure f <*> pure x = pure (f x)" $ hedgehog $ do
|
||||
p <- forAll intGen
|
||||
x <- forAll intGen
|
||||
xs <- forAll ints
|
||||
let f = (+ p)
|
||||
runPure (pure f <*> pure x) xs === runPure (pure (f x)) xs
|
||||
|
||||
it "u <*> pure y = pure ($ y) <*> u" $ hedgehog $ do
|
||||
u <- forAllMealy funArrowGen
|
||||
y <- forAll intGen
|
||||
xs <- forAll ints
|
||||
runPure (u <*> pure y) xs === runPure (pure ($ y) <*> u) xs
|
||||
|
||||
it "pure (.) <*> u <*> v <*> w = u <*> (v <*> w)" $ hedgehog $ do
|
||||
u <- forAllMealy funArrowGen
|
||||
v <- forAllMealy funArrowGen
|
||||
w <- forAllMealy statefulGen
|
||||
xs <- forAll ints
|
||||
runPure (pure (.) <*> u <*> v <*> w) xs
|
||||
=== runPure (u <*> (v <*> w)) xs
|
||||
|
||||
it "fmap f x = pure f <*> x" $ hedgehog $ do
|
||||
x <- forAllMealy statefulGen
|
||||
p <- forAll intGen
|
||||
xs <- forAll ints
|
||||
let f = (+ p)
|
||||
runPure (fmap f x) xs === runPure (pure f <*> x) xs
|
||||
+135
-79
@@ -1,13 +1,18 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module AFRPSpec (spec) where
|
||||
|
||||
import Control.Arrow (arr)
|
||||
import Control.Arrow (arr, (&&&), first, left)
|
||||
import Control.Category ((>>>))
|
||||
import Control.Monad.Fix (MonadFix (..))
|
||||
import Data.Foldable (for_)
|
||||
import AFRP
|
||||
import Data.Functor.Identity (Identity (..))
|
||||
import Data.List (sort)
|
||||
import Data.Time (NominalDiffTime, UTCTime (..), addUTCTime, diffUTCTime)
|
||||
import Data.Serialize (get, put, runGet, runPut)
|
||||
import qualified Data.Set as S
|
||||
import qualified Data.Text as T
|
||||
import Data.Time (Day (..), NominalDiffTime, LocalTime(..), TimeOfDay(..), UTCTime (..), picosecondsToDiffTime, utc)
|
||||
import Data.UUID (nil)
|
||||
import Hedgehog
|
||||
import qualified Hedgehog.Gen as Gen
|
||||
@@ -16,22 +21,29 @@ import Test.Hspec
|
||||
import Test.Hspec.Hedgehog
|
||||
|
||||
fakeRequest :: Request
|
||||
fakeRequest = Request (sec 0) nil
|
||||
fakeRequest = Request (sec 0) utc nil
|
||||
|
||||
sec :: Integer -> UTCTime
|
||||
sec n = UTCTime (toEnum 0) (fromIntegral n)
|
||||
|
||||
untime :: SerializeUTCTime -> UTCTime
|
||||
untime (SerializeUTCTime t) = t
|
||||
|
||||
runPure :: Mealy Identity a b -> [a] -> [b]
|
||||
runPure _ [] = []
|
||||
runPure m (a : as) = case runIdentity (AFRP.runMealy m id fakeRequest a) of
|
||||
(b, m') -> b : runPure m' as
|
||||
runPure m = go (runMealy m id)
|
||||
where
|
||||
go _ [] = []
|
||||
go w (a : as) = case runIdentity (stepAuto w fakeRequest a) of
|
||||
(b, w') -> b : go w' as
|
||||
|
||||
-- | Run a Mealy with a per-step wall clock (seconds since the day-0 epoch).
|
||||
runTimed :: Mealy Identity a b -> [(Integer, a)] -> [b]
|
||||
runTimed _ [] = []
|
||||
runTimed m ((s, a) : as) =
|
||||
case runIdentity (AFRP.runMealy m id (Request (sec s) nil) a) of
|
||||
(b, m') -> b : runTimed m' as
|
||||
runTimed m = go (runMealy m id)
|
||||
where
|
||||
go _ [] = []
|
||||
go w ((s, a) : as) =
|
||||
case runIdentity (stepAuto w (Request (sec s) utc nil) a) of
|
||||
(b, w') -> b : go w' as
|
||||
|
||||
-- | A minimal State monad for observing effectful arrows (e.g. whenA gating).
|
||||
newtype St a = St { unSt :: Int -> (a, Int) }
|
||||
@@ -50,15 +62,15 @@ instance MonadFix St where
|
||||
mfix f = St $ \s -> let (a, s') = unSt (f a) s in (a, s')
|
||||
|
||||
runStEff :: Mealy St a b -> Int -> [a] -> ([b], Int)
|
||||
runStEff m s0 as = go m s0 as
|
||||
runStEff m = go (runMealy m id)
|
||||
where
|
||||
go _ s [] = ([], s)
|
||||
go m' s (a : rest) =
|
||||
case unSt (AFRP.runMealy m' id fakeRequest a) s of
|
||||
((b, m''), s') -> let (bs, s'') = go m'' s' rest in (b : bs, s'')
|
||||
go w s (a : rest) = case unSt (stepAuto w fakeRequest a) s of
|
||||
((b, w'), s') -> let (bs, s'') = go w' s' rest in (b : bs, s'')
|
||||
|
||||
spec :: Spec
|
||||
spec = describe "AFRP" $ do
|
||||
entitiesSpec
|
||||
holdSpec
|
||||
eventsSpec
|
||||
isEventSpec
|
||||
@@ -75,9 +87,8 @@ spec = describe "AFRP" $ do
|
||||
delayEventSpec
|
||||
debounceSpec
|
||||
rollupSpec
|
||||
fixedSpec
|
||||
serializeSpec
|
||||
effSpec
|
||||
switchSpec
|
||||
mapAccumRequestSpec
|
||||
preMapAccumRequestSpec
|
||||
whenASpec
|
||||
@@ -134,6 +145,23 @@ lMergeSpec = describe "lMerge" $ do
|
||||
it "prefers right Event if left is Tick" $
|
||||
lMerge Tick (Event (2 :: Int)) `shouldBe` Event (2 :: Int)
|
||||
|
||||
it "Tick is a left identity" $
|
||||
hedgehog $ do
|
||||
e <- forAll eventGen
|
||||
lMerge Tick e === e
|
||||
|
||||
it "Tick is a right identity" $
|
||||
hedgehog $ do
|
||||
e <- forAll eventGen
|
||||
lMerge e Tick === e
|
||||
|
||||
it "is associative" $
|
||||
hedgehog $ do
|
||||
a <- forAll eventGen
|
||||
b <- forAll eventGen
|
||||
c <- forAll eventGen
|
||||
lMerge a (lMerge b c) === lMerge (lMerge a b) c
|
||||
|
||||
changesSpec :: Spec
|
||||
changesSpec = describe "changes" $ do
|
||||
it "first output is always Tick" $
|
||||
@@ -188,6 +216,7 @@ edgeSpec = describe "edge" $ do
|
||||
else o' === Tick
|
||||
_ -> failure
|
||||
|
||||
|
||||
filterASpec :: Spec
|
||||
filterASpec = describe "filterA" $ do
|
||||
it "lets through values matching predicate" $
|
||||
@@ -245,7 +274,7 @@ mapAccumSpec = describe "mapAccum" $ do
|
||||
for_ (zip3 [0 ..] xs out) $ \(i, _x, cur) ->
|
||||
cur === sum (take (i + 1) xs)
|
||||
|
||||
preMapAccumSpec :: Spec
|
||||
preMapAccumSpec :: Spec
|
||||
preMapAccumSpec = describe "preMapAccum" $ do
|
||||
it "running sum with pre-state extraction" $
|
||||
runPure (preMapAccum (+) (0 :: Int) id) [1, 2, 3]
|
||||
@@ -370,36 +399,6 @@ rollupSpec = describe "rollup" $ do
|
||||
emitted = concat [xs | Event xs <- out]
|
||||
sort emitted === sort [x | Event x <- evs]
|
||||
|
||||
fixedSpec :: Spec
|
||||
fixedSpec = describe "fixed" $ do
|
||||
it "accumulates events within a window and rolls over on expiry" $
|
||||
runTimed (fixed 10)
|
||||
[ (0, Event 'a'), (1, Event 'b'), (2, Tick)
|
||||
, (12, Event 'c'), (13, Tick)
|
||||
]
|
||||
`shouldBe` [ ['a'], ['a', 'b'], ['a', 'b']
|
||||
, ['c'], ['c']
|
||||
]
|
||||
|
||||
it "starts a window even on a leading Tick" $
|
||||
runTimed (fixed 10)
|
||||
[ (0, Tick), (1, Event 'a')
|
||||
, (12, Tick), (13, Tick)
|
||||
, (25, Event 'b')
|
||||
]
|
||||
`shouldBe` [ [], ['a'], [], [], ['b'] ]
|
||||
|
||||
it "output is always the current window's accumulated list" $
|
||||
hedgehog $ do
|
||||
w <- forAll $ Gen.int (Range.constant 1 10)
|
||||
evs <- forAll $ Gen.list (Range.linear 0 30) eventGen
|
||||
let out = runTimed (fixed w) (zip [0 ..] evs)
|
||||
expected =
|
||||
[ [ x | Event x <- take (i - lo + 1) (drop lo evs) ]
|
||||
| i <- [0 .. length evs - 1]
|
||||
, let lo = (i `div` w) * w
|
||||
]
|
||||
out === expected
|
||||
|
||||
eventGen :: Gen (Event Char)
|
||||
eventGen = Gen.frequency
|
||||
@@ -407,11 +406,39 @@ eventGen = Gen.frequency
|
||||
, (1, pure Tick)
|
||||
]
|
||||
|
||||
timeGen :: Gen SerializeUTCTime
|
||||
timeGen = do
|
||||
day <- ModifiedJulianDay . fromIntegral <$> Gen.int (Range.linear 0 100000)
|
||||
pico <- picosecondsToDiffTime . fromIntegral
|
||||
<$> Gen.int (Range.linear 0 (86400 * 10 ^ (12 :: Int) - 1))
|
||||
pure $ SerializeUTCTime (UTCTime day pico)
|
||||
|
||||
localTimeGen :: Gen SerializeLocalTime
|
||||
localTimeGen = do
|
||||
day <- ModifiedJulianDay . fromIntegral <$> genInt 0 100000
|
||||
tod <- TimeOfDay <$> genInt 0 23 <*> genInt 0 59 <*> (fromIntegral <$> genInt 0 60)
|
||||
pure $ SerializeLocalTime (LocalTime day tod)
|
||||
where
|
||||
genInt a b = Gen.int (Range.linear a b)
|
||||
|
||||
serializeSpec :: Spec
|
||||
serializeSpec = do
|
||||
describe "SerializeUTCTime" $ do
|
||||
it "get (put x) == pure x" $
|
||||
hedgehog $ do
|
||||
x <- forAll timeGen
|
||||
tripping x (runPut . put) (runGet get)
|
||||
describe "SerializeLocalTime" $ do
|
||||
it "get (put x) == pure x" $
|
||||
hedgehog $ do
|
||||
x <- forAll localTimeGen
|
||||
tripping x (runPut . put) (runGet get)
|
||||
|
||||
effSpec :: Spec
|
||||
effSpec = describe "eff" $ do
|
||||
it "lifts a pure effect function into a stateless Mealy" $
|
||||
runPure (eff (\_ x -> Identity (x + 1))) [1, 2, 3]
|
||||
`shouldBe` [2, 3, 4]
|
||||
`shouldBe` [2 :: Int, 3, 4]
|
||||
|
||||
it "output equals f(input) for every step" $
|
||||
hedgehog $ do
|
||||
@@ -419,41 +446,17 @@ effSpec = describe "eff" $ do
|
||||
let out = runPure (eff (\_ x -> Identity (x * 2))) xs
|
||||
out === map (* 2) xs
|
||||
|
||||
switchSpec :: Spec
|
||||
switchSpec = describe "switch" $ do
|
||||
it "switches to the continuation at the first Event" $
|
||||
runPure (switch (arr (\x -> (x, if x >= 3 then Event () else Tick)))
|
||||
(const (arr (const 99))))
|
||||
[1, 2, 3, 4, 5]
|
||||
`shouldBe` [1, 2, 99, 99, 99]
|
||||
|
||||
it "never switches if no Event is emitted" $
|
||||
runPure (switch (arr (\x -> (x, Tick :: Event ())))
|
||||
(const (arr (const 99))))
|
||||
[1, 2, 3]
|
||||
`shouldBe` [1, 2, 3]
|
||||
|
||||
it "prefix outputs come from the first arrow, suffix from the continuation" $
|
||||
hedgehog $ do
|
||||
threshold <- forAll $ Gen.int (Range.linear (-20) 20)
|
||||
xs <- forAll $ Gen.list (Range.linear 0 30) (Gen.int (Range.linear (-20) 20))
|
||||
let first = arr (\x -> (x, if x >= threshold then Event () else Tick))
|
||||
out = runPure (switch first (const (arr (const 99)))) xs
|
||||
(pre, _post) = break (>= threshold) xs
|
||||
take (length pre) out === pre
|
||||
drop (length pre) out === replicate (length xs - length pre) 99
|
||||
|
||||
mapAccumRequestSpec :: Spec
|
||||
mapAccumRequestSpec = describe "mapAccumRequest" $ do
|
||||
it "accumulates request times, post-state extraction" $
|
||||
runTimed (mapAccumRequest (\req s _ -> s ++ [requestTime req]) [] id)
|
||||
runTimed (mapAccumRequest (\req s _ -> s ++ [SerializeUTCTime (requestTime req)]) [] (map untime))
|
||||
[(0, 'a'), (5, 'b'), (10, 'c')]
|
||||
`shouldBe` [ [sec 0], [sec 0, sec 5], [sec 0, sec 5, sec 10] ]
|
||||
|
||||
it "output i is every request time seen so far" $
|
||||
hedgehog $ do
|
||||
secs' <- forAll $ Gen.list (Range.linear 0 30) (Gen.int (Range.linear 0 100))
|
||||
let out = runTimed (mapAccumRequest (\req s _ -> s ++ [requestTime req]) [] id)
|
||||
let out = runTimed (mapAccumRequest (\req s _ -> s ++ [SerializeUTCTime (requestTime req)]) [] (map untime))
|
||||
[(fromIntegral s, ()) | s <- secs']
|
||||
expected = [ map (sec . fromIntegral) (take (i + 1) secs') | i <- [0 .. length secs' - 1] ]
|
||||
out === expected
|
||||
@@ -461,14 +464,14 @@ mapAccumRequestSpec = describe "mapAccumRequest" $ do
|
||||
preMapAccumRequestSpec :: Spec
|
||||
preMapAccumRequestSpec = describe "preMapAccumRequest" $ do
|
||||
it "accumulates request times, pre-state extraction" $
|
||||
runTimed (preMapAccumRequest (\req s _ -> s ++ [requestTime req]) [] id)
|
||||
runTimed (preMapAccumRequest (\req s _ -> s ++ [SerializeUTCTime (requestTime req)]) [] (map untime))
|
||||
[(0, 'a'), (5, 'b'), (10, 'c')]
|
||||
`shouldBe` [ [], [sec 0], [sec 0, sec 5] ]
|
||||
|
||||
it "output i is every request time before the current step" $
|
||||
hedgehog $ do
|
||||
secs' <- forAll $ Gen.list (Range.linear 0 30) (Gen.int (Range.linear 0 100))
|
||||
let out = runTimed (preMapAccumRequest (\req s _ -> s ++ [requestTime req]) [] id)
|
||||
let out = runTimed (preMapAccumRequest (\req s _ -> s ++ [SerializeUTCTime (requestTime req)]) [] (map untime))
|
||||
[(fromIntegral s, ()) | s <- secs']
|
||||
expected = [ map (sec . fromIntegral) (take i secs') | i <- [0 .. length secs' - 1] ]
|
||||
out === expected
|
||||
@@ -508,7 +511,7 @@ thenASpec = describe "thenA" $ do
|
||||
xs <- forAll $ Gen.list (Range.linear 0 30) (Gen.int (Range.linear (-20) 20))
|
||||
let out = runPure (filterA (even @Int) >>| filterA (> 0)) xs
|
||||
expected =
|
||||
[ if not (even x) then Left ()
|
||||
[ if odd x then Left ()
|
||||
else if x > 0 then Right x
|
||||
else Left ()
|
||||
| x <- xs ]
|
||||
@@ -518,14 +521,67 @@ sampleSpec :: Spec
|
||||
sampleSpec = describe "sample" $ do
|
||||
it "tags the current value onto the Event structure" $
|
||||
runPure sample [(1, Tick), (2, Event 'a'), (3, Tick)]
|
||||
`shouldBe` [Tick, Event 2, Tick]
|
||||
`shouldBe` [Tick, Event @Int 2, Tick]
|
||||
|
||||
it "output is Event a iff the input event is present" $
|
||||
hedgehog $ do
|
||||
vals <- forAll $ Gen.list (Range.linear 0 30) (Gen.int (Range.linear 0 100))
|
||||
evs <- forAll $ Gen.list (Range.linear 0 30) eventGen
|
||||
let n = min (length vals) (length evs)
|
||||
ps = zip (take n vals) (take n evs)
|
||||
ps = take n $ zip vals evs
|
||||
out = runPure sample ps
|
||||
for_ (zip ps out) $ \((v, ev), o) ->
|
||||
o === tag v ev
|
||||
|
||||
-- | A stateless arrow carrying a fixed entity set, for testing propagation.
|
||||
subscribed :: S.Set T.Text -> Mealy Identity Int Int
|
||||
subscribed ents = Mealy ents $ \_ -> Fun $ \_ a -> a
|
||||
|
||||
-- | Same as 'subscribed' but yields a function, for testing '<*>'.
|
||||
subscribedF :: S.Set T.Text -> Mealy Identity Int (Int -> Int)
|
||||
subscribedF ents = Mealy ents $ \_ -> Fun $ \_ a -> (a +)
|
||||
|
||||
entitiesSpec :: Spec
|
||||
entitiesSpec = describe "entities" $ do
|
||||
it "id carries no entities" $
|
||||
entities (arr id :: Mealy Identity Int Int) `shouldBe` S.empty
|
||||
|
||||
it "arr carries no entities" $
|
||||
entities (arr (+ 1) :: Mealy Identity Int Int) `shouldBe` S.empty
|
||||
|
||||
it "eff carries no entities" $
|
||||
entities (eff (\_ x -> Identity (x + 1 :: Int))) `shouldBe` S.empty
|
||||
|
||||
it "primitive combinators carry no entities" $ do
|
||||
entities (hold 'a') `shouldBe` S.empty
|
||||
entities (changes @Int) `shouldBe` S.empty
|
||||
entities edge `shouldBe` S.empty
|
||||
entities (sliding (3 :: Int) :: Mealy Identity (Event Int) [Int]) `shouldBe` S.empty
|
||||
|
||||
it "Category (.) unions entity sets" $
|
||||
entities (subscribed (S.singleton "a") >>> subscribed (S.singleton "b"))
|
||||
`shouldBe` S.fromList ["a", "b"]
|
||||
|
||||
it "Applicative (<*>) unions entity sets" $
|
||||
entities (subscribedF (S.singleton "a") <*> subscribed (S.singleton "b"))
|
||||
`shouldBe` S.fromList ["a", "b"]
|
||||
|
||||
it "Arrow (&&&) unions entity sets" $
|
||||
entities (subscribed (S.singleton "a") &&& subscribed (S.singleton "b"))
|
||||
`shouldBe` S.fromList ["a", "b"]
|
||||
|
||||
it "(>>>) unions entity sets" $
|
||||
entities (subscribed (S.singleton "a") >>> arr id >>> subscribed (S.singleton "b"))
|
||||
`shouldBe` S.fromList ["a", "b"]
|
||||
|
||||
it "left preserves the entity set" $
|
||||
entities (left (subscribed (S.singleton "a")) :: Mealy Identity (Either Int Int) (Either Int Int))
|
||||
`shouldBe` S.singleton "a"
|
||||
|
||||
it "first preserves the entity set" $
|
||||
entities (first (subscribed (S.singleton "a")) :: Mealy Identity (Int, Int) (Int, Int))
|
||||
`shouldBe` S.singleton "a"
|
||||
|
||||
it "fmap preserves the entity set" $
|
||||
entities (fmap (+ 1) (subscribed (S.singleton "a")))
|
||||
`shouldBe` S.singleton "a"
|
||||
@@ -1,21 +0,0 @@
|
||||
module BackoffProp (spec) where
|
||||
|
||||
import Data.Maybe (listToMaybe)
|
||||
import Data.Time (NominalDiffTime)
|
||||
import qualified Hedgehog.Gen as Gen
|
||||
import qualified Hedgehog.Range as Range
|
||||
import HomeAssistant.Runtime.Supervisor (Backoff (..), backoffDelay)
|
||||
import Test.Hspec (Spec, describe, it)
|
||||
import Test.Hspec.Hedgehog (hedgehog, forAll, (===))
|
||||
|
||||
spec :: Spec
|
||||
spec = describe "backoffDelay" $
|
||||
it "doubles from base, clamped at cap" $ hedgehog $ do
|
||||
baseD <- forAll $ Gen.double (Range.constant 0.0001 10)
|
||||
ratio <- forAll $ Gen.double (Range.constant 1 100)
|
||||
let base = realToFrac baseD :: NominalDiffTime
|
||||
cap = realToFrac (baseD * ratio) :: NominalDiffTime
|
||||
backoff = Backoff base cap 1
|
||||
delays = map (backoffDelay backoff) [1 .. 100 :: Int]
|
||||
listToMaybe delays === Just (min cap base)
|
||||
mapM_ (\(a, b) -> b === min cap (a * 2)) (zip delays (drop 1 delays))
|
||||
+49
-17
@@ -2,7 +2,8 @@
|
||||
|
||||
module BedroomSpec (spec) where
|
||||
|
||||
import AFRP (Event (..))
|
||||
import AFRP (Event (..), entities)
|
||||
import qualified Data.Set as S
|
||||
import qualified Data.Text as T
|
||||
import Data.Aeson (Value)
|
||||
import HomeAssistant.Controller
|
||||
@@ -21,9 +22,40 @@ drawerState = Event . stateEvent "binary_sensor.bedroom_nightstand_drawer_sensor
|
||||
|
||||
spec :: Spec
|
||||
spec = describe "Bedroom" $ do
|
||||
entitySpec
|
||||
drawerSpec
|
||||
buttonSpec
|
||||
|
||||
entitySpec :: Spec
|
||||
entitySpec = describe "entities" $ do
|
||||
it "entityChangeEvent' registers its entity id" $
|
||||
entities (entityChangeEvent' "sensor.foo")
|
||||
`shouldBe` S.singleton "sensor.foo"
|
||||
|
||||
it "entityRead / entityBool inherit the entity id" $ do
|
||||
entities (entityRead @Double "sensor.bar") `shouldBe` S.singleton "sensor.bar"
|
||||
entities (entityBool "binary_sensor.baz") `shouldBe` S.singleton "binary_sensor.baz"
|
||||
|
||||
it "bedroomDrawerController subscribes to the drawer sensor" $
|
||||
entities bedroomDrawerController
|
||||
`shouldBe` S.singleton "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contact"
|
||||
|
||||
it "bedroomButtonController subscribes to both remote event entities" $
|
||||
entities bedroomButtonController
|
||||
`shouldBe` S.fromList
|
||||
[ "event.bedroom_quick_remote_masse_action"
|
||||
, "event.bedroom_quick_jemina_action"
|
||||
, "event.bedroom_remote_action"
|
||||
]
|
||||
|
||||
it "bedroomPresenceController subscribes to the presence sensor" $
|
||||
entities bedroomPresenceController
|
||||
`shouldBe` S.singleton "binary_sensor.presence_sensor_bedroom_occupancy"
|
||||
|
||||
it "humidifierController subscribes to the door sensor" $
|
||||
entities humidifierController
|
||||
`shouldBe` S.singleton "binary_sensor.makuuhuone_ovi_contact"
|
||||
|
||||
drawerSpec :: Spec
|
||||
drawerSpec = describe "bedroomDrawerController" $ do
|
||||
let entity = EntityId "switch.bedroom_drawer_light_masse"
|
||||
@@ -58,36 +90,36 @@ buttonSpec = describe "bedroomButtonController" $ do
|
||||
let area = AreaId "makuuhuone"
|
||||
|
||||
it "Masse single click turns on his nightstand scene (lowest)" $
|
||||
services (runHASS bedroomButtonController [masseButton "1_short_release"])
|
||||
`shouldBe` [[activateScene "scene.makuuhuone_masse"]]
|
||||
concat (services (runHASS bedroomButtonController [masseButton "1_short_release"]))
|
||||
`shouldContain` [activateScene "scene.makuuhuone_masse"]
|
||||
|
||||
it "Masse double click turns on the middle scene" $
|
||||
services (runHASS bedroomButtonController [masseButton "1_double_press"])
|
||||
`shouldBe` [[activateScene "scene.makuuhuone_keski"]]
|
||||
concat (services (runHASS bedroomButtonController [masseButton "1_double_press"]))
|
||||
`shouldContain` [activateScene "scene.makuuhuone_keski"]
|
||||
|
||||
it "Masse long click turns on the bright scene" $
|
||||
services (runHASS bedroomButtonController [masseButton "1_long_press"])
|
||||
`shouldBe` [[activateScene "scene.makuuhuone_kirkas"]]
|
||||
concat (services (runHASS bedroomButtonController [masseButton "1_long_press"]))
|
||||
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
|
||||
|
||||
it "Masse off click turns the bedroom lights off" $
|
||||
services (runHASS bedroomButtonController [masseButton "2_short_release"])
|
||||
`shouldBe` [[light [area] False]]
|
||||
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
|
||||
`shouldContain` [light [area] Off]
|
||||
|
||||
it "Enishen single click turns on her nightstand scene (lowest)" $
|
||||
services (runHASS bedroomButtonController [enishenButton "1_short_release"])
|
||||
`shouldBe` [[activateScene "scene.makuuhuone_jemina"]]
|
||||
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
|
||||
`shouldContain` [activateScene "scene.makuuhuone_jemina"]
|
||||
|
||||
it "Enishen double click turns on the middle scene" $
|
||||
services (runHASS bedroomButtonController [enishenButton "1_double_press"])
|
||||
`shouldBe` [[activateScene "scene.makuuhuone_keski"]]
|
||||
concat (services (runHASS bedroomButtonController [enishenButton "1_double_press"]))
|
||||
`shouldContain` [activateScene "scene.makuuhuone_keski"]
|
||||
|
||||
it "Enishen long click turns on the bright scene" $
|
||||
services (runHASS bedroomButtonController [enishenButton "1_long_press"])
|
||||
`shouldBe` [[activateScene "scene.makuuhuone_kirkas"]]
|
||||
concat (services (runHASS bedroomButtonController [enishenButton "1_long_press"]))
|
||||
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
|
||||
|
||||
it "Enishen off click turns the bedroom lights off" $
|
||||
services (runHASS bedroomButtonController [enishenButton "2_short_release"])
|
||||
`shouldBe` [[light [area] False]]
|
||||
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
|
||||
`shouldContain` [light [area] Off]
|
||||
|
||||
it "ignores the initial press (scene only fires on release)" $
|
||||
services (runHASS bedroomButtonController [masseButton "1_initial_press"])
|
||||
|
||||
+30
-9
@@ -2,7 +2,7 @@
|
||||
|
||||
module BusSpec (spec) where
|
||||
|
||||
import AFRP (Request (..))
|
||||
import AFRP (Request (..), Event (..))
|
||||
import Control.Concurrent.STM
|
||||
( atomically
|
||||
, dupTChan
|
||||
@@ -10,27 +10,30 @@ import Control.Concurrent.STM
|
||||
, writeTChan
|
||||
)
|
||||
import Data.Aeson (Value (..))
|
||||
import Data.Time (UTCTime (..))
|
||||
import qualified Data.HashMap.Strict as HM
|
||||
import Data.Time (UTCTime (..), utc)
|
||||
import Data.UUID (nil)
|
||||
import HomeAssistant.Controller (HASSEff (..), Service (..), Target(..))
|
||||
import HomeAssistant.Runtime.Bus
|
||||
import HomeAssistant.Runtime.Metrics (registerAppMetrics)
|
||||
import Katip (Namespace (Namespace), runKatipContextT, Severity (..))
|
||||
import qualified System.Metrics as Metrics
|
||||
import Test.Hspec
|
||||
|
||||
spec :: Spec
|
||||
spec = describe "Bus" $ do
|
||||
it "broadcasts inbound messages to every dup'd channel in order" $ withBus InfoS $ \bus -> do
|
||||
it "broadcasts inbound messages to every dup'd channel in order" $ withTestBus $ \bus -> do
|
||||
p1 <- atomically $ dupTChan (busInbound bus)
|
||||
p2 <- atomically $ dupTChan (busInbound bus)
|
||||
atomically $ writeTChan (busInbound bus) (Number 1)
|
||||
atomically $ writeTChan (busInbound bus) (Number 2)
|
||||
atomically $ writeTChan (busInbound bus) (Event (Number 1))
|
||||
atomically $ writeTChan (busInbound bus) (Event (Number 2))
|
||||
r1 <- atomically $ (,) <$> readTChan p1 <*> readTChan p1
|
||||
r2 <- atomically $ (,) <$> readTChan p2 <*> readTChan p2
|
||||
r1 `shouldBe` (Number 1, Number 2)
|
||||
r2 `shouldBe` (Number 1, Number 2)
|
||||
r1 `shouldBe` (Event (Number 1), Event (Number 2))
|
||||
r2 `shouldBe` (Event (Number 1), Event (Number 2))
|
||||
|
||||
it "channelHassEval writes CallService to the outbound channel" $ withBus InfoS $ \bus -> do
|
||||
let req = Request (UTCTime (toEnum 0) 0) nil
|
||||
it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do
|
||||
let req = Request (UTCTime (toEnum 0) 0) utc nil
|
||||
svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"]
|
||||
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
|
||||
channelHassEval bus (CallService req svc)
|
||||
@@ -43,3 +46,21 @@ spec = describe "Bus" $ do
|
||||
a <- generateCallId gen
|
||||
b <- generateCallId gen
|
||||
(a, b) `shouldBe` (1, 2)
|
||||
|
||||
describe "recordInbound / recordOutbound" $ do
|
||||
it "increments the trigger and service counters" $ do
|
||||
store <- Metrics.newStore
|
||||
m <- registerAppMetrics store
|
||||
withBus InfoS m $ \bus -> do
|
||||
recordInbound bus
|
||||
recordInbound bus
|
||||
recordOutbound bus
|
||||
sample <- Metrics.sampleAll store
|
||||
HM.lookup "hass.trigger.in" sample `shouldBe` Just (Metrics.Counter 2)
|
||||
HM.lookup "hass.service.out" sample `shouldBe` Just (Metrics.Counter 1)
|
||||
|
||||
withTestBus :: (Bus -> IO a) -> IO a
|
||||
withTestBus action = do
|
||||
store <- Metrics.newStore
|
||||
m <- registerAppMetrics store
|
||||
withBus InfoS m action
|
||||
+29
-2
@@ -2,14 +2,19 @@
|
||||
|
||||
module ConnectionSpec (spec) where
|
||||
|
||||
import AFRP (Request(..))
|
||||
import Data.Aeson (object, (.=))
|
||||
import Data.Maybe (fromJust)
|
||||
import Data.Text (Text)
|
||||
import Data.Time (UTCTime (..), utc)
|
||||
import Data.UUID (fromString)
|
||||
import HomeAssistant.Controller (Service (..), Target(..))
|
||||
import HomeAssistant.Runtime.Connection (encodeService)
|
||||
import HomeAssistant.Runtime.Connection (encodeService, isTriggerEvent)
|
||||
import Test.Hspec
|
||||
|
||||
spec :: Spec
|
||||
spec = describe "encodeService" $ do
|
||||
spec = do
|
||||
describe "encodeService" $ do
|
||||
it "encodes a call_service message" $
|
||||
encodeService 7 (Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"])
|
||||
`shouldBe` object
|
||||
@@ -30,3 +35,25 @@ spec = describe "encodeService" $ do
|
||||
, "target" .= object ["entity_id" .= ("light.bedroom_masse" :: Text)]
|
||||
, "service_data" .= object ["brightness" .= (200 :: Int)]
|
||||
]
|
||||
|
||||
describe "isTriggerEvent" $ do
|
||||
it "is true for event frames" $
|
||||
isTriggerEvent (object ["type" .= ("event" :: Text)]) `shouldBe` True
|
||||
it "is false for result frames" $
|
||||
isTriggerEvent (object ["type" .= ("result" :: Text)]) `shouldBe` False
|
||||
it "is false when there is no type" $
|
||||
isTriggerEvent (object ["id" .= (1 :: Int)]) `shouldBe` False
|
||||
|
||||
|
||||
req :: Int -> Request
|
||||
req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
|
||||
(fromJust (fromString uuid))
|
||||
where
|
||||
pad i = replicate (12 - length (show i)) '0' <> show i
|
||||
uuid = "00000000-0000-0000-0000-" <> pad n
|
||||
|
||||
lightOn :: [Target] -> Service
|
||||
lightOn targets = Service "light" "turn_on" Nothing targets
|
||||
|
||||
lightOff :: [Target] -> Service
|
||||
lightOff targets = Service "light" "turn_off" Nothing targets
|
||||
@@ -0,0 +1,144 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module GraphingSpec (spec) where
|
||||
|
||||
import Control.Exception (SomeException, finally, try)
|
||||
import qualified Data.ByteString as BS
|
||||
import HomeAssistant.Runtime.Graphing
|
||||
( GraphSpec (..)
|
||||
, Range (..)
|
||||
, buildGraphArgs
|
||||
, graphs
|
||||
, lookupGraph
|
||||
, parseNameParam
|
||||
, parseRange
|
||||
, rangeStart
|
||||
, readProcessBytes
|
||||
)
|
||||
import qualified HomeAssistant.Runtime.Metrics as Metrics
|
||||
import System.Directory (findExecutable, getTemporaryDirectory, removeFile)
|
||||
import System.Exit (ExitCode (..))
|
||||
import System.Process (readProcessWithExitCode)
|
||||
import Test.Hspec
|
||||
import Servant.API (FromHttpApiData(..), ToHttpApiData (..))
|
||||
import HomeAssistant.Runtime.Graphing (Graph(..))
|
||||
|
||||
traffic :: GraphSpec
|
||||
traffic = case lookupGraph graphs Traffic of
|
||||
Just s -> s
|
||||
Nothing -> error "traffic graph is missing from the table"
|
||||
|
||||
spec :: Spec
|
||||
spec = do
|
||||
describe "Graph HttpApiData" $ do
|
||||
-- There's an enumerable amount of graphs, we can just enumerate through them all
|
||||
it "satisfies roundtrip property" $ do
|
||||
let modes = [minBound..maxBound]
|
||||
let got = map (parseQueryParam . toQueryParam @Graph) modes
|
||||
let wanted = map Right modes
|
||||
got `shouldBe` wanted
|
||||
describe "parseRange" $ do
|
||||
-- Fully enumerable
|
||||
it "the http-api-data satisfies roundtrip property" $ do
|
||||
let rs = [minBound..maxBound]
|
||||
let got = map (parseQueryParam . toQueryParam @Range) rs
|
||||
let wanted = map Right rs
|
||||
got `shouldBe` wanted
|
||||
it "accepts every suffix in the closed set" $
|
||||
map parseRange ["10m", "1h", "24h", "7d", "30d"]
|
||||
`shouldBe` [ Just TenMinutes
|
||||
, Just OneHour
|
||||
, Just OneDay
|
||||
, Just OneWeek
|
||||
, Just OneMonth
|
||||
]
|
||||
|
||||
it "rejects everything outside the closed set" $
|
||||
map parseRange
|
||||
[ ""
|
||||
, "1h "
|
||||
, " 1h"
|
||||
, "1h; rm -rf /"
|
||||
, "end-1h"
|
||||
, "../../etc/passwd"
|
||||
, "1y"
|
||||
, "30m"
|
||||
, "1H"
|
||||
]
|
||||
`shouldBe` replicate 9 Nothing
|
||||
|
||||
describe "rangeStart" $ do
|
||||
it "renders rrdtool end- relative starts" $
|
||||
map rangeStart [TenMinutes, OneHour, OneDay, OneWeek, OneMonth]
|
||||
`shouldBe` ["end-10m", "end-1h", "end-24h", "end-7d", "end-30d"]
|
||||
|
||||
describe "parseNameParam" $ do
|
||||
it "resolves the traffic graph only with a .png suffix" $ do
|
||||
fmap gsName (parseNameParam graphs "traffic.png") `shouldBe` Just "traffic"
|
||||
parseNameParam graphs "traffic" `shouldBe` Nothing
|
||||
|
||||
it "rejects unknown, malformed, and traversing names" $
|
||||
map (parseNameParam graphs)
|
||||
[ "unknown.png"
|
||||
, "../traffic.png"
|
||||
, "traffic.png.png"
|
||||
, ""
|
||||
, "nope"
|
||||
]
|
||||
`shouldBe` replicate 5 Nothing
|
||||
|
||||
describe "buildGraphArgs" $ do
|
||||
it "builds the traffic argv for a range" $
|
||||
buildGraphArgs "hass-controller.rrd" traffic OneHour
|
||||
`shouldBe`
|
||||
[ "graph"
|
||||
, "-"
|
||||
, "--start", "end-1h"
|
||||
, "--title", "Hass triggers in / services out"
|
||||
, "--width", "800"
|
||||
, "--height", "250"
|
||||
, "--imgformat", "PNG"
|
||||
, "DEF:in_raw=hass-controller.rrd:hass_trigger_in:AVERAGE"
|
||||
, "CDEF:in=in_raw,60.0,*"
|
||||
, "DEF:out_raw=hass-controller.rrd:hass_service_out:AVERAGE"
|
||||
, "CDEF:out=out_raw,60.0,*"
|
||||
, "LINE2:in#0066cc:Triggers in/min"
|
||||
, "LINE2:out#cc0000:Service calls out/min"
|
||||
]
|
||||
|
||||
describe "end-to-end (rrdtool-gated)" $ do
|
||||
it "renders a PNG for the traffic graph" $ do
|
||||
mRrdtool <- findExecutable "rrdtool"
|
||||
case mRrdtool of
|
||||
Nothing -> pendingWith "rrdtool not on PATH"
|
||||
Just rrdtool -> do
|
||||
tmp <- getTemporaryDirectory
|
||||
let rrdPath = tmp ++ "/hass-controller-graph-test.rrd"
|
||||
cleanup = try (removeFile rrdPath) :: IO (Either SomeException ())
|
||||
schema =
|
||||
[ ("hass_trigger_in", Metrics.Derive)
|
||||
, ("hass_service_out", Metrics.Derive)
|
||||
]
|
||||
pngMagic = BS.pack [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
|
||||
_ <- cleanup
|
||||
( do
|
||||
(createCode, _, _) <-
|
||||
readProcessWithExitCode rrdtool (Metrics.buildCreateArgs rrdPath 10 schema) ""
|
||||
createCode `shouldBe` ExitSuccess
|
||||
(updateCode, _, _) <-
|
||||
readProcessWithExitCode
|
||||
rrdtool
|
||||
(Metrics.buildUpdateArgs
|
||||
rrdPath
|
||||
["hass_trigger_in", "hass_service_out"]
|
||||
[Just 5, Just 3])
|
||||
""
|
||||
updateCode `shouldBe` ExitSuccess
|
||||
(code, out, _) <- readProcessBytes rrdtool (buildGraphArgs rrdPath traffic OneHour)
|
||||
code `shouldBe` ExitSuccess
|
||||
out `shouldSatisfy` BS.isPrefixOf pngMagic
|
||||
)
|
||||
`finally` cleanup
|
||||
|
||||
|
||||
|
||||
+6
-4
@@ -1,20 +1,22 @@
|
||||
module Main (main) where
|
||||
|
||||
import Test.Hspec (hspec)
|
||||
import qualified AFRPLawsSpec
|
||||
import qualified AFRPSpec
|
||||
import qualified BackoffProp
|
||||
import qualified BedroomSpec
|
||||
import qualified BusSpec
|
||||
import qualified ConnectionSpec
|
||||
import qualified GraphingSpec
|
||||
import qualified MetricsSpec
|
||||
import qualified RuntimeSpec
|
||||
import qualified SupervisorSpec
|
||||
|
||||
main :: IO ()
|
||||
main = hspec $ do
|
||||
AFRPLawsSpec.spec
|
||||
AFRPSpec.spec
|
||||
BedroomSpec.spec
|
||||
BusSpec.spec
|
||||
ConnectionSpec.spec
|
||||
GraphingSpec.spec
|
||||
MetricsSpec.spec
|
||||
RuntimeSpec.spec
|
||||
SupervisorSpec.spec
|
||||
BackoffProp.spec
|
||||
@@ -0,0 +1,226 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module MetricsSpec (spec) where
|
||||
|
||||
import Data.HashMap.Strict (HashMap)
|
||||
import qualified Data.HashMap.Strict as HM
|
||||
import Data.List (isPrefixOf)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import HomeAssistant.Runtime.Metrics
|
||||
( DsType (..)
|
||||
, DsSpec (..)
|
||||
, dsTypeOf
|
||||
, sanitizeName
|
||||
, buildSchema
|
||||
, buildCreateArgs
|
||||
, buildUpdateArgs
|
||||
, ensureRrd
|
||||
, sampleAndUpdate
|
||||
, parseInfoDs
|
||||
, schemaMatches
|
||||
, AppMetrics (..)
|
||||
, registerAppMetrics
|
||||
)
|
||||
import qualified System.Metrics as M (Value (..))
|
||||
import Test.Hspec
|
||||
import Control.Exception (try, SomeException, finally)
|
||||
import Control.Monad (forM_)
|
||||
import System.Directory (findExecutable, getTemporaryDirectory, listDirectory, removeFile)
|
||||
import System.Exit (ExitCode (ExitSuccess))
|
||||
import System.Process (readProcessWithExitCode)
|
||||
import qualified System.Metrics as Metrics
|
||||
import qualified System.Metrics.Counter as Counter
|
||||
import qualified System.Metrics.Gauge as Gauge
|
||||
|
||||
spec :: Spec
|
||||
spec = do
|
||||
describe "dsTypeOf" $ do
|
||||
it "maps Counter to Derive" $
|
||||
dsTypeOf (M.Counter 1000) `shouldBe` Just Derive
|
||||
|
||||
it "maps Gauge to Gauge" $
|
||||
dsTypeOf (M.Gauge 500) `shouldBe` Just Gauge
|
||||
|
||||
it "maps Label to Nothing" $
|
||||
dsTypeOf (M.Label "hello") `shouldBe` Nothing
|
||||
|
||||
describe "sanitizeName" $ do
|
||||
it "replaces dots with underscores for short names" $
|
||||
sanitizeName ("rts.gc.cpu_ms" :: Text) `shouldBe` "rts_gc_cpu_ms"
|
||||
|
||||
it "shortens names longer than 19 chars to 15 chars + _ + 3 hex" $ do
|
||||
let result = sanitizeName ("rts.gc.par_balanced_bytes_copied" :: Text)
|
||||
length result `shouldBe` 19
|
||||
take 15 result `shouldBe` "rts_gc_par_bala"
|
||||
drop 15 result `shouldBe` "_" ++ drop 16 result
|
||||
|
||||
it "is deterministic (same input -> same output)" $
|
||||
sanitizeName ("rts.gc.peak_megabytes_allocated" :: Text)
|
||||
`shouldBe` sanitizeName ("rts.gc.peak_megabytes_allocated" :: Text)
|
||||
|
||||
describe "buildSchema" $ do
|
||||
it "builds sorted DsSpecs from counters and gauges, skipping labels" $
|
||||
let sample :: HashMap Text M.Value
|
||||
sample = HM.fromList
|
||||
[ ("x.allocated", M.Counter 1000)
|
||||
, ("a.bytes_used", M.Gauge 500)
|
||||
, ("c.label_thing", M.Label "irrelevant")
|
||||
]
|
||||
in buildSchema sample `shouldBe`
|
||||
[ DsSpec "a.bytes_used" "a_bytes_used" Gauge
|
||||
, DsSpec "x.allocated" "x_allocated" Derive
|
||||
]
|
||||
|
||||
it "produces dsName <= 19 chars for long ekg GC metric names" $
|
||||
let sample :: HashMap Text M.Value
|
||||
sample = HM.fromList
|
||||
[ ("rts.gc.par_balanced_bytes_copied", M.Gauge 1)
|
||||
, ("rts.gc.peak_megabytes_allocated", M.Gauge 2)
|
||||
, ("rts.gc.cumulative_bytes_used", M.Counter 3)
|
||||
]
|
||||
in map (length . dsName) (buildSchema sample) `shouldSatisfy` all (<= 19)
|
||||
|
||||
describe "buildCreateArgs" $ do
|
||||
it "builds create argv with mixed DERIVE and GAUGE DSes and RRAs" $
|
||||
buildCreateArgs "test.rrd" 10
|
||||
[ ("ds1", Derive)
|
||||
, ("ds2", Gauge)
|
||||
]
|
||||
`shouldBe`
|
||||
[ "create"
|
||||
, "test.rrd"
|
||||
, "--step"
|
||||
, "10"
|
||||
, "DS:ds1:DERIVE:20:0:U"
|
||||
, "DS:ds2:GAUGE:20:0:U"
|
||||
, "RRA:AVERAGE:0.5:1:6000"
|
||||
, "RRA:MAX:0.5:1:6000"
|
||||
, "RRA:AVERAGE:0.5:360:1680"
|
||||
, "RRA:MAX:0.5:360:1680"
|
||||
]
|
||||
|
||||
describe "buildUpdateArgs" $ do
|
||||
it "builds update argv with numeric values" $
|
||||
buildUpdateArgs "test.rrd" ["ds1", "ds2"] [Just 100, Just 200]
|
||||
`shouldBe`
|
||||
[ "update"
|
||||
, "test.rrd"
|
||||
, "--template"
|
||||
, "ds1:ds2"
|
||||
, "N:100:200"
|
||||
]
|
||||
|
||||
it "renders Nothing as U (unknown)" $
|
||||
buildUpdateArgs "test.rrd" ["ds1", "ds2"] [Just 100, Nothing]
|
||||
`shouldBe`
|
||||
[ "update"
|
||||
, "test.rrd"
|
||||
, "--template"
|
||||
, "ds1:ds2"
|
||||
, "N:100:U"
|
||||
]
|
||||
|
||||
it "renders all-Nothing as all-U" $
|
||||
buildUpdateArgs "test.rrd" ["ds1"] [Nothing]
|
||||
`shouldBe`
|
||||
[ "update"
|
||||
, "test.rrd"
|
||||
, "--template"
|
||||
, "ds1"
|
||||
, "N:U"
|
||||
]
|
||||
|
||||
describe "parseInfoDs" $ do
|
||||
it "extracts DS names and types from rrdtool info output" $
|
||||
let info = unlines
|
||||
[ "filename = \"test.rrd\""
|
||||
, "step = 10"
|
||||
, "ds[foo].index = 0"
|
||||
, "ds[foo].type = \"DERIVE\""
|
||||
, "ds[bar].type = \"GAUGE\""
|
||||
, "rra[0].cf = \"AVERAGE\""
|
||||
]
|
||||
in parseInfoDs info `shouldBe` [("foo", Derive), ("bar", Gauge)]
|
||||
|
||||
it "ignores lines that are not ds type declarations" $
|
||||
parseInfoDs "step = 10\nrra[0].cf = \"AVERAGE\"\n" `shouldBe` []
|
||||
|
||||
describe "schemaMatches" $ do
|
||||
let ds name ty = DsSpec (T.pack name) name ty
|
||||
it "is true for identical schemas regardless of order" $
|
||||
schemaMatches [ds "b" Gauge, ds "a" Derive] [("a", Derive), ("b", Gauge)]
|
||||
`shouldBe` True
|
||||
|
||||
it "is false when the derived schema has an added DS" $
|
||||
schemaMatches [ds "a" Derive, ds "b" Gauge] [("a", Derive)]
|
||||
`shouldBe` False
|
||||
|
||||
it "is false when the derived schema has a removed DS" $
|
||||
schemaMatches [ds "a" Derive] [("a", Derive), ("b", Gauge)]
|
||||
`shouldBe` False
|
||||
|
||||
it "is false when a DS type changed" $
|
||||
schemaMatches [ds "a" Derive] [("a", Gauge)]
|
||||
`shouldBe` False
|
||||
|
||||
describe "registerAppMetrics" $ do
|
||||
it "registers both counters with the store" $ do
|
||||
store <- Metrics.newStore
|
||||
m <- registerAppMetrics store
|
||||
Counter.inc (amTriggersIn m)
|
||||
Counter.inc (amServicesOut m)
|
||||
sample <- Metrics.sampleAll store
|
||||
HM.lookup "hass.trigger.in" sample `shouldBe` Just (M.Counter 1)
|
||||
HM.lookup "hass.service.out" sample `shouldBe` Just (M.Counter 1)
|
||||
|
||||
describe "end-to-end (rrdtool-gated)" $ do
|
||||
it "creates an rrd, samples, and updates it" $ do
|
||||
mRrdtool <- findExecutable "rrdtool"
|
||||
case mRrdtool of
|
||||
Nothing -> pendingWith "rrdtool not on PATH"
|
||||
Just rrdtool -> do
|
||||
store <- Metrics.newStore
|
||||
c <- Metrics.createCounter "test.counter" store
|
||||
g <- Metrics.createGauge "test.gauge" store
|
||||
Counter.inc c
|
||||
Gauge.set g 42
|
||||
tmp <- getTemporaryDirectory
|
||||
let rrdPath = tmp ++ "/hass-controller-metrics-test.rrd"
|
||||
_ <- try (removeFile rrdPath) :: IO (Either SomeException ())
|
||||
schema <- buildSchema <$> Metrics.sampleAll store
|
||||
ensureRrd rrdtool rrdPath schema
|
||||
sampleAndUpdate store rrdtool rrdPath schema
|
||||
(rc, out, _) <- readProcessWithExitCode rrdtool ["fetch", rrdPath, "AVERAGE"] ""
|
||||
rc `shouldBe` ExitSuccess
|
||||
length out `shouldSatisfy` (> 0)
|
||||
_ <- try (removeFile rrdPath) :: IO (Either SomeException ())
|
||||
return ()
|
||||
|
||||
it "backs up and recreates the rrd when the schema changes" $ do
|
||||
mRrdtool <- findExecutable "rrdtool"
|
||||
case mRrdtool of
|
||||
Nothing -> pendingWith "rrdtool not on PATH"
|
||||
Just rrdtool -> do
|
||||
tmp <- getTemporaryDirectory
|
||||
let rrdPath = tmp ++ "/hass-controller-schema-change-test.rrd"
|
||||
bakPrefix = "hass-controller-schema-change-test.rrd.bak-"
|
||||
base = [ DsSpec "a" "a" Derive, DsSpec "b" "b" Gauge ]
|
||||
expanded = base ++ [ DsSpec "c" "c" Derive ]
|
||||
clean = do
|
||||
stale <- filter (isPrefixOf bakPrefix) <$> listDirectory tmp
|
||||
forM_ (rrdPath : map (\f -> tmp ++ "/" ++ f) stale) $ \f ->
|
||||
try (removeFile f) :: IO (Either SomeException ())
|
||||
clean
|
||||
( do
|
||||
ensureRrd rrdtool rrdPath base
|
||||
ensureRrd rrdtool rrdPath base
|
||||
noBackups <- filter (isPrefixOf bakPrefix) <$> listDirectory tmp
|
||||
noBackups `shouldBe` []
|
||||
ensureRrd rrdtool rrdPath expanded
|
||||
backups <- filter (isPrefixOf bakPrefix) <$> listDirectory tmp
|
||||
length backups `shouldBe` 1
|
||||
(rc, out, _) <- readProcessWithExitCode rrdtool ["info", rrdPath] ""
|
||||
rc `shouldBe` ExitSuccess
|
||||
out `shouldContain` "ds[c].type"
|
||||
) `finally` clean
|
||||
+32
-7
@@ -1,9 +1,32 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module RuntimeSpec (spec) where
|
||||
|
||||
import Control.Concurrent (threadDelay)
|
||||
import Control.Concurrent.Async (async, cancel, race, waitCatch)
|
||||
import Control.Exception (bracket)
|
||||
import Control.Monad (forever)
|
||||
import Control.Monad.IO.Class (liftIO)
|
||||
import HomeAssistant.Runtime.Supervisor (supervised)
|
||||
import Katip (LogEnv, closeScribes, initLogEnv, runKatipContextT)
|
||||
import Test.Hspec
|
||||
|
||||
spec :: Spec
|
||||
spec = pure ()
|
||||
spec = describe "supervised" $ do
|
||||
it "propagates ThreadKilled instead of retrying" $
|
||||
withTestLogEnv $ \le -> do
|
||||
worker <- async $ runKatipContextT le () mempty $
|
||||
supervised "test" (liftIO (forever (threadDelay 100000)))
|
||||
threadDelay 200000
|
||||
cancel worker
|
||||
result <- race (threadDelay 5000000) (waitCatch worker)
|
||||
case result of
|
||||
Left () -> expectationFailure
|
||||
"supervised retried on ThreadKilled (process would hang)"
|
||||
Right _ -> pure ()
|
||||
|
||||
withTestLogEnv :: (LogEnv -> IO a) -> IO a
|
||||
withTestLogEnv = bracket (initLogEnv "test" "test") closeScribes
|
||||
|
||||
-- I'm commenting out the test as that specific controller
|
||||
-- was just a dummy for seeing how the data flows (dead code)
|
||||
@@ -11,14 +34,14 @@ spec = pure ()
|
||||
--
|
||||
-- spec :: Spec
|
||||
-- spec = describe "runController" $ do
|
||||
-- it "feeds inbound events through the machine and forwards service calls" $ withBus InfoS $ \bus -> do
|
||||
-- it "feeds inbound events through the machine and forwards service calls" $ withBus severity appMetrics $ \bus -> do
|
||||
-- _ <- async (runController bus (Controller "test" lightController True))
|
||||
-- putStrLn "Before the delay"
|
||||
-- threadDelay 100000 -- let the controller dup its inbound channel
|
||||
-- putStrLn "After the delay"
|
||||
-- atomically $ writeTChan (busInbound bus) (doorEvent "on") -- initial value: no change event
|
||||
-- atomically $ writeTChan (busInbound bus) (doorEvent "off") -- door closes: lights on
|
||||
-- atomically $ writeTChan (busInbound bus) (doorEvent "on") -- door opens: lights off
|
||||
-- atomically $ writeTChan (busInbound bus) (Event (doorEvent "on")) -- initial value: no change event
|
||||
-- atomically $ writeTChan (busInbound bus) (Event (doorEvent "off")) -- door closes: lights on
|
||||
-- atomically $ writeTChan (busInbound bus) (Event (doorEvent "on")) -- door opens: lights off
|
||||
-- putStrLn "After the writes"
|
||||
-- Right (_, svc1) <- boundedRead (busOutbound bus)
|
||||
-- Right (_, svc2) <- boundedRead (busOutbound bus)
|
||||
@@ -32,9 +55,11 @@ spec = pure ()
|
||||
-- doorEvent :: Text -> Value
|
||||
-- doorEvent state = object
|
||||
-- [ "event" .= object
|
||||
-- [ "data" .= object
|
||||
-- [ "variables" .= object
|
||||
-- [ "trigger" .= object
|
||||
-- [ "entity_id" .= ("binary_sensor.makuuhuone_ovi_contact" :: Text)
|
||||
-- , "new_state" .= object ["state" .= state]
|
||||
-- , "to_state" .= object ["state" .= state]
|
||||
-- ]
|
||||
-- ]
|
||||
-- ]
|
||||
-- ]
|
||||
@@ -1,73 +0,0 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module SupervisorSpec (spec) where
|
||||
|
||||
import Control.Concurrent (newEmptyMVar, putMVar, readMVar, threadDelay)
|
||||
import Control.Concurrent.Async (async, cancel, poll, waitCatch)
|
||||
import Control.Exception (fromException)
|
||||
import Control.Exception.Annotated (AnnotatedException (..), throw)
|
||||
import Control.Monad (forever)
|
||||
import Data.IORef (atomicModifyIORef', newIORef, readIORef)
|
||||
import Data.Maybe (isJust, isNothing)
|
||||
import HomeAssistant.Runtime.Supervisor
|
||||
import Test.Hspec
|
||||
|
||||
tinyBackoff :: Backoff
|
||||
tinyBackoff = Backoff 0.001 0.002 0.001
|
||||
|
||||
spec :: Spec
|
||||
spec = describe "supervised" $ do
|
||||
it "restarts a crashing action until it stays up" $ do
|
||||
counter <- newIORef (0 :: Int)
|
||||
up <- newEmptyMVar
|
||||
let action = do
|
||||
n <- atomicModifyIORef' counter (\c -> (c + 1, c + 1))
|
||||
if n < 3
|
||||
then ioError (userError "boom")
|
||||
else do putMVar up (); forever (threadDelay 1000000)
|
||||
sup <- async (supervised "test" tinyBackoff action)
|
||||
readMVar up
|
||||
threadDelay 50000
|
||||
status <- poll sup
|
||||
isNothing status `shouldBe` True
|
||||
readIORef counter `shouldReturn` 3
|
||||
cancel sup
|
||||
|
||||
it "rethrows Fatal instead of restarting" $ do
|
||||
counter <- newIORef (0 :: Int)
|
||||
let action = do
|
||||
_ <- atomicModifyIORef' counter (\c -> (c + 1, c + 1))
|
||||
throw (Fatal "auth_invalid")
|
||||
sup <- async (supervised "test" tinyBackoff action)
|
||||
res <- waitCatch sup
|
||||
case res of
|
||||
Left se -> case fromException se :: Maybe (AnnotatedException Fatal) of
|
||||
Just _ -> pure ()
|
||||
Nothing -> expectationFailure "expected Fatal to propagate"
|
||||
Right _ -> expectationFailure "supervised returned"
|
||||
threadDelay 50000
|
||||
readIORef counter `shouldReturn` 1
|
||||
|
||||
it "does not restart on async exceptions" $ do
|
||||
counter <- newIORef (0 :: Int)
|
||||
let action = do
|
||||
_ <- atomicModifyIORef' counter (\c -> (c + 1, c + 1))
|
||||
forever (threadDelay 1000000)
|
||||
sup <- async (supervised "test" tinyBackoff action)
|
||||
threadDelay 100000
|
||||
cancel sup
|
||||
threadDelay 100000
|
||||
readIORef counter `shouldReturn` 1
|
||||
status <- poll sup
|
||||
isJust status `shouldBe` True
|
||||
|
||||
describe "nextAttempt" $ do
|
||||
it "resets after a quiet period" $
|
||||
nextAttempt tinyBackoff 0.001 5 `shouldBe` 1
|
||||
it "increments otherwise" $
|
||||
nextAttempt tinyBackoff 0.0005 5 `shouldBe` 6
|
||||
|
||||
describe "backoffDelay" $ do
|
||||
it "starts at base" $ backoffDelay tinyBackoff 1 `shouldBe` 0.001
|
||||
it "doubles" $ backoffDelay tinyBackoff 2 `shouldBe` 0.002
|
||||
it "clamps at cap" $ backoffDelay tinyBackoff 3 `shouldBe` 0.002
|
||||
+21
-13
@@ -14,13 +14,13 @@ module Support
|
||||
import Control.Monad.Fix (MonadFix (..))
|
||||
import Data.Aeson (Value, object, (.=))
|
||||
import qualified Data.Text as T
|
||||
import Data.Time (UTCTime (..))
|
||||
import Data.Time (UTCTime (..), utc)
|
||||
import Data.UUID (nil)
|
||||
import AFRP (Mealy (..), Request (..))
|
||||
import AFRP (Mealy (..), Request (..), stepAuto)
|
||||
import HomeAssistant.Controller (HASSEff (..), Service)
|
||||
|
||||
fakeRequest :: Request
|
||||
fakeRequest = Request (sec 0) nil
|
||||
fakeRequest = Request (sec 0) utc nil
|
||||
|
||||
sec :: Integer -> UTCTime
|
||||
sec n = UTCTime (toEnum 0) (fromIntegral n)
|
||||
@@ -49,33 +49,41 @@ interp (Trace _ _) = pure ()
|
||||
|
||||
-- | Run a HASS arrow over a list of inputs, collecting per-step emitted services.
|
||||
runHASS :: Mealy HASSEff a b -> [a] -> [(b, [Service])]
|
||||
runHASS _ [] = []
|
||||
runHASS m (a : as) =
|
||||
case runAcc (runMealy m interp fakeRequest a) [] of
|
||||
((b, m'), svcs) -> (b, svcs) : runHASS m' as
|
||||
runHASS m = go (runMealy m interp)
|
||||
where
|
||||
go _ [] = []
|
||||
go w (a : as) =
|
||||
case runAcc (stepAuto w fakeRequest a) [] of
|
||||
((b, w'), svcs) -> (b, svcs) : go w' as
|
||||
|
||||
services :: [(b, [Service])] -> [[Service]]
|
||||
services = map snd
|
||||
|
||||
-- | Build a state-change event payload matching `entityChangeEvent'` / `entityBool'` lenses.
|
||||
-- | Build a state-trigger payload matching `entityChangeEvent'` / `entityBool'`
|
||||
-- lenses. The subscribe_trigger websocket event wraps the trigger datum under
|
||||
-- `event.variables.trigger`, with `entity_id` and `to_state.state` fields.
|
||||
stateEvent :: T.Text -> T.Text -> Value
|
||||
stateEvent entityId state = object
|
||||
[ "event" .= object
|
||||
[ "data" .= object
|
||||
[ "variables" .= object
|
||||
[ "trigger" .= object
|
||||
[ "entity_id" .= entityId
|
||||
, "new_state" .= object [ "state" .= state ]
|
||||
, "to_state" .= object [ "state" .= state ]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
-- | Build an Ikea button event payload matching `ikeaQuickButton` lenses.
|
||||
-- | Build an Ikea button trigger payload matching `ikeaQuickButton` lenses.
|
||||
buttonEvent :: T.Text -> T.Text -> Value
|
||||
buttonEvent entityId eventType = object
|
||||
[ "event" .= object
|
||||
[ "data" .= object
|
||||
[ "variables" .= object
|
||||
[ "trigger" .= object
|
||||
[ "entity_id" .= entityId
|
||||
, "new_state" .= object
|
||||
, "to_state" .= object
|
||||
[ "attributes" .= object [ "event_type" .= eventType ] ]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
Reference in new issue
Block a user