Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6bcab1a0d8 | ||
|
|
cceddad037 | ||
|
|
c75fc1a7b9 | ||
|
|
1098be227d | ||
|
|
a427acd6ed | ||
|
|
aee34f4e14 | ||
|
|
526710ef71 | ||
|
|
c2425e8fb0 | ||
|
|
a7a11e96b7 | ||
|
|
adce7c8427 | ||
|
|
9e00aeb6a2 | ||
|
|
b643fe55b1 | ||
|
|
138b62c54a | ||
|
|
889091d321 | ||
|
|
c2426dec3d | ||
|
|
ad023a1ba2 | ||
|
|
7ce994e814 | ||
|
|
fefeae6301 | ||
|
|
fcaccfdeb0 |
No files matched your search
@@ -10,6 +10,7 @@ reactive programming (AFRP). Haskell, built with cabal.
|
|||||||
- Vertical modules: split by feature/concept, not by layer.
|
- Vertical modules: split by feature/concept, not by layer.
|
||||||
- Comments are minimal. They describe the contract, not the implementation,
|
- Comments are minimal. They describe the contract, not the implementation,
|
||||||
and should stay stable as the implementation changes.
|
and should stay stable as the implementation changes.
|
||||||
|
- Never ever log directly to stdout via `putStr` and friends. Always use proper logging functions
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
|
|||||||
@@ -4,5 +4,4 @@ import qualified HomeAssistant.Runtime (defaultMain)
|
|||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = do
|
main = do
|
||||||
putStrLn "Hello, Haskell!"
|
|
||||||
HomeAssistant.Runtime.defaultMain
|
HomeAssistant.Runtime.defaultMain
|
||||||
+11
-9
@@ -1,7 +1,8 @@
|
|||||||
{ mkDerivation, aeson, annotated-exception, async, base, bytestring
|
{ mkDerivation, aeson, annotated-exception, async, base, bytestring
|
||||||
, cereal, cereal-conduit, conduit, containers, directory, ekg-core
|
, cereal, cereal-conduit, cereal-text, conduit, containers
|
||||||
, exceptions, filepath, hedgehog, hspec, hspec-hedgehog, http-media
|
, data-default, directory, ekg-core, exceptions, filepath, hedgehog
|
||||||
, http-types, katip, lens, lens-aeson, lib, network, process, retry
|
, hspec, hspec-hedgehog, http-media, http-types, katip, lens
|
||||||
|
, lens-aeson, lib, libsystemd-journal, network, process, retry
|
||||||
, servant, servant-server, stm, temporary, text, time, unliftio
|
, servant, servant-server, stm, temporary, text, time, unliftio
|
||||||
, unordered-containers, uuid, wai, warp, websockets
|
, unordered-containers, uuid, wai, warp, websockets
|
||||||
}:
|
}:
|
||||||
@@ -13,16 +14,17 @@ mkDerivation {
|
|||||||
isExecutable = true;
|
isExecutable = true;
|
||||||
libraryHaskellDepends = [
|
libraryHaskellDepends = [
|
||||||
aeson annotated-exception async base bytestring cereal
|
aeson annotated-exception async base bytestring cereal
|
||||||
cereal-conduit conduit containers directory ekg-core exceptions
|
cereal-conduit cereal-text conduit containers data-default
|
||||||
filepath http-media http-types katip lens lens-aeson network
|
directory ekg-core exceptions filepath http-media http-types katip
|
||||||
process retry servant servant-server stm text time unliftio
|
lens lens-aeson libsystemd-journal network process retry servant
|
||||||
unordered-containers uuid wai warp websockets
|
servant-server stm text time unliftio unordered-containers uuid wai
|
||||||
|
warp websockets
|
||||||
];
|
];
|
||||||
executableHaskellDepends = [ base ];
|
executableHaskellDepends = [ base ];
|
||||||
testHaskellDepends = [
|
testHaskellDepends = [
|
||||||
aeson annotated-exception async base bytestring cereal containers
|
aeson annotated-exception async base bytestring cereal containers
|
||||||
directory ekg-core hedgehog hspec hspec-hedgehog katip process
|
data-default directory ekg-core hedgehog hspec hspec-hedgehog katip
|
||||||
servant stm temporary text time unordered-containers uuid
|
process servant stm temporary text time unordered-containers uuid
|
||||||
];
|
];
|
||||||
license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause";
|
license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause";
|
||||||
mainProgram = "home-assistant-controller";
|
mainProgram = "home-assistant-controller";
|
||||||
|
|||||||
@@ -62,11 +62,22 @@ library
|
|||||||
exposed-modules: AFRP
|
exposed-modules: AFRP
|
||||||
, HomeAssistant.Controller
|
, HomeAssistant.Controller
|
||||||
, HomeAssistant.Controller.Bedroom
|
, HomeAssistant.Controller.Bedroom
|
||||||
, HomeAssistant.Controller.Hallway
|
|
||||||
, HomeAssistant.Controller.Kitchen
|
|
||||||
, HomeAssistant.Controller.Children
|
, HomeAssistant.Controller.Children
|
||||||
|
, HomeAssistant.Controller.Door
|
||||||
|
, HomeAssistant.Controller.Effect
|
||||||
|
, HomeAssistant.Controller.Entity
|
||||||
|
, HomeAssistant.Controller.Hallway
|
||||||
|
, HomeAssistant.Controller.Ikea
|
||||||
|
, HomeAssistant.Controller.Kitchen
|
||||||
|
, HomeAssistant.Controller.Light.Command
|
||||||
|
, HomeAssistant.Controller.Light.Mode
|
||||||
|
, HomeAssistant.Controller.Light.Observation
|
||||||
, HomeAssistant.Controller.Livingroom
|
, HomeAssistant.Controller.Livingroom
|
||||||
|
, HomeAssistant.Controller.Presence
|
||||||
, HomeAssistant.Controller.Ruuvi
|
, HomeAssistant.Controller.Ruuvi
|
||||||
|
, HomeAssistant.Controller.Scene
|
||||||
|
, HomeAssistant.Controller.Service
|
||||||
|
, HomeAssistant.Controller.Switch
|
||||||
, HomeAssistant.Runtime
|
, HomeAssistant.Runtime
|
||||||
, HomeAssistant.Runtime.Bus
|
, HomeAssistant.Runtime.Bus
|
||||||
, HomeAssistant.Runtime.Connection
|
, HomeAssistant.Runtime.Connection
|
||||||
@@ -76,6 +87,7 @@ library
|
|||||||
, HomeAssistant.Runtime.Supervisor
|
, HomeAssistant.Runtime.Supervisor
|
||||||
, HomeAssistant.Runtime.RateLimit
|
, HomeAssistant.Runtime.RateLimit
|
||||||
, HttpServer
|
, HttpServer
|
||||||
|
, Katip.Scribes.Journal
|
||||||
|
|
||||||
-- Modules included in this library but not exported.
|
-- Modules included in this library but not exported.
|
||||||
-- other-modules:
|
-- other-modules:
|
||||||
@@ -107,7 +119,9 @@ library
|
|||||||
, process
|
, process
|
||||||
, directory
|
, directory
|
||||||
, cereal
|
, cereal
|
||||||
|
, cereal-text
|
||||||
, containers
|
, containers
|
||||||
|
, data-default
|
||||||
, filepath
|
, filepath
|
||||||
, conduit
|
, conduit
|
||||||
, cereal-conduit
|
, cereal-conduit
|
||||||
@@ -117,6 +131,7 @@ library
|
|||||||
, warp
|
, warp
|
||||||
, wai
|
, wai
|
||||||
, retry
|
, retry
|
||||||
|
, libsystemd-journal
|
||||||
|
|
||||||
-- Directories containing source files.
|
-- Directories containing source files.
|
||||||
hs-source-dirs: src
|
hs-source-dirs: src
|
||||||
@@ -169,6 +184,7 @@ test-suite home-assistant-controller-test
|
|||||||
, MetricsSpec
|
, MetricsSpec
|
||||||
, RuntimeSpec
|
, RuntimeSpec
|
||||||
, Support
|
, Support
|
||||||
|
, ControllerSpec
|
||||||
|
|
||||||
-- LANGUAGE extensions used by modules in this package.
|
-- LANGUAGE extensions used by modules in this package.
|
||||||
-- other-extensions:
|
-- other-extensions:
|
||||||
@@ -187,6 +203,7 @@ test-suite home-assistant-controller-test
|
|||||||
base ^>=4.20.2.0,
|
base ^>=4.20.2.0,
|
||||||
home-assistant-controller,
|
home-assistant-controller,
|
||||||
bytestring,
|
bytestring,
|
||||||
|
data-default,
|
||||||
hspec,
|
hspec,
|
||||||
stm,
|
stm,
|
||||||
servant,
|
servant,
|
||||||
|
|||||||
+13
-5
@@ -42,6 +42,7 @@ module AFRP
|
|||||||
, load
|
, load
|
||||||
, stepAuto
|
, stepAuto
|
||||||
, stepAutoSerializing
|
, stepAutoSerializing
|
||||||
|
, snapshot
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Control.Category (Category(..), (>>>))
|
import Control.Category (Category(..), (>>>))
|
||||||
@@ -55,7 +56,7 @@ import qualified Data.Set as S
|
|||||||
import qualified Data.Text as T
|
import qualified Data.Text as T
|
||||||
import Data.Serialize (Get, Putter, Serialize (put), runGet, get)
|
import Data.Serialize (Get, Putter, Serialize (put), runGet, get)
|
||||||
import qualified Data.ByteString as B
|
import qualified Data.ByteString as B
|
||||||
import Control.Exception (IOException, handle, throwIO)
|
import Control.Exception (IOException)
|
||||||
import System.IO.Error (isDoesNotExistError)
|
import System.IO.Error (isDoesNotExistError)
|
||||||
import GHC.Generics (Generic)
|
import GHC.Generics (Generic)
|
||||||
import Data.Sequence (Seq, (|>))
|
import Data.Sequence (Seq, (|>))
|
||||||
@@ -64,6 +65,8 @@ import Control.Monad.IO.Class (MonadIO, liftIO)
|
|||||||
import Conduit (ConduitT, (.|))
|
import Conduit (ConduitT, (.|))
|
||||||
import qualified Data.Conduit.Cereal as CC
|
import qualified Data.Conduit.Cereal as CC
|
||||||
import qualified Conduit as C
|
import qualified Conduit as C
|
||||||
|
import Control.Monad.Catch (MonadCatch, handle)
|
||||||
|
import Control.Exception.Annotated (throw)
|
||||||
|
|
||||||
|
|
||||||
data Codec s = Codec { getter :: !(Get s), putter :: !(Putter s) }
|
data Codec s = Codec { getter :: !(Get s), putter :: !(Putter s) }
|
||||||
@@ -246,13 +249,13 @@ save path s
|
|||||||
isDirty _ = False
|
isDirty _ = False
|
||||||
|
|
||||||
|
|
||||||
load :: forall m a b. FilePath -> Auto m a b -> IO (DecodedAuto m a b)
|
load :: forall eff a b m. (MonadCatch m, MonadIO m) => FilePath -> Auto eff a b -> m (DecodedAuto eff a b)
|
||||||
load path a = handle defaultOnMissingFile (flip deserialize a <$> B.readFile path)
|
load path a = handle defaultOnMissingFile (flip deserialize a <$> liftIO (B.readFile path))
|
||||||
where
|
where
|
||||||
defaultOnMissingFile :: IOException -> IO (DecodedAuto m a b)
|
defaultOnMissingFile :: IOException -> m (DecodedAuto eff a b)
|
||||||
defaultOnMissingFile e
|
defaultOnMissingFile e
|
||||||
| isDoesNotExistError e = pure $ FailDecode "State doesn't exist yet" a
|
| isDoesNotExistError e = pure $ FailDecode "State doesn't exist yet" a
|
||||||
| otherwise = throwIO e
|
| otherwise = throw e
|
||||||
|
|
||||||
-- | The set of entity ids an arrow subscribes to. Static: it does not
|
-- | The set of entity ids an arrow subscribes to. Static: it does not
|
||||||
-- change as the machine steps, so the runtime can read it once to build
|
-- change as the machine steps, so the runtime can read it once to build
|
||||||
@@ -325,6 +328,11 @@ hold def = mapAccum step def id
|
|||||||
Tick -> prev
|
Tick -> prev
|
||||||
Event new -> new
|
Event new -> new
|
||||||
|
|
||||||
|
snapshot :: (Serialize a, Eq a) => a -> Mealy m (Event (), a) a
|
||||||
|
snapshot def = mapAccum step def id
|
||||||
|
where
|
||||||
|
step prev (Tick, _) = prev
|
||||||
|
step _prev (Event _, a) = a
|
||||||
|
|
||||||
events :: Mealy eff (Event a) (Either () a)
|
events :: Mealy eff (Event a) (Either () a)
|
||||||
events = arr $ \case
|
events = arr $ \case
|
||||||
|
|||||||
+12
-268
@@ -1,271 +1,15 @@
|
|||||||
{-# LANGUAGE Arrows #-}
|
|
||||||
{-# LANGUAGE OverloadedStrings #-}
|
|
||||||
{-# LANGUAGE LambdaCase #-}
|
|
||||||
{-# LANGUAGE GADTs #-}
|
|
||||||
|
|
||||||
module HomeAssistant.Controller
|
module HomeAssistant.Controller
|
||||||
( Service(..)
|
( module Export
|
||||||
, HASSEff(..)
|
|
||||||
, HASS
|
|
||||||
, callService
|
|
||||||
, callServiceDyn
|
|
||||||
, entityChangeEvent
|
|
||||||
, entityChangeEvent'
|
|
||||||
, entityRead
|
|
||||||
, entityRead'
|
|
||||||
, entityBool
|
|
||||||
, entityBool'
|
|
||||||
, DoorState(..)
|
|
||||||
, light
|
|
||||||
, Presence(..)
|
|
||||||
, presence
|
|
||||||
, motion
|
|
||||||
, motionToPresence
|
|
||||||
, debug
|
|
||||||
, traceEvent
|
|
||||||
, traceValue
|
|
||||||
, switch
|
|
||||||
, Target(..)
|
|
||||||
, brightness
|
|
||||||
, Light(..)
|
|
||||||
, ikeaQuickButton
|
|
||||||
, IkeaButton(..)
|
|
||||||
, IkeaGesture(..)
|
|
||||||
, activateScene
|
|
||||||
, activateSceneWith
|
|
||||||
, ikeaBoxRemote
|
|
||||||
, IkeaController(..)
|
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import AFRP (Mealy (..), eff, Event(..), events, filterA, (>>|), toEvent, Request, hold, lMerge, waitFor, tag, edge)
|
import HomeAssistant.Controller.Service as Export
|
||||||
import Control.Arrow (Arrow(..), returnA)
|
import HomeAssistant.Controller.Effect as Export
|
||||||
import Control.Category ((>>>))
|
import HomeAssistant.Controller.Entity as Export
|
||||||
import Data.Aeson (Value, object, (.=))
|
import HomeAssistant.Controller.Presence as Export
|
||||||
import qualified Data.Text as T
|
import HomeAssistant.Controller.Door as Export
|
||||||
import qualified Data.Set as S
|
import HomeAssistant.Controller.Switch as Export
|
||||||
import Control.Lens (has, only, (^?), to, traversed)
|
import HomeAssistant.Controller.Scene as Export
|
||||||
import Data.Aeson.Lens (key, _String, _Integral)
|
import HomeAssistant.Controller.Ikea as Export
|
||||||
import qualified Data.Text.Lens as TL
|
import HomeAssistant.Controller.Light.Command as Export
|
||||||
import Data.Bool (bool)
|
import HomeAssistant.Controller.Light.Observation as Export
|
||||||
import Data.Serialize (Serialize)
|
import HomeAssistant.Controller.Light.Mode as Export
|
||||||
import GHC.Generics (Generic)
|
|
||||||
import Data.Time (NominalDiffTime)
|
|
||||||
|
|
||||||
data Target = EntityId !T.Text | AreaId !T.Text
|
|
||||||
deriving (Show,Eq,Ord)
|
|
||||||
|
|
||||||
data Service = Service
|
|
||||||
{ serviceDomain :: T.Text
|
|
||||||
, serviceName :: T.Text
|
|
||||||
, serviceData :: Maybe Value
|
|
||||||
, serviceTarget :: [Target]
|
|
||||||
}
|
|
||||||
deriving (Show, Eq)
|
|
||||||
|
|
||||||
data HASSEff a where
|
|
||||||
CallService :: Request -> Service -> HASSEff ()
|
|
||||||
Debug :: Show a => a -> HASSEff ()
|
|
||||||
Trace :: Show a => Request -> a -> HASSEff ()
|
|
||||||
|
|
||||||
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 = 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
|
|
||||||
eff Trace -< x
|
|
||||||
returnA -< x
|
|
||||||
|
|
||||||
data DoorState = Open | Closed
|
|
||||||
deriving (Show, Eq, Generic)
|
|
||||||
|
|
||||||
instance Serialize DoorState
|
|
||||||
|
|
||||||
data Presence = Occupied | Unoccupied
|
|
||||||
deriving (Show, Eq, Generic)
|
|
||||||
|
|
||||||
instance Serialize Presence
|
|
||||||
|
|
||||||
presence :: T.Text -> HASS (Event Value) (Event Presence)
|
|
||||||
presence entityId = entityBool entityId
|
|
||||||
>>> arr (fmap (bool Unoccupied Occupied))
|
|
||||||
|
|
||||||
|
|
||||||
data Motion = MotionDetected | MotionNotDetected | MotionUnknown
|
|
||||||
deriving (Show, Eq, Generic)
|
|
||||||
|
|
||||||
|
|
||||||
motion :: T.Text -> HASS (Event Value) Motion
|
|
||||||
motion entityId = entityBool entityId
|
|
||||||
>>> arr (fmap (bool MotionNotDetected MotionDetected))
|
|
||||||
>>> hold MotionUnknown
|
|
||||||
|
|
||||||
|
|
||||||
-- Convert a motion status into a simulated presence
|
|
||||||
--
|
|
||||||
-- A motion tracker detects _motion_, but if you are still, it can't detect you.
|
|
||||||
-- A simple and cheap heuristic is to assume the person is a bit longer there
|
|
||||||
motionToPresence :: NominalDiffTime -> HASS Motion Presence
|
|
||||||
motionToPresence delay = (eventOccupied &&& eventUnoccupied)
|
|
||||||
>>> arr (uncurry lMerge)
|
|
||||||
>>> AFRP.hold Unoccupied
|
|
||||||
where
|
|
||||||
eventOccupied :: HASS Motion (Event Presence)
|
|
||||||
eventOccupied = arr (== MotionDetected) >>> edge >>> arr (fmap (const Occupied))
|
|
||||||
eventUnoccupied :: HASS Motion (Event Presence)
|
|
||||||
eventUnoccupied = arr (== MotionNotDetected) >>> waitFor delay >>> arr (tag Unoccupied)
|
|
||||||
|
|
||||||
instance Serialize Motion
|
|
||||||
|
|
||||||
data Light
|
|
||||||
= Off
|
|
||||||
| On { brightnessPercentage :: Maybe Double }
|
|
||||||
|
|
||||||
-- Turn off lights when door is closed
|
|
||||||
light :: [Target] -> Light -> Service
|
|
||||||
light targets (On {brightnessPercentage}) = Service
|
|
||||||
{ serviceDomain="light"
|
|
||||||
, 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
|
|
||||||
}
|
|
||||||
|
|
||||||
-- Name conflict with AFRP
|
|
||||||
switch :: [Target] -> Bool -> Service
|
|
||||||
switch targets b = Service
|
|
||||||
{ serviceDomain="switch"
|
|
||||||
, serviceName= bool "turn_off" "turn_on" b
|
|
||||||
, serviceData=Nothing
|
|
||||||
, serviceTarget=targets
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
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 = Mealy (S.singleton entityId) $ runMealy (events >>| filterA isEntity)
|
|
||||||
where
|
|
||||||
isEntity :: Value -> Bool
|
|
||||||
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 "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 "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to toBool
|
|
||||||
toBool = \case
|
|
||||||
"on" -> True
|
|
||||||
"off" -> False
|
|
||||||
_ -> False
|
|
||||||
|
|
||||||
entityRead :: (Read a) => T.Text -> Mealy eff (Event Value) (Event a)
|
|
||||||
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 = activateSceneWith sceneId Nothing
|
|
||||||
|
|
||||||
activateSceneWith :: T.Text -> Maybe Value -> Service
|
|
||||||
activateSceneWith sceneId d = Service
|
|
||||||
{ serviceDomain="scene"
|
|
||||||
, serviceName= "turn_on"
|
|
||||||
, serviceTarget= [EntityId sceneId]
|
|
||||||
, serviceData = d
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
{-# LANGUAGE Arrows #-}
|
{-# LANGUAGE Arrows #-}
|
||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
{-# LANGUAGE DerivingVia #-}
|
||||||
module HomeAssistant.Controller.Bedroom where
|
module HomeAssistant.Controller.Bedroom where
|
||||||
|
|
||||||
import HomeAssistant.Controller
|
import HomeAssistant.Controller
|
||||||
@@ -10,11 +11,16 @@ import Control.Arrow ((>>>), returnA, arr, Arrow (..))
|
|||||||
import Data.Bool (bool)
|
import Data.Bool (bool)
|
||||||
import Data.Time (NominalDiffTime)
|
import Data.Time (NominalDiffTime)
|
||||||
import qualified AFRP
|
import qualified AFRP
|
||||||
|
import Data.Map (Map)
|
||||||
|
import qualified Data.Map.Strict as M
|
||||||
|
import Data.Serialize.Text ()
|
||||||
|
import Data.Default (def)
|
||||||
|
import Data.Serialize (Serialize)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
bedroomLights :: [Target]
|
bedroomLightTargets :: [Target]
|
||||||
bedroomLights = map EntityId ["light.bedroom_masse","light.bedroom_jemina","light.bedroom_ceiling","light.bedroom_led_switch"]
|
bedroomLightTargets = map EntityId ["light.bedroom_masse","light.bedroom_jemina","light.bedroom_ceiling","light.bedroom_led_switch"]
|
||||||
|
|
||||||
createBedroomScene :: Service
|
createBedroomScene :: Service
|
||||||
createBedroomScene = Service
|
createBedroomScene = Service
|
||||||
@@ -22,22 +28,16 @@ createBedroomScene = Service
|
|||||||
, serviceName= "create"
|
, serviceName= "create"
|
||||||
, serviceData= Just $ object
|
, serviceData= Just $ object
|
||||||
[ "scene_id" .= ("makuuhuone_lights_snapshot" :: T.Text)
|
[ "scene_id" .= ("makuuhuone_lights_snapshot" :: T.Text)
|
||||||
, "snapshot_entities" .= [l | EntityId l <- bedroomLights]
|
, "snapshot_entities" .= [l | EntityId l <- bedroomLightTargets]
|
||||||
]
|
]
|
||||||
, serviceTarget= []
|
, serviceTarget= []
|
||||||
}
|
}
|
||||||
|
|
||||||
data PresenceLights
|
|
||||||
= LightsOn -- Restore lights
|
|
||||||
| LightsOff -- Timer expired, darkness
|
|
||||||
| LightsSleep -- No presence detected, sleep mode
|
|
||||||
deriving Show
|
|
||||||
|
|
||||||
-- Bedroom presence
|
-- Bedroom presence
|
||||||
bedroomPresence :: HASS (Event Value) (Event Presence)
|
bedroomPresence :: HASS (Event Value) (Event Presence)
|
||||||
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
|
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
|
||||||
|
|
||||||
presenceLightEvents :: HASS (Event Value) (Event PresenceLights)
|
presenceLightEvents :: HASS (Event Value) (Event LightingMode)
|
||||||
presenceLightEvents =
|
presenceLightEvents =
|
||||||
bedroomPresence >>> AFRP.hold Unoccupied
|
bedroomPresence >>> AFRP.hold Unoccupied
|
||||||
>>> arr lightWanted
|
>>> arr lightWanted
|
||||||
@@ -45,30 +45,58 @@ presenceLightEvents =
|
|||||||
>>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
|
>>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
|
||||||
where
|
where
|
||||||
lightWanted o = o == Occupied
|
lightWanted o = o == Occupied
|
||||||
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightsSleep)
|
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightingSleep)
|
||||||
onEvent = AFRP.edge >>> arr (AFRP.tag LightsOn)
|
onEvent = AFRP.edge >>> arr (AFRP.tag LightingOn)
|
||||||
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightsOff)
|
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightingOff)
|
||||||
|
|
||||||
|
|
||||||
|
bedroomLightStatus :: HASS (Event Value) (Map T.Text LightObservation)
|
||||||
|
bedroomLightStatus = M.fromList <$> traverse (\e -> (e,) <$> observedLight e) [e | EntityId e <- bedroomLightTargets]
|
||||||
|
|
||||||
|
newtype Snapshot = Snapshot { getSnapshot :: Map T.Text LightObservation }
|
||||||
|
deriving (Show, Eq)
|
||||||
|
deriving Serialize via (Map T.Text LightObservation)
|
||||||
|
|
||||||
|
lightLevel :: HASS (Event Value) Int
|
||||||
|
lightLevel = entityRead "sensor.presence_sensor_bedroom_light_level" >>> AFRP.hold 15
|
||||||
|
|
||||||
bedroomPresenceController :: HASS (Event Value) ()
|
bedroomPresenceController :: HASS (Event Value) ()
|
||||||
bedroomPresenceController = proc x -> do
|
bedroomPresenceController = proc x -> do
|
||||||
p <- presenceLightEvents >>> traceEvent -< x
|
p <- presenceLightEvents >>> traceEvent -< x
|
||||||
|
capped <- lightLevel >>> arr (< 4) -< x
|
||||||
|
-- mode <- AFRP.hold LightingOff -< p
|
||||||
|
-- This line is just for debugging purposes
|
||||||
|
_ <- bedroomLightStatus >>> AFRP.changes >>> traceEvent -< x
|
||||||
|
_ <- lightLevel >>> AFRP.changes >>> traceEvent -< x
|
||||||
|
snap <- (doSnapshot &&& bedroomLightStatus) >>> AFRP.snapshot M.empty >>> arr Snapshot -< x
|
||||||
|
-- This line is just for debugging
|
||||||
|
_ <- AFRP.changes >>> traceEvent -< snap
|
||||||
case p of
|
case p of
|
||||||
Event LightsOff -> do
|
Event LightingOff -> do
|
||||||
callService (light bedroomLights Off) -< ()
|
callService (light bedroomLightTargets Off) -< ()
|
||||||
Event LightsOn -> do
|
Event LightingOn -> do
|
||||||
callService (activateSceneWith "scene.makuuhuone_lights_snapshot" transition) -< ()
|
callServicesDyn (\(c,xs) -> concatMap (uncurry (toLight c)) xs) -< (capped, M.toList (getSnapshot snap))
|
||||||
Event LightsSleep -> do
|
returnA -< ()
|
||||||
callService createBedroomScene -< ()
|
Event LightingSleep -> do
|
||||||
callService (activateSceneWith "scene.makuuhuone_lepotila" transition) -< ()
|
callService (activateScene "scene.makuuhuone_lepotila") -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
where
|
where
|
||||||
transition = Just $ object ["transition" .= (10 :: Int)]
|
toLight :: Bool -> T.Text -> LightObservation -> [Service]
|
||||||
|
toLight _ entityId LightObservation{observedOn=False} = [light [EntityId entityId] Off]
|
||||||
|
toLight capped entityId LightObservation{observedOn=True, observedTemperature=t, observedBrightness=b} =
|
||||||
|
[ light [EntityId entityId] (On def
|
||||||
|
{lightBrightness = fmap (\b' -> BrightnessAbsolute $ if capped then 140 `min` b' else b') b
|
||||||
|
, lightColorTemperature = t
|
||||||
|
})
|
||||||
|
]
|
||||||
|
doSnapshot = presenceLightEvents
|
||||||
|
>>> arr (\ev -> if ev == Event LightingSleep then Event () else Tick)
|
||||||
|
|
||||||
|
|
||||||
data BedroomControls
|
data BedroomControls
|
||||||
= Masse (IkeaButton IkeaGesture)
|
= Masse (IkeaButton IkeaGesture)
|
||||||
| Enishen (IkeaButton IkeaGesture)
|
| Enishen (IkeaButton IkeaGesture)
|
||||||
| Central IkeaController
|
| Central IkeaRemoteAction
|
||||||
deriving Show
|
deriving Show
|
||||||
|
|
||||||
|
|
||||||
@@ -86,24 +114,22 @@ bedroomButtonController = proc x -> do
|
|||||||
-- Any event will cause the sleep mode to be turned off
|
-- Any event will cause the sleep mode to be turned off
|
||||||
case ev of
|
case ev of
|
||||||
Event (Masse (OnButton ShortRelease)) -> do
|
Event (Masse (OnButton ShortRelease)) -> do
|
||||||
callService (activateSceneWith "scene.makuuhuone_masse" transition) -< ()
|
callService (activateScene "scene.makuuhuone_masse") -< ()
|
||||||
Event (Masse (OnButton DoubleClick)) -> do
|
Event (Masse (OnButton DoubleClick)) -> do
|
||||||
callService (activateSceneWith "scene.makuuhuone_keski" transition) -< ()
|
callService (activateScene "scene.makuuhuone_keski") -< ()
|
||||||
Event (Masse (OnButton LongClick)) -> do
|
Event (Masse (OnButton LongClick)) -> do
|
||||||
callService (activateSceneWith "scene.makuuhuone_kirkas" transition) -< ()
|
callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
||||||
Event (Masse (OffButton _)) -> do
|
Event (Masse (OffButton _)) -> do
|
||||||
callService (light [AreaId "makuuhuone"] Off) -< ()
|
callService (light [AreaId "makuuhuone"] Off) -< ()
|
||||||
Event (Enishen (OnButton ShortRelease)) -> do
|
Event (Enishen (OnButton ShortRelease)) -> do
|
||||||
callService (activateSceneWith "scene.makuuhuone_jemina" transition) -< ()
|
callService (activateScene "scene.makuuhuone_jemina") -< ()
|
||||||
Event (Enishen (OnButton DoubleClick)) -> do
|
Event (Enishen (OnButton DoubleClick)) -> do
|
||||||
callService (activateSceneWith "scene.makuuhuone_keski" transition) -< ()
|
callService (activateScene "scene.makuuhuone_keski") -< ()
|
||||||
Event (Enishen (OnButton LongClick)) -> do
|
Event (Enishen (OnButton LongClick)) -> do
|
||||||
callService (activateSceneWith "scene.makuuhuone_kirkas" transition) -< ()
|
callService (activateScene "scene.makuuhuone_kirkas") -< ()
|
||||||
Event (Enishen (OffButton _)) -> do
|
Event (Enishen (OffButton _)) -> do
|
||||||
callService (light [AreaId "makuuhuone"] Off) -< ()
|
callService (light [AreaId "makuuhuone"] Off) -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
where
|
|
||||||
transition = Just $ object ["transition" .= (5 :: Int)]
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -115,8 +141,8 @@ bedroomDrawerController :: HASS (Event Value) ()
|
|||||||
bedroomDrawerController = proc x -> do
|
bedroomDrawerController = proc x -> do
|
||||||
st <- drawer >>> traceEvent -< x
|
st <- drawer >>> traceEvent -< x
|
||||||
case st of
|
case st of
|
||||||
Event Open -> callService (switch [entity] True) -< ()
|
Event Open -> callService (switchService [entity] True) -< ()
|
||||||
Event Closed -> callService (switch [entity] False) -< ()
|
Event Closed -> callService (switchService [entity] False) -< ()
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
where
|
where
|
||||||
entity = EntityId "switch.bedroom_drawer_light_masse"
|
entity = EntityId "switch.bedroom_drawer_light_masse"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{-# LANGUAGE Arrows #-}
|
{-# LANGUAGE Arrows #-}
|
||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
module HomeAssistant.Controller.Children where
|
module HomeAssistant.Controller.Children where
|
||||||
import HomeAssistant.Controller (HASS, callService, Target (AreaId), light, Light(..), ikeaQuickButton, IkeaGesture (..), IkeaButton (..), traceEvent, activateScene)
|
import HomeAssistant.Controller (HASS, callService, Target (AreaId), light, LightCommand(..), ikeaQuickButton, IkeaGesture (..), IkeaButton (..), traceEvent, activateScene, LightAttributes (..), Brightness (..))
|
||||||
import AFRP (Event (..))
|
import AFRP (Event (..))
|
||||||
import qualified AFRP
|
import qualified AFRP
|
||||||
import Control.Arrow (Arrow(..), (>>>), returnA)
|
import Control.Arrow (Arrow(..), (>>>), returnA)
|
||||||
@@ -9,6 +9,7 @@ import Data.Time (Day, TimeOfDay (..), localDay, LocalTime (..))
|
|||||||
import Data.Time.Calendar.OrdinalDate (WeekOfYear, mondayStartWeek)
|
import Data.Time.Calendar.OrdinalDate (WeekOfYear, mondayStartWeek)
|
||||||
import Data.Functor.Contravariant (Predicate (..), (>$<))
|
import Data.Functor.Contravariant (Predicate (..), (>$<))
|
||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value)
|
||||||
|
import Data.Default (Default(..))
|
||||||
|
|
||||||
-- Let's see building some reasonable interface for utctime
|
-- Let's see building some reasonable interface for utctime
|
||||||
dow :: Day -> (WeekOfYear, Int)
|
dow :: Day -> (WeekOfYear, Int)
|
||||||
@@ -74,19 +75,19 @@ schoolLightController = lightsOn <> lightsOff
|
|||||||
|
|
||||||
lightsOn :: HASS a ()
|
lightsOn :: HASS a ()
|
||||||
lightsOn = foldMap atTime timersOn
|
lightsOn = foldMap atTime timersOn
|
||||||
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] On{brightnessPercentage = Just 100}))
|
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] (On def{lightBrightness=Just $ BrightnessPercent 100} )))
|
||||||
|
|
||||||
lightsOff :: HASS a ()
|
lightsOff :: HASS a ()
|
||||||
lightsOff = foldMap atTime timersOff
|
lightsOff = foldMap atTime timersOff
|
||||||
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] Off))
|
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] Off))
|
||||||
|
|
||||||
|
|
||||||
bedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
|
childrenBedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
|
||||||
bedroomButton = ikeaQuickButton "event.children_quick_remote_action"
|
childrenBedroomButton = ikeaQuickButton "event.children_quick_remote_action"
|
||||||
|
|
||||||
childrenBedroomButtonController :: HASS (Event Value) ()
|
childrenBedroomButtonController :: HASS (Event Value) ()
|
||||||
childrenBedroomButtonController = proc x -> do
|
childrenBedroomButtonController = proc x -> do
|
||||||
ev <- bedroomButton >>> traceEvent -< x
|
ev <- childrenBedroomButton >>> traceEvent -< x
|
||||||
case ev of
|
case ev of
|
||||||
Event (OnButton ShortRelease) -> callService (activateScene "scene.lasten_nukkuvalmistelu") -< ()
|
Event (OnButton ShortRelease) -> callService (activateScene "scene.lasten_nukkuvalmistelu") -< ()
|
||||||
Event (OnButton DoubleClick) -> callService (activateScene "scene.lasten_luku") -< ()
|
Event (OnButton DoubleClick) -> callService (activateScene "scene.lasten_luku") -< ()
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
module HomeAssistant.Controller.Door (DoorState(..)) where
|
||||||
|
|
||||||
|
import GHC.Generics (Generic)
|
||||||
|
import Data.Serialize (Serialize)
|
||||||
|
|
||||||
|
data DoorState = Open | Closed
|
||||||
|
deriving (Show, Eq, Generic)
|
||||||
|
|
||||||
|
instance Serialize DoorState
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
{-# LANGUAGE Arrows #-}
|
||||||
|
{-# LANGUAGE GADTs #-}
|
||||||
|
|
||||||
|
module HomeAssistant.Controller.Effect
|
||||||
|
( HASSEff(..)
|
||||||
|
, HASS
|
||||||
|
, callService
|
||||||
|
, callServices
|
||||||
|
, callServiceDyn
|
||||||
|
, callServicesDyn
|
||||||
|
, debug
|
||||||
|
, traceEvent
|
||||||
|
, traceValue
|
||||||
|
) where
|
||||||
|
|
||||||
|
import AFRP (Mealy, eff, Event (..), Request)
|
||||||
|
import Control.Arrow (returnA)
|
||||||
|
import HomeAssistant.Controller.Service (Service)
|
||||||
|
|
||||||
|
data HASSEff a where
|
||||||
|
CallService :: Request -> Service -> HASSEff ()
|
||||||
|
CallServices :: Request -> [Service] -> HASSEff ()
|
||||||
|
Debug :: Show a => a -> HASSEff ()
|
||||||
|
Trace :: Show a => Request -> a -> HASSEff ()
|
||||||
|
|
||||||
|
type HASS a b = Mealy HASSEff a b
|
||||||
|
|
||||||
|
callService :: Service -> HASS a ()
|
||||||
|
callService service = eff (\req _ -> CallService req service)
|
||||||
|
|
||||||
|
callServices :: [Service] -> HASS a ()
|
||||||
|
callServices service = eff (\req _ -> CallServices req service)
|
||||||
|
|
||||||
|
callServiceDyn :: (a -> Service) -> HASS a ()
|
||||||
|
callServiceDyn mkService = eff (\req a -> CallService req (mkService a))
|
||||||
|
|
||||||
|
callServicesDyn :: (a -> [Service]) -> HASS a ()
|
||||||
|
callServicesDyn mkService = eff (\req a -> CallServices 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 = 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
|
||||||
|
eff Trace -< x
|
||||||
|
returnA -< x
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
{-# LANGUAGE LambdaCase #-}
|
||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
|
module HomeAssistant.Controller.Entity
|
||||||
|
( entityChangeEvent
|
||||||
|
, entityChangeEvent'
|
||||||
|
, entityRead
|
||||||
|
, entityRead'
|
||||||
|
, entityBool
|
||||||
|
, entityBool'
|
||||||
|
) where
|
||||||
|
|
||||||
|
import AFRP (Mealy (..), Event, events, filterA, (>>|), toEvent)
|
||||||
|
import Control.Arrow (arr)
|
||||||
|
import Control.Category ((>>>))
|
||||||
|
import Data.Aeson (Value)
|
||||||
|
import Data.Aeson.Lens (key, _String)
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import qualified Data.Set as S
|
||||||
|
import Control.Lens (has, only, (^?), to)
|
||||||
|
import qualified Data.Text.Lens as TL
|
||||||
|
|
||||||
|
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 = Mealy (S.singleton entityId) $ runMealy (events >>| filterA isEntity)
|
||||||
|
where
|
||||||
|
isEntity :: Value -> Bool
|
||||||
|
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 "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 "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to toBool
|
||||||
|
toBool = \case
|
||||||
|
"on" -> True
|
||||||
|
"off" -> False
|
||||||
|
_ -> False
|
||||||
|
|
||||||
|
entityRead :: (Read a) => T.Text -> Mealy eff (Event Value) (Event a)
|
||||||
|
entityRead entityId = entityRead' entityId >>> toEvent
|
||||||
|
|
||||||
|
entityBool :: T.Text -> Mealy eff (Event Value) (Event Bool)
|
||||||
|
entityBool entityId = entityBool' entityId >>> toEvent
|
||||||
@@ -2,37 +2,30 @@
|
|||||||
{-# LANGUAGE Arrows #-}
|
{-# LANGUAGE Arrows #-}
|
||||||
module HomeAssistant.Controller.Hallway where
|
module HomeAssistant.Controller.Hallway where
|
||||||
|
|
||||||
import HomeAssistant.Controller (Presence (..), HASS, motion, motionToPresence, traceEvent, callServiceDyn, light, Target (..), Light (..))
|
import HomeAssistant.Controller (Presence, HASS, motion, motionToPresence, traceEvent, callServiceDyn, light, Target (..), LightCommand (..))
|
||||||
|
import HomeAssistant.Controller.Light.Mode (LightingMode (..), lightingModeEvents)
|
||||||
import AFRP (Event (..))
|
import AFRP (Event (..))
|
||||||
import qualified AFRP
|
import qualified AFRP
|
||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value)
|
||||||
import Control.Arrow ((>>>), Arrow (..), returnA)
|
import Control.Arrow ((>>>), returnA)
|
||||||
import Data.Time (LocalTime(..), TimeOfDay (..))
|
import Data.Time (LocalTime(..), TimeOfDay (..))
|
||||||
|
import Data.Default (def)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
hallwayPresence :: HASS (Event Value) Presence
|
hallwayPresence :: HASS (Event Value) Presence
|
||||||
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
|
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
|
||||||
|
|
||||||
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 :: HASS (Event Value) ()
|
||||||
hallwayLightsController = proc x -> do
|
hallwayLightsController = proc x -> do
|
||||||
now <- AFRP.currentTime -< ()
|
now <- AFRP.currentTime -< ()
|
||||||
p <- hallwayPresence -< x
|
p <- hallwayPresence -< x
|
||||||
ev <- eventLights -< p
|
ev <- lightingModeEvents -< p
|
||||||
traceEvent -< ev
|
traceEvent -< ev
|
||||||
case ev of
|
case ev of
|
||||||
-- The lights entity is a "group of lights" in hass
|
-- The lights entity is a "group of lights" in hass
|
||||||
Event LightsOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< On Nothing
|
Event LightingOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< On def
|
||||||
Event LightsOff -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< Off
|
Event LightingOff -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< Off
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
where
|
where
|
||||||
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
|
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
{-# LANGUAGE LambdaCase #-}
|
||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
|
module HomeAssistant.Controller.Ikea
|
||||||
|
( IkeaGesture(..)
|
||||||
|
, IkeaButton(..)
|
||||||
|
, IkeaRemoteAction(..)
|
||||||
|
, ikeaQuickButton
|
||||||
|
, ikeaBoxRemote
|
||||||
|
) where
|
||||||
|
|
||||||
|
import AFRP (Event, toEvent, (>>|))
|
||||||
|
import Control.Arrow (arr)
|
||||||
|
import Control.Category ((>>>))
|
||||||
|
import Control.Lens ((^?), to, traversed)
|
||||||
|
import Data.Aeson (Value)
|
||||||
|
import Data.Aeson.Lens (key, _String)
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import HomeAssistant.Controller.Entity (entityChangeEvent')
|
||||||
|
import HomeAssistant.Controller.Effect (HASS)
|
||||||
|
|
||||||
|
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 IkeaRemoteAction
|
||||||
|
= RemoteOn -- Short press on
|
||||||
|
| RemoteOff -- Short press off
|
||||||
|
| RemoteBrightnessUp -- Turn brightness up
|
||||||
|
| RemoteBrightnessDown -- Turn brightness down
|
||||||
|
| RemoteArrowRight -- Arrow right
|
||||||
|
| RemoteArrowLeft -- Arrow left
|
||||||
|
| RemoteBrightnessStop
|
||||||
|
deriving Show
|
||||||
|
|
||||||
|
toIkeaRemoteAction :: T.Text -> Maybe IkeaRemoteAction
|
||||||
|
toIkeaRemoteAction = \case
|
||||||
|
"on" -> Just RemoteOn
|
||||||
|
"off" -> Just RemoteOff
|
||||||
|
"brightness_move_up" -> Just RemoteBrightnessUp
|
||||||
|
"brightness_move_down" -> Just RemoteBrightnessDown
|
||||||
|
"brightness_stop" -> Just RemoteBrightnessStop
|
||||||
|
"arrow_right_click" -> Just RemoteArrowRight
|
||||||
|
"arrow_left_click" -> Just RemoteArrowLeft
|
||||||
|
_ -> Nothing
|
||||||
|
|
||||||
|
ikeaBoxRemote :: T.Text -> HASS (Event Value) (Event IkeaRemoteAction)
|
||||||
|
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 toIkeaRemoteAction . traversed
|
||||||
@@ -8,31 +8,23 @@ import Data.Aeson (Value)
|
|||||||
import Control.Arrow ((>>>), Arrow (..), returnA)
|
import Control.Arrow ((>>>), Arrow (..), returnA)
|
||||||
import Prelude hiding (id)
|
import Prelude hiding (id)
|
||||||
import Data.Time (LocalTime(..), TimeOfDay (..))
|
import Data.Time (LocalTime(..), TimeOfDay (..))
|
||||||
|
import Data.Default (def)
|
||||||
|
|
||||||
|
|
||||||
-- Kitchen has two "presence" sensors. One IKEA motion sensor and one SwitchBot presence sensor
|
-- 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 :: HASS (Event Value) Presence
|
||||||
kitchenPresence = motion "binary_sensor.kitchen_movement_occupancy" >>> motionToPresence 500
|
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 :: HASS (Event Value) ()
|
||||||
kitchenCeilingController = proc x -> do
|
kitchenCeilingController = proc x -> do
|
||||||
now <- AFRP.currentTime -< ()
|
now <- AFRP.currentTime -< ()
|
||||||
p <- kitchenPresence -< x
|
p <- kitchenPresence -< x
|
||||||
ev <- eventLights -< p
|
ev <- lightingModeEvents -< p
|
||||||
traceEvent -< ev
|
traceEvent -< ev
|
||||||
case ev of
|
case ev of
|
||||||
Event LightsOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< On Nothing
|
Event LightingOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< On def
|
||||||
Event LightsOff -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< Off
|
Event LightingOff -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< Off
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
where
|
where
|
||||||
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
|
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
|
||||||
@@ -44,7 +36,7 @@ dinnerLightLevel = entityRead "sensor.sijainti_keittio_light_level" >>> AFRP.hol
|
|||||||
dinnerPresence :: HASS (Event Value) Presence
|
dinnerPresence :: HASS (Event Value) Presence
|
||||||
dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
|
dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
|
||||||
|
|
||||||
dinnerLightEvents :: HASS (Event Value) (Event Lights)
|
dinnerLightEvents :: HASS (Event Value) (Event LightingMode)
|
||||||
dinnerLightEvents =
|
dinnerLightEvents =
|
||||||
((,) <$> dinnerLightLevel <*> dinnerPresence)
|
((,) <$> dinnerLightLevel <*> dinnerPresence)
|
||||||
>>> arr lightWanted
|
>>> arr lightWanted
|
||||||
@@ -55,33 +47,33 @@ dinnerLightEvents =
|
|||||||
|
|
||||||
onEvent =
|
onEvent =
|
||||||
AFRP.edge
|
AFRP.edge
|
||||||
>>> arr (fmap (const LightsOn))
|
>>> arr (fmap (const LightingOn))
|
||||||
|
|
||||||
sleepEvent =
|
sleepEvent =
|
||||||
arr not
|
arr not
|
||||||
>>> AFRP.edge
|
>>> AFRP.edge
|
||||||
>>> arr (fmap (const LightsSleep))
|
>>> arr (fmap (const LightingSleep))
|
||||||
|
|
||||||
offEvent =
|
offEvent =
|
||||||
arr not
|
arr not
|
||||||
>>> AFRP.waitFor 300
|
>>> AFRP.waitFor 300
|
||||||
>>> arr (fmap (const LightsOff))
|
>>> arr (fmap (const LightingOff))
|
||||||
|
|
||||||
dinnerTableController :: HASS (Event Value) ()
|
dinnerTableController :: HASS (Event Value) ()
|
||||||
dinnerTableController = proc x -> do
|
dinnerTableController = proc x -> do
|
||||||
ev <- dinnerLightEvents -< x
|
ev <- dinnerLightEvents -< x
|
||||||
case ev of
|
case ev of
|
||||||
Event LightsOn -> do
|
Event LightingOn -> do
|
||||||
sleep -< False
|
sleep -< False
|
||||||
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On Nothing
|
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On def
|
||||||
Event LightsOff -> do
|
Event LightingOff -> do
|
||||||
sleep -< False
|
sleep -< False
|
||||||
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< Off
|
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< Off
|
||||||
Event LightsSleep -> do
|
Event LightingSleep -> do
|
||||||
sleep -< True
|
sleep -< True
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
where
|
where
|
||||||
sleep = callServiceDyn (switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"])
|
sleep = callServiceDyn (switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"])
|
||||||
|
|
||||||
kitchenMotionController :: HASS (Event Value) ()
|
kitchenMotionController :: HASS (Event Value) ()
|
||||||
kitchenMotionController = kitchenCeilingController <> dinnerTableController
|
kitchenMotionController = kitchenCeilingController <> dinnerTableController
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
{-# LANGUAGE MonadComprehensions #-}
|
||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
|
module HomeAssistant.Controller.Light.Command
|
||||||
|
( LightCommand(..)
|
||||||
|
, LightAttributes(..)
|
||||||
|
, Brightness(..)
|
||||||
|
, light
|
||||||
|
, formatLightAttributes
|
||||||
|
) where
|
||||||
|
|
||||||
|
import Data.Aeson (Value, object, (.=))
|
||||||
|
import Data.Aeson.Types (Pair)
|
||||||
|
import Data.Default (Default)
|
||||||
|
import Data.Maybe (catMaybes)
|
||||||
|
import GHC.Generics (Generic)
|
||||||
|
import HomeAssistant.Controller.Service (Service (..), Target)
|
||||||
|
|
||||||
|
data Brightness = BrightnessPercent Double | BrightnessAbsolute Int
|
||||||
|
deriving (Show, Generic)
|
||||||
|
instance Default Brightness where
|
||||||
|
|
||||||
|
data LightAttributes = LightAttributes
|
||||||
|
{ lightBrightness :: Maybe Brightness
|
||||||
|
, lightColorTemperature :: Maybe Int
|
||||||
|
, lightTransition :: Maybe Double
|
||||||
|
}
|
||||||
|
deriving (Show, Generic)
|
||||||
|
|
||||||
|
|
||||||
|
instance Default LightAttributes where
|
||||||
|
|
||||||
|
|
||||||
|
formatLightAttributes :: LightAttributes -> Maybe Value
|
||||||
|
formatLightAttributes s = toObject $ catMaybes
|
||||||
|
[ ["transition" .= x | x <- lightTransition s]
|
||||||
|
, ["color_temp_kelvin" .= k | k <- lightColorTemperature s]
|
||||||
|
, ["brightness" .= b | BrightnessAbsolute b <- lightBrightness s]
|
||||||
|
, ["brightness_pct" .= b | BrightnessPercent b <- lightBrightness s]
|
||||||
|
]
|
||||||
|
where
|
||||||
|
toObject :: [Pair] -> Maybe Value
|
||||||
|
toObject [] = Nothing
|
||||||
|
toObject xs = Just $ object xs
|
||||||
|
|
||||||
|
data LightCommand
|
||||||
|
= Off
|
||||||
|
| On LightAttributes
|
||||||
|
|
||||||
|
light :: [Target] -> LightCommand -> Service
|
||||||
|
light targets (On settings) = Service
|
||||||
|
{ serviceDomain="light"
|
||||||
|
, serviceName= "turn_on"
|
||||||
|
, serviceData= formatLightAttributes settings
|
||||||
|
, serviceTarget=targets
|
||||||
|
}
|
||||||
|
light targets Off = Service
|
||||||
|
{ serviceDomain="light"
|
||||||
|
, serviceName= "turn_off"
|
||||||
|
, serviceData=Nothing
|
||||||
|
, serviceTarget=targets
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
module HomeAssistant.Controller.Light.Mode
|
||||||
|
( LightingMode(..)
|
||||||
|
, toLightingMode
|
||||||
|
, lightingModeEvents
|
||||||
|
) where
|
||||||
|
|
||||||
|
import HomeAssistant.Controller.Effect (HASS)
|
||||||
|
import HomeAssistant.Controller.Presence (Presence (..))
|
||||||
|
import qualified AFRP
|
||||||
|
import Control.Arrow (Arrow(..), (>>>))
|
||||||
|
import GHC.Generics (Generic)
|
||||||
|
import Data.Serialize (Serialize)
|
||||||
|
|
||||||
|
data LightingMode = LightingOn | LightingOff | LightingSleep
|
||||||
|
deriving (Eq, Show, Generic)
|
||||||
|
instance Serialize LightingMode
|
||||||
|
|
||||||
|
toLightingMode :: Presence -> LightingMode
|
||||||
|
toLightingMode Occupied = LightingOn
|
||||||
|
toLightingMode Unoccupied = LightingOff
|
||||||
|
|
||||||
|
lightingModeEvents :: HASS Presence (AFRP.Event LightingMode)
|
||||||
|
lightingModeEvents = AFRP.changes >>> arr (fmap toLightingMode)
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
{-# LANGUAGE Arrows #-}
|
||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
{-# LANGUAGE StrictData #-}
|
||||||
|
|
||||||
|
module HomeAssistant.Controller.Light.Observation
|
||||||
|
( LightObservation(..)
|
||||||
|
, observedLight
|
||||||
|
, lightBrightnessEvent
|
||||||
|
, lightTemperatureEvent
|
||||||
|
) where
|
||||||
|
|
||||||
|
import AFRP (Event, hold)
|
||||||
|
import Control.Arrow (arr, returnA)
|
||||||
|
import Control.Category ((>>>), (.))
|
||||||
|
import Control.Lens ((^?))
|
||||||
|
import Data.Aeson (Value)
|
||||||
|
import Data.Aeson.Lens (key, _Integral)
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import GHC.Generics (Generic)
|
||||||
|
import Data.Serialize (Serialize)
|
||||||
|
import HomeAssistant.Controller.Entity (entityBool, entityChangeEvent)
|
||||||
|
import HomeAssistant.Controller.Effect (HASS)
|
||||||
|
import Prelude hiding ((.))
|
||||||
|
|
||||||
|
lightBrightnessEvent :: T.Text -> HASS (Event Value) (Event (Maybe Int))
|
||||||
|
lightBrightnessEvent entityId =
|
||||||
|
entityChangeEvent entityId
|
||||||
|
>>> arr (fmap eventBrightness)
|
||||||
|
where
|
||||||
|
eventBrightness v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "brightness" . _Integral
|
||||||
|
|
||||||
|
lightTemperatureEvent :: T.Text -> HASS (Event Value) (Event (Maybe Int))
|
||||||
|
lightTemperatureEvent entityId =
|
||||||
|
entityChangeEvent entityId
|
||||||
|
>>> arr (fmap eventTemperature)
|
||||||
|
where
|
||||||
|
eventTemperature v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "color_temp_kelvin" . _Integral
|
||||||
|
|
||||||
|
data LightObservation = LightObservation
|
||||||
|
{ observedOn :: Bool
|
||||||
|
, observedBrightness :: Maybe Int
|
||||||
|
, observedTemperature :: Maybe Int
|
||||||
|
}
|
||||||
|
deriving (Show, Generic, Eq)
|
||||||
|
instance Serialize LightObservation
|
||||||
|
|
||||||
|
observedLight :: T.Text -> HASS (Event Value) LightObservation
|
||||||
|
observedLight entityId = proc ev -> do
|
||||||
|
e <- hold False . entityBool entityId -< ev
|
||||||
|
b <- hold Nothing . lightBrightnessEvent entityId -< ev
|
||||||
|
t <- hold Nothing . lightTemperatureEvent entityId -< ev
|
||||||
|
returnA -< LightObservation e b t
|
||||||
@@ -2,26 +2,19 @@
|
|||||||
{-# LANGUAGE Arrows #-}
|
{-# LANGUAGE Arrows #-}
|
||||||
module HomeAssistant.Controller.Livingroom where
|
module HomeAssistant.Controller.Livingroom where
|
||||||
|
|
||||||
import HomeAssistant.Controller (HASS, Presence (..), Target (..), presence, callServiceDyn, light, Light (..), traceEvent, callService, activateScene)
|
import HomeAssistant.Controller (HASS, Presence (..), Target (..), presence, callServiceDyn, light, LightCommand (..), traceEvent, callService, activateScene)
|
||||||
|
import HomeAssistant.Controller.Light.Mode (LightingMode (..), lightingModeEvents)
|
||||||
import qualified AFRP
|
import qualified AFRP
|
||||||
import Control.Arrow ((>>>), Arrow (..), returnA)
|
import Control.Arrow ((>>>), Arrow (..), returnA)
|
||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value)
|
||||||
import Prelude hiding ((.))
|
import Prelude hiding ((.))
|
||||||
import Control.Category ((.))
|
import Control.Category ((.))
|
||||||
import Data.Time (LocalTime(..), toGregorian, TimeOfDay (..))
|
import Data.Time (LocalTime(..), toGregorian, TimeOfDay (..))
|
||||||
|
import Data.Default (def)
|
||||||
data Lights = LightsOn | LightsOff
|
|
||||||
deriving (Show)
|
|
||||||
|
|
||||||
livingroomPresence :: HASS (AFRP.Event Value) Presence
|
livingroomPresence :: HASS (AFRP.Event Value) Presence
|
||||||
livingroomPresence = presence "binary_sensor.occupancy_olohuone_derived" >>> AFRP.hold Unoccupied
|
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
|
-- There's a small race condition / corner case bug in the og implementation
|
||||||
-- I have a couple of lights in the Livingroom
|
-- I have a couple of lights in the Livingroom
|
||||||
@@ -38,16 +31,16 @@ eventLights = AFRP.changes >>> arr (fmap presenceLights)
|
|||||||
-- With that in mind, I'll be explicitly controlling the two lights, without any scene shenanigans
|
-- With that in mind, I'll be explicitly controlling the two lights, without any scene shenanigans
|
||||||
|
|
||||||
|
|
||||||
lights :: [Target]
|
livingroomLightTargets :: [Target]
|
||||||
lights = [EntityId "light.livingroom_ceiling", EntityId "light.livingroom_sofa"]
|
livingroomLightTargets = [EntityId "light.livingroom_ceiling", EntityId "light.livingroom_sofa"]
|
||||||
|
|
||||||
livingroomPresenceController :: HASS (AFRP.Event Value) ()
|
livingroomPresenceController :: HASS (AFRP.Event Value) ()
|
||||||
livingroomPresenceController = proc x -> do
|
livingroomPresenceController = proc x -> do
|
||||||
ev <- eventLights . livingroomPresence -< x
|
ev <- lightingModeEvents . livingroomPresence -< x
|
||||||
traceEvent -< ev
|
traceEvent -< ev
|
||||||
case ev of
|
case ev of
|
||||||
AFRP.Event LightsOn -> callServiceDyn (light lights) -< On Nothing
|
AFRP.Event LightingOn -> callServiceDyn (light livingroomLightTargets) -< On def
|
||||||
AFRP.Event LightsOff -> callServiceDyn (light lights) -< Off
|
AFRP.Event LightingOff -> callServiceDyn (light livingroomLightTargets) -< Off
|
||||||
_ -> returnA -< ()
|
_ -> returnA -< ()
|
||||||
returnA -< ()
|
returnA -< ()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
module HomeAssistant.Controller.Presence
|
||||||
|
( Presence(..)
|
||||||
|
, presence
|
||||||
|
, Motion(..)
|
||||||
|
, motion
|
||||||
|
, motionToPresence
|
||||||
|
) where
|
||||||
|
|
||||||
|
import AFRP (Event, hold, lMerge, waitFor, tag, edge)
|
||||||
|
import Control.Arrow (arr, (&&&))
|
||||||
|
import Control.Category ((>>>))
|
||||||
|
import Data.Aeson (Value)
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import Data.Bool (bool)
|
||||||
|
import Data.Serialize (Serialize)
|
||||||
|
import GHC.Generics (Generic)
|
||||||
|
import Data.Time (NominalDiffTime)
|
||||||
|
import HomeAssistant.Controller.Entity (entityBool)
|
||||||
|
import HomeAssistant.Controller.Effect (HASS)
|
||||||
|
|
||||||
|
data Presence = Occupied | Unoccupied
|
||||||
|
deriving (Show, Eq, Generic)
|
||||||
|
|
||||||
|
instance Serialize Presence
|
||||||
|
|
||||||
|
presence :: T.Text -> HASS (Event Value) (Event Presence)
|
||||||
|
presence entityId = entityBool entityId
|
||||||
|
>>> arr (fmap (bool Unoccupied Occupied))
|
||||||
|
|
||||||
|
|
||||||
|
data Motion = MotionDetected | MotionNotDetected | MotionUnknown
|
||||||
|
deriving (Show, Eq, Generic)
|
||||||
|
|
||||||
|
|
||||||
|
motion :: T.Text -> HASS (Event Value) Motion
|
||||||
|
motion entityId = entityBool entityId
|
||||||
|
>>> arr (fmap (bool MotionNotDetected MotionDetected))
|
||||||
|
>>> hold MotionUnknown
|
||||||
|
|
||||||
|
|
||||||
|
-- Convert a motion status into a simulated presence
|
||||||
|
--
|
||||||
|
-- A motion tracker detects _motion_, but if you are still, it can't detect you.
|
||||||
|
-- A simple and cheap heuristic is to assume the person is a bit longer there
|
||||||
|
motionToPresence :: NominalDiffTime -> HASS Motion Presence
|
||||||
|
motionToPresence delay = (eventOccupied &&& eventUnoccupied)
|
||||||
|
>>> arr (uncurry lMerge)
|
||||||
|
>>> AFRP.hold Unoccupied
|
||||||
|
where
|
||||||
|
eventOccupied :: HASS Motion (Event Presence)
|
||||||
|
eventOccupied = arr (== MotionDetected) >>> edge >>> arr (fmap (const Occupied))
|
||||||
|
eventUnoccupied :: HASS Motion (Event Presence)
|
||||||
|
eventUnoccupied = arr (== MotionNotDetected) >>> waitFor delay >>> arr (tag Unoccupied)
|
||||||
|
|
||||||
|
instance Serialize Motion
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
|
module HomeAssistant.Controller.Scene
|
||||||
|
( activateScene
|
||||||
|
, activateSceneWith
|
||||||
|
) where
|
||||||
|
|
||||||
|
import Data.Aeson (Value)
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import HomeAssistant.Controller.Service (Service (..), Target (..))
|
||||||
|
|
||||||
|
activateScene :: T.Text -> Service
|
||||||
|
activateScene sceneId = activateSceneWith sceneId Nothing
|
||||||
|
|
||||||
|
activateSceneWith :: T.Text -> Maybe Value -> Service
|
||||||
|
activateSceneWith sceneId d = Service
|
||||||
|
{ serviceDomain="scene"
|
||||||
|
, serviceName= "turn_on"
|
||||||
|
, serviceTarget= [EntityId sceneId]
|
||||||
|
, serviceData = d
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
module HomeAssistant.Controller.Service
|
||||||
|
( Service(..)
|
||||||
|
, Target(..)
|
||||||
|
) where
|
||||||
|
|
||||||
|
import Data.Aeson (Value)
|
||||||
|
import qualified Data.Text as T
|
||||||
|
|
||||||
|
data Target = EntityId !T.Text | AreaId !T.Text
|
||||||
|
deriving (Show,Eq,Ord)
|
||||||
|
|
||||||
|
data Service = Service
|
||||||
|
{ serviceDomain :: T.Text
|
||||||
|
, serviceName :: T.Text
|
||||||
|
, serviceData :: Maybe Value
|
||||||
|
, serviceTarget :: [Target]
|
||||||
|
}
|
||||||
|
deriving (Show, Eq)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
|
module HomeAssistant.Controller.Switch (switchService) where
|
||||||
|
|
||||||
|
import Data.Bool (bool)
|
||||||
|
import HomeAssistant.Controller.Service (Service (..), Target)
|
||||||
|
|
||||||
|
switchService :: [Target] -> Bool -> Service
|
||||||
|
switchService targets b = Service
|
||||||
|
{ serviceDomain="switch"
|
||||||
|
, serviceName= bool "turn_off" "turn_on" b
|
||||||
|
, serviceData=Nothing
|
||||||
|
, serviceTarget=targets
|
||||||
|
}
|
||||||
@@ -4,45 +4,50 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
module HomeAssistant.Runtime
|
module HomeAssistant.Runtime
|
||||||
( defaultMain
|
( defaultMain,
|
||||||
, step
|
step,
|
||||||
, CallIdGen
|
CallIdGen,
|
||||||
, mkCallIdGen
|
mkCallIdGen,
|
||||||
, dryRunHassEval
|
dryRunHassEval,
|
||||||
, Controller(..)
|
Controller (..),
|
||||||
, runController
|
runController,
|
||||||
) where
|
)
|
||||||
|
where
|
||||||
|
|
||||||
import AFRP (Event (..), Mealy (..), Request (..), Auto, stepAutoSerializing, load, DecodedAuto (..))
|
import AFRP (Auto, DecodedAuto (..), Event (..), Mealy (..), Request (..), load, stepAutoSerializing)
|
||||||
import Control.Concurrent.STM (atomically, dupTChan, readTChan)
|
import Control.Concurrent.STM (atomically, dupTChan, readTChan)
|
||||||
|
import Control.Monad.IO.Class (MonadIO, liftIO)
|
||||||
import Data.Aeson (Value)
|
import Data.Aeson (Value)
|
||||||
import qualified Data.Text as T
|
import Data.Foldable (forM_)
|
||||||
|
import Data.Maybe (fromMaybe)
|
||||||
|
import Data.Text qualified as T
|
||||||
import Data.Time (getCurrentTime, getCurrentTimeZone)
|
import Data.Time (getCurrentTime, getCurrentTimeZone)
|
||||||
|
import Data.UUID (UUID, toText)
|
||||||
|
import Data.UUID.V4 qualified as UUID.V4
|
||||||
import Data.Void (Void)
|
import Data.Void (Void)
|
||||||
|
import GHC.Stack (HasCallStack)
|
||||||
import HomeAssistant.Controller (HASS, HASSEff (..))
|
import HomeAssistant.Controller (HASS, HASSEff (..))
|
||||||
|
import HomeAssistant.Controller.Bedroom (bedroomButtonController, bedroomDrawerController, bedroomPresenceController, humidifierController)
|
||||||
|
import HomeAssistant.Controller.Children (childrenBedroomButtonController, schoolLightController)
|
||||||
|
import HomeAssistant.Controller.Hallway (hallwayLightsController)
|
||||||
|
import HomeAssistant.Controller.Kitchen (kitchenMotionController)
|
||||||
|
import HomeAssistant.Controller.Livingroom (livingroomPlantLights, livingroomPresenceController)
|
||||||
import HomeAssistant.Runtime.Bus
|
import HomeAssistant.Runtime.Bus
|
||||||
|
import HomeAssistant.Runtime.Connection (readerAction, writerAction)
|
||||||
import HomeAssistant.Runtime.Flags (loadFlags)
|
import HomeAssistant.Runtime.Flags (loadFlags)
|
||||||
import HomeAssistant.Runtime.Connection (writerAction, readerAction)
|
import HomeAssistant.Runtime.Metrics qualified
|
||||||
|
import HomeAssistant.Runtime.RateLimit (registerRateLimitMetrics, slidingWindowLimiter)
|
||||||
|
import HomeAssistant.Runtime.Supervisor (supervised)
|
||||||
|
import HttpServer qualified
|
||||||
|
import Katip (KatipContext, Namespace (Namespace), Severity (..), logF, logLocM, ls, runKatipContextT, runKatipT, sl, katipAddNamespace)
|
||||||
import Network.Socket (withSocketsDo)
|
import Network.Socket (withSocketsDo)
|
||||||
import System.Environment (getEnv, lookupEnv)
|
import System.Environment (getEnv, lookupEnv)
|
||||||
import HomeAssistant.Controller.Bedroom (bedroomPresenceController, bedroomButtonController, bedroomDrawerController, humidifierController)
|
|
||||||
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 HomeAssistant.Controller.Children (schoolLightController, childrenBedroomButtonController)
|
|
||||||
import Data.Maybe (fromMaybe)
|
|
||||||
import qualified System.Metrics
|
|
||||||
import qualified HomeAssistant.Runtime.Metrics
|
|
||||||
import System.FilePath ((</>))
|
import System.FilePath ((</>))
|
||||||
|
import System.Metrics qualified
|
||||||
import Text.Read (readMaybe)
|
import Text.Read (readMaybe)
|
||||||
import HomeAssistant.Controller.Kitchen (kitchenMotionController)
|
|
||||||
import HomeAssistant.Controller.Livingroom (livingroomPresenceController, livingroomPlantLights)
|
|
||||||
import HomeAssistant.Runtime.RateLimit (slidingWindowLimiter, registerRateLimitMetrics)
|
|
||||||
import UnliftIO.Async
|
import UnliftIO.Async
|
||||||
import HomeAssistant.Runtime.Supervisor (supervised)
|
import Control.Monad.Catch (MonadCatch)
|
||||||
import HomeAssistant.Controller.Hallway (hallwayLightsController)
|
import Control.Exception.Annotated (checkpoint, Annotation (..))
|
||||||
import qualified HttpServer
|
|
||||||
|
|
||||||
step :: (MonadIO m) => FilePath -> T.Text -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
|
step :: (MonadIO m) => FilePath -> T.Text -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
|
||||||
step path name trace st a = do
|
step path name trace st a = do
|
||||||
@@ -55,41 +60,42 @@ data Controller = forall b. Controller T.Text (HASS (Event Value) b)
|
|||||||
|
|
||||||
controllers :: [Controller]
|
controllers :: [Controller]
|
||||||
controllers =
|
controllers =
|
||||||
[ Controller "bedroom-presence" bedroomPresenceController
|
[ Controller "bedroom-presence" bedroomPresenceController,
|
||||||
, Controller "bedroom-button" bedroomButtonController
|
Controller "bedroom-button" bedroomButtonController,
|
||||||
, Controller "bedroom-drawer" bedroomDrawerController
|
Controller "bedroom-drawer" bedroomDrawerController,
|
||||||
, Controller "bedroom-humidifier" humidifierController
|
Controller "bedroom-humidifier" humidifierController,
|
||||||
, Controller "school-light-controller" schoolLightController
|
Controller "school-light-controller" schoolLightController,
|
||||||
, Controller "kitchen-motion-controller" kitchenMotionController
|
Controller "kitchen-motion-controller" kitchenMotionController,
|
||||||
, Controller "livingroom-presence" livingroomPresenceController
|
Controller "livingroom-presence" livingroomPresenceController,
|
||||||
, Controller "hallway-motion-controller" hallwayLightsController
|
Controller "hallway-motion-controller" hallwayLightsController,
|
||||||
, Controller "children-button" childrenBedroomButtonController
|
Controller "children-button" childrenBedroomButtonController,
|
||||||
, Controller "livingroom-plants" livingroomPlantLights
|
Controller "livingroom-plants" livingroomPlantLights
|
||||||
]
|
]
|
||||||
|
|
||||||
-- | Steps the machine for every inbound message; service calls go to the
|
-- | 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
|
-- bus. A restart re-dups the inbound channel and starts from the machine's
|
||||||
-- initial state; messages broadcast during the restart window are lost.
|
-- initial state; messages broadcast during the restart window are lost.
|
||||||
runController :: MonadIO m => FilePath -> Bus -> Controller -> m Void
|
runController :: forall m. (HasCallStack, MonadCatch m, KatipContext m, MonadIO m) => FilePath -> Bus -> Controller -> m Void
|
||||||
runController rootDir bus (Controller name machine ) = liftIO $ do
|
runController rootDir bus (Controller name machine) = checkpoint (Annotation name) $ katipAddNamespace ns $ do
|
||||||
inbound <- atomically (dupTChan (busInbound bus))
|
inbound <- liftIO $ atomically (dupTChan (busInbound bus))
|
||||||
let ns = Namespace [name]
|
let workerDefinition = runMealy machine (channelHassEval @m bus)
|
||||||
let workerDefinition = runMealy machine (runKatipContextT (busLogEnv bus) () ns . channelHassEval bus)
|
|
||||||
let path = rootDir </> T.unpack name
|
let path = rootDir </> T.unpack name
|
||||||
worker <- load path workerDefinition >>= \case
|
worker <-
|
||||||
|
load path workerDefinition >>= \case
|
||||||
Decoded a -> pure a
|
Decoded a -> pure a
|
||||||
FailDecode err a -> a <$ putStrLn ("Failed to load (" <> T.unpack name <> "): " <> err)
|
FailDecode err a -> a <$ logLocM WarningS (ls ("Failed to load (" <> T.unpack name <> "): " <> err))
|
||||||
go path inbound worker
|
go path inbound worker
|
||||||
where
|
where
|
||||||
|
ns = Namespace [name]
|
||||||
go path inbound f = do
|
go path inbound f = do
|
||||||
msg <- atomically (readTChan inbound)
|
msg <- liftIO $ atomically (readTChan inbound)
|
||||||
uuid <- UUID.V4.nextRandom
|
uuid <- liftIO UUID.V4.nextRandom
|
||||||
(_, next) <- step path name uuid f msg
|
(_, next) <- step path name uuid f msg
|
||||||
go path inbound next
|
go path inbound next
|
||||||
|
|
||||||
lookupPort :: IO Int
|
lookupPort :: (MonadFail m, MonadIO m) => m Int
|
||||||
lookupPort = do
|
lookupPort = do
|
||||||
m <- lookupEnv "HA_METRICS_PORT"
|
m <- liftIO (lookupEnv "HA_METRICS_PORT")
|
||||||
case m of
|
case m of
|
||||||
Nothing -> pure 8124
|
Nothing -> pure 8124
|
||||||
Just s -> case readMaybe s of
|
Just s -> case readMaybe s of
|
||||||
@@ -97,37 +103,45 @@ lookupPort = do
|
|||||||
_ -> fail ("HA_METRICS_PORT must be a port in 1..65535: " <> s)
|
_ -> fail ("HA_METRICS_PORT must be a port in 1..65535: " <> s)
|
||||||
|
|
||||||
defaultMain :: IO ()
|
defaultMain :: IO ()
|
||||||
defaultMain = withSocketsDo $ do
|
defaultMain =
|
||||||
severity <- maybe InfoS (const DebugS) <$> lookupEnv "HA_DEBUG"
|
withSocketsDo $
|
||||||
store <- System.Metrics.newStore
|
getSeverity >>= \s -> withLogEnv s $ \le -> runKatipContextT le () mempty $ do
|
||||||
System.Metrics.registerGcMetrics store
|
logLocM InfoS "Hello world"
|
||||||
appMetrics <- HomeAssistant.Runtime.Metrics.registerAppMetrics store
|
store <- liftIO System.Metrics.newStore
|
||||||
|
liftIO $ System.Metrics.registerGcMetrics store
|
||||||
|
appMetrics <- liftIO $ HomeAssistant.Runtime.Metrics.registerAppMetrics store
|
||||||
rateLimitMetrics <- registerRateLimitMetrics store
|
rateLimitMetrics <- registerRateLimitMetrics store
|
||||||
rootPath <- fromMaybe "/tmp/" <$> lookupEnv "HA_LIB_DIR"
|
rootPath <- fromMaybe "/tmp/" <$> liftIO (lookupEnv "HA_LIB_DIR")
|
||||||
let allNames = map (\(Controller n _) -> n) controllers
|
let allNames = map (\(Controller n _) -> n) controllers
|
||||||
flags <- loadFlags rootPath allNames
|
flags <- loadFlags rootPath allNames
|
||||||
withBus severity appMetrics flags $ \bus -> do
|
withBus le appMetrics flags $ \bus -> do
|
||||||
token <- getEnv "HA_TOKEN"
|
token <- liftIO $ getEnv "HA_TOKEN"
|
||||||
host <- getEnv "HA_HOST"
|
host <- liftIO $ getEnv "HA_HOST"
|
||||||
let rrdPath = rootPath </> "hass-controller.rrd"
|
let rrdPath = rootPath </> "hass-controller.rrd"
|
||||||
rrdtool <- fromMaybe "rrdtool" <$> lookupEnv "HA_RRDTOOL"
|
rrdtool <- fromMaybe "rrdtool" <$> liftIO (lookupEnv "HA_RRDTOOL")
|
||||||
metricsPort <- lookupPort
|
metricsPort <- lookupPort
|
||||||
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
|
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
|
||||||
let ents = foldMap (\(Controller _ m) -> entities m) controllers
|
let ents = foldMap (\(Controller _ m) -> entities m) controllers
|
||||||
workers =
|
workers =
|
||||||
[ ("reader", readerAction host 8123 token ents bus)
|
[ ("reader", readerAction host 8123 token ents bus),
|
||||||
, ("writer", writerAction writerLimiter bus)
|
("writer", writerAction writerLimiter bus),
|
||||||
, ("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool)
|
("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool),
|
||||||
, ("metrics-http", HttpServer.runHttpServer (busLogEnv bus) rrdPath rrdtool (busFlags bus) metricsPort)
|
("metrics-http", HttpServer.runHttpServer (busLogEnv bus) rrdPath rrdtool (busFlags bus) metricsPort)
|
||||||
] ++ [ (name, runController rootPath bus c) | c@(Controller name _) <- controllers ]
|
]
|
||||||
|
++ [(name, runController rootPath bus c) | c@(Controller name _) <- controllers]
|
||||||
runKatipContextT (busLogEnv bus) () mempty $
|
runKatipContextT (busLogEnv bus) () mempty $
|
||||||
mapConcurrently_ (uncurry supervised) workers
|
mapConcurrently_ (uncurry supervised) workers
|
||||||
|
where
|
||||||
|
getSeverity = maybe InfoS (const DebugS) <$> lookupEnv "HA_DEBUG"
|
||||||
|
|
||||||
dryRunHassEval :: Namespace -> Bus -> HASSEff a -> IO a
|
dryRunHassEval :: Namespace -> Bus -> HASSEff a -> IO a
|
||||||
dryRunHassEval ns bus = \case
|
dryRunHassEval ns bus = \case
|
||||||
CallService req x -> runKatipT (busLogEnv bus) $ do
|
CallService req x -> runKatipT (busLogEnv bus) $ do
|
||||||
callId <- liftIO $ generateCallId (busGen bus)
|
callId <- liftIO $ generateCallId (busGen bus)
|
||||||
logF (sl "traceId" (toText (requestTraceId req))) ns DebugS (ls $ show (callId, x))
|
logF (sl "traceId" (toText (requestTraceId req))) ns DebugS (ls $ show (callId, x))
|
||||||
|
CallServices req xs -> runKatipT (busLogEnv bus) $ forM_ xs $ \x -> do
|
||||||
|
callId <- liftIO $ generateCallId (busGen bus)
|
||||||
|
logF (sl "traceId" (toText (requestTraceId req))) ns DebugS (ls $ show (callId, x))
|
||||||
Debug x -> runKatipT (busLogEnv bus) $ do
|
Debug x -> runKatipT (busLogEnv bus) $ do
|
||||||
logF () ns DebugS (ls $ show x)
|
logF () ns DebugS (ls $ show x)
|
||||||
Trace req x -> runKatipT (busLogEnv bus) $ do
|
Trace req x -> runKatipT (busLogEnv bus) $ do
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
{-# LANGUAGE LambdaCase #-}
|
{-# LANGUAGE LambdaCase #-}
|
||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
{-# LANGUAGE ScopedTypeVariables #-}
|
||||||
|
|
||||||
module HomeAssistant.Runtime.Bus
|
module HomeAssistant.Runtime.Bus
|
||||||
( Bus(..)
|
( Bus(..)
|
||||||
@@ -9,6 +10,7 @@ module HomeAssistant.Runtime.Bus
|
|||||||
, recordInbound
|
, recordInbound
|
||||||
, recordOutbound
|
, recordOutbound
|
||||||
, channelHassEval
|
, channelHassEval
|
||||||
|
, withLogEnv
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Control.Concurrent.STM
|
import Control.Concurrent.STM
|
||||||
@@ -31,9 +33,11 @@ import System.IO (stdout)
|
|||||||
import System.Metrics.Counter (inc)
|
import System.Metrics.Counter (inc)
|
||||||
import Data.UUID (toText)
|
import Data.UUID (toText)
|
||||||
import AFRP (Request(..), Event(..))
|
import AFRP (Request(..), Event(..))
|
||||||
import Control.Monad (when)
|
|
||||||
import Control.Monad.IO.Class (MonadIO, liftIO)
|
import Control.Monad.IO.Class (MonadIO, liftIO)
|
||||||
import HomeAssistant.Runtime.Flags (Flags, isEnabled)
|
import HomeAssistant.Runtime.Flags (Flags)
|
||||||
|
import Katip.Scribes.Journal (mkJournalScribe)
|
||||||
|
import System.Environment (lookupEnv)
|
||||||
|
import Data.Maybe (isJust)
|
||||||
|
|
||||||
-- | Shared runtime state: inbound is a broadcast channel (controllers
|
-- | Shared runtime state: inbound is a broadcast channel (controllers
|
||||||
-- read from 'dupTChan' copies), outbound queues service calls for the
|
-- read from 'dupTChan' copies), outbound queues service calls for the
|
||||||
@@ -48,17 +52,31 @@ data Bus = Bus
|
|||||||
, busFlags :: Flags
|
, busFlags :: Flags
|
||||||
}
|
}
|
||||||
|
|
||||||
withBus :: Severity -> AppMetrics -> Flags -> (Bus -> IO a) -> IO a
|
withLogEnv :: Severity -> (LogEnv -> IO a) -> IO a
|
||||||
withBus severity metrics flags callback = do
|
withLogEnv severity f = do
|
||||||
handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem severity) V2
|
let makeLogEnv = registerJournalScribe =<< registerHandleScribe =<< initLogEnv "hass-controller" "production"
|
||||||
let makeLogEnv = registerScribe "stdout" handleScribe defaultScribeSettings =<< initLogEnv "hass-controller" "production"
|
|
||||||
-- closeScribes will stop accepting new logs, flush existing ones and clean up resources
|
-- closeScribes will stop accepting new logs, flush existing ones and clean up resources
|
||||||
bracket makeLogEnv closeScribes $ \le -> do
|
bracket makeLogEnv closeScribes $ \le -> f le
|
||||||
|
where
|
||||||
|
registerJournalScribe :: LogEnv -> IO LogEnv
|
||||||
|
registerJournalScribe le = do
|
||||||
|
journalScribe <- mkJournalScribe (permitItem severity) V2
|
||||||
|
registerScribe "journalctl" journalScribe defaultScribeSettings le
|
||||||
|
registerHandleScribe le = do
|
||||||
|
systemdUnit <- isJust <$> lookupEnv "HA_CONTROLLER_SYSTEMD"
|
||||||
|
if systemdUnit
|
||||||
|
then pure le -- ignore stdout when running in systemd
|
||||||
|
else do
|
||||||
|
handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem severity) V2
|
||||||
|
registerScribe "stdout" handleScribe defaultScribeSettings le
|
||||||
|
|
||||||
|
withBus :: MonadIO m => LogEnv -> AppMetrics -> Flags -> (Bus -> m a) -> m a
|
||||||
|
withBus le metrics flags callback = do
|
||||||
bus <- Bus
|
bus <- Bus
|
||||||
<$> newBroadcastTChanIO
|
<$> liftIO newBroadcastTChanIO
|
||||||
<*> newTChanIO
|
<*> liftIO newTChanIO
|
||||||
<*> newTVarIO Nothing
|
<*> liftIO (newTVarIO Nothing)
|
||||||
<*> mkCallIdGen 0
|
<*> liftIO (mkCallIdGen 0)
|
||||||
<*> pure le
|
<*> pure le
|
||||||
<*> pure metrics
|
<*> pure metrics
|
||||||
<*> pure flags
|
<*> pure flags
|
||||||
@@ -70,15 +88,16 @@ recordInbound bus = inc (amTriggersIn (busMetrics bus))
|
|||||||
recordOutbound :: Bus -> IO ()
|
recordOutbound :: Bus -> IO ()
|
||||||
recordOutbound bus = inc (amServicesOut (busMetrics bus))
|
recordOutbound bus = inc (amServicesOut (busMetrics bus))
|
||||||
|
|
||||||
channelHassEval :: (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a
|
channelHassEval :: forall m a. (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a
|
||||||
channelHassEval bus = \case
|
channelHassEval bus = \case
|
||||||
CallService req svc -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ do
|
CallService req svc -> emit req svc
|
||||||
logFM DebugS (ls $ show svc)
|
CallServices req svcs -> mapM_ (emit req) svcs
|
||||||
enabled <- isEnabled (busFlags bus) (requestHandler req)
|
|
||||||
when enabled $ liftIO $ atomically $ writeTChan (busOutbound bus) (req, svc)
|
|
||||||
Debug x -> logFM DebugS (ls $ show x)
|
Debug x -> logFM DebugS (ls $ show x)
|
||||||
Trace req x -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $
|
Trace req x -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $
|
||||||
logFM InfoS (ls $ show x)
|
logFM InfoS (ls $ show x)
|
||||||
|
where
|
||||||
|
emit :: Request -> Service -> m ()
|
||||||
|
emit req svc = liftIO $ atomically $ writeTChan (busOutbound bus) (req, svc)
|
||||||
|
|
||||||
newtype CallIdGen = CallIdGen { generateCallId :: IO Int }
|
newtype CallIdGen = CallIdGen { generateCallId :: IO Int }
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
module HomeAssistant.Runtime.Connection
|
module HomeAssistant.Runtime.Connection
|
||||||
( readerAction
|
( readerAction
|
||||||
, writerAction
|
, writerAction
|
||||||
|
, dispatchService
|
||||||
, encodeService
|
, encodeService
|
||||||
, isTriggerEvent
|
, isTriggerEvent
|
||||||
) where
|
) where
|
||||||
@@ -16,9 +17,7 @@ import Control.Concurrent.STM
|
|||||||
, writeTChan
|
, writeTChan
|
||||||
, writeTVar
|
, writeTVar
|
||||||
)
|
)
|
||||||
import Control.Concurrent.Async (race)
|
|
||||||
import Control.Concurrent (threadDelay)
|
import Control.Concurrent (threadDelay)
|
||||||
import Control.Exception (onException)
|
|
||||||
import Control.Exception.Annotated (throw)
|
import Control.Exception.Annotated (throw)
|
||||||
import Control.Lens ((^?))
|
import Control.Lens ((^?))
|
||||||
import Control.Monad (forever, forM_, when)
|
import Control.Monad (forever, forM_, when)
|
||||||
@@ -29,27 +28,31 @@ import qualified Data.Text as T
|
|||||||
import Data.Void (Void)
|
import Data.Void (Void)
|
||||||
import HomeAssistant.Controller (Service (..), Target (..))
|
import HomeAssistant.Controller (Service (..), Target (..))
|
||||||
import HomeAssistant.Runtime.Bus
|
import HomeAssistant.Runtime.Bus
|
||||||
|
import HomeAssistant.Runtime.Flags (isEnabled)
|
||||||
import HomeAssistant.Runtime.Supervisor (Fatal (..))
|
import HomeAssistant.Runtime.Supervisor (Fatal (..))
|
||||||
import qualified Network.WebSockets as WS
|
import qualified Network.WebSockets as WS
|
||||||
import Katip (sl, logFM, Severity (..), ls, KatipContext, katipAddNamespace, katipAddContext)
|
import Katip (sl, logFM, Severity (..), ls, Namespace (Namespace), KatipContext, katipAddNamespace, katipAddContext, logLocM)
|
||||||
import Data.UUID (toText)
|
import Data.UUID (toText)
|
||||||
import AFRP (Request(..), Event(..))
|
import AFRP (Request(..), Event(..))
|
||||||
import Control.Monad.IO.Class (liftIO, MonadIO)
|
import Control.Monad.IO.Class (liftIO, MonadIO)
|
||||||
import HomeAssistant.Runtime.RateLimit (RateLimited, RateLimiter, runRateLimited)
|
import HomeAssistant.Runtime.RateLimit (RateLimited, RateLimiter, runRateLimited)
|
||||||
import Control.Monad.Catch (MonadCatch)
|
import Control.Monad.Catch (MonadCatch)
|
||||||
|
import GHC.Stack (HasCallStack)
|
||||||
|
import UnliftIO (MonadUnliftIO, race, withRunInIO)
|
||||||
|
import Control.Monad.Catch (onException)
|
||||||
|
|
||||||
-- | Connect, authenticate, subscribe, then receive and broadcast forever.
|
-- | Connect, authenticate, subscribe, then receive and broadcast forever.
|
||||||
-- Restarting this action reconnects. All setup sends happen before the
|
-- Restarting this action reconnects. All setup sends happen before the
|
||||||
-- connection is published in the bus, so only the writer sends afterwards.
|
-- connection is published in the bus, so only the writer sends afterwards.
|
||||||
readerAction :: MonadIO m => String -> Int -> String -> S.Set T.Text -> Bus -> m Void
|
readerAction :: (MonadCatch m, HasCallStack, KatipContext m, MonadUnliftIO m, MonadIO m) => String -> Int -> String -> S.Set T.Text -> Bus -> m Void
|
||||||
readerAction host port token ents bus = liftIO $
|
readerAction host port token ents bus = katipAddNamespace "receiver" $ withRunInIO $ \rio ->
|
||||||
WS.runClient host port "/api/websocket" $ \conn -> do
|
WS.runClient host port "/api/websocket" $ \conn -> rio $ do
|
||||||
handshake conn token
|
liftIO $ handshake conn token
|
||||||
subscribe bus conn ents
|
subscribe bus conn ents
|
||||||
atomically $ writeTVar (busConn bus) (Just conn)
|
liftIO $ atomically $ writeTVar (busConn bus) (Just conn)
|
||||||
putStrLn "[reader] connected"
|
logLocM InfoS "connected"
|
||||||
-- Unpublish on exit so the writer blocks and the backlog survives the outage.
|
-- Unpublish on exit so the writer blocks and the backlog survives the outage.
|
||||||
receiveLoop bus conn `onException` atomically (writeTVar (busConn bus) Nothing)
|
receiveLoop bus conn `onException` liftIO (atomically (writeTVar (busConn bus) Nothing))
|
||||||
|
|
||||||
handshake :: WS.Connection -> String -> IO ()
|
handshake :: WS.Connection -> String -> IO ()
|
||||||
handshake conn token = do
|
handshake conn token = do
|
||||||
@@ -71,12 +74,12 @@ expectType expected msg =
|
|||||||
isTriggerEvent :: Value -> Bool
|
isTriggerEvent :: Value -> Bool
|
||||||
isTriggerEvent v = v ^? key "type" . _String == Just "event"
|
isTriggerEvent v = v ^? key "type" . _String == Just "event"
|
||||||
|
|
||||||
subscribe :: Bus -> WS.Connection -> S.Set T.Text -> IO ()
|
subscribe :: HasCallStack => KatipContext m => Bus -> WS.Connection -> S.Set T.Text -> m ()
|
||||||
subscribe bus conn ents =
|
subscribe bus conn ents =
|
||||||
forM_ (S.toList ents) $ \entityId -> do
|
forM_ (S.toList ents) $ \entityId -> do
|
||||||
print entityId
|
logLocM InfoS $ ls entityId
|
||||||
sid <- generateCallId (busGen bus)
|
sid <- liftIO $ generateCallId (busGen bus)
|
||||||
WS.sendTextData conn $ encode $ object
|
liftIO $ WS.sendTextData conn $ encode $ object
|
||||||
[ "id" .= sid
|
[ "id" .= sid
|
||||||
, "type" .= ("subscribe_trigger" :: T.Text)
|
, "type" .= ("subscribe_trigger" :: T.Text)
|
||||||
, "trigger" .= object
|
, "trigger" .= object
|
||||||
@@ -91,14 +94,14 @@ subscribe bus conn ents =
|
|||||||
-- Each read races a one-second timeout: a timeout broadcasts 'Tick' so
|
-- Each read races a one-second timeout: a timeout broadcasts 'Tick' so
|
||||||
-- time-based primitives (debounce, rollup, fixed, ...) keep advancing
|
-- time-based primitives (debounce, rollup, fixed, ...) keep advancing
|
||||||
-- even when no state changes arrive.
|
-- even when no state changes arrive.
|
||||||
receiveLoop :: Bus -> WS.Connection -> IO Void
|
receiveLoop :: (HasCallStack, MonadUnliftIO m, KatipContext m) => Bus -> WS.Connection -> m Void
|
||||||
receiveLoop bus conn = forever $ do
|
receiveLoop bus conn = forever $ do
|
||||||
winner <- race (threadDelay 1_000_000) (WS.receiveData conn)
|
winner <- race (liftIO $ threadDelay 1_000_000) (liftIO $ WS.receiveData conn)
|
||||||
case winner of
|
case winner of
|
||||||
Left () -> atomically $ writeTChan (busInbound bus) Tick
|
Left () -> liftIO $ atomically $ writeTChan (busInbound bus) Tick
|
||||||
Right msg -> case eitherDecode msg of
|
Right msg -> case eitherDecode msg of
|
||||||
Left err -> putStrLn $ "[reader] skipping undecodable message: " <> err
|
Left err -> logLocM WarningS $ ls $ "skipping undecodable message: " <> err
|
||||||
Right v -> do
|
Right v -> liftIO $ do
|
||||||
when (isTriggerEvent v) (recordInbound bus)
|
when (isTriggerEvent v) (recordInbound bus)
|
||||||
atomically $ writeTChan (busInbound bus) (Event v)
|
atomically $ writeTChan (busInbound bus) (Event v)
|
||||||
|
|
||||||
@@ -122,9 +125,20 @@ sendWithId bus conn svc = katipAddNamespace "connection" $ do
|
|||||||
writerAction :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> Bus -> m Void
|
writerAction :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> Bus -> m Void
|
||||||
writerAction rateLimiter bus = forever $ do
|
writerAction rateLimiter bus = forever $ do
|
||||||
(request, svc) <- liftIO $ atomically $ readTChan (busOutbound bus)
|
(request, svc) <- liftIO $ atomically $ readTChan (busOutbound bus)
|
||||||
katipAddContext (sl "traceId" (toText (requestTraceId request))) $ do
|
katipAddContext (sl "traceId" (toText (requestTraceId request))) $
|
||||||
|
katipAddNamespace (Namespace [requestHandler request]) $
|
||||||
|
dispatchService rateLimiter bus request svc
|
||||||
|
|
||||||
|
-- | Sends the service call, or logs and drops it when its handler is disabled.
|
||||||
|
dispatchService
|
||||||
|
:: (MonadIO m, KatipContext m, MonadCatch m)
|
||||||
|
=> RateLimiter -> Bus -> Request -> Service -> m ()
|
||||||
|
dispatchService rateLimiter bus request svc = do
|
||||||
|
enabled <- isEnabled (busFlags bus) (requestHandler request)
|
||||||
|
let logPrefix = if enabled then "Calling: " else "Skipping: "
|
||||||
|
logFM InfoS (ls $ logPrefix <> show svc)
|
||||||
|
when enabled $ do
|
||||||
conn <- liftIO $ atomically $ readTVar (busConn bus) >>= maybe retry pure
|
conn <- liftIO $ atomically $ readTVar (busConn bus) >>= maybe retry pure
|
||||||
-- runRateLimited rateLimiter $ sendWithId bus conn request svc
|
|
||||||
runRateLimited rateLimiter $ sendWithId bus conn svc
|
runRateLimited rateLimiter $ sendWithId bus conn svc
|
||||||
|
|
||||||
encodeService :: Int -> Service -> Value
|
encodeService :: Int -> Service -> Value
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ module HomeAssistant.Runtime.Flags
|
|||||||
|
|
||||||
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
|
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
|
||||||
import Control.Concurrent.STM (TVar, atomically, newTVarIO, readTVarIO, stateTVar)
|
import Control.Concurrent.STM (TVar, atomically, newTVarIO, readTVarIO, stateTVar)
|
||||||
import Control.Exception (IOException, handle)
|
|
||||||
import Control.Monad.IO.Class (MonadIO, liftIO)
|
import Control.Monad.IO.Class (MonadIO, liftIO)
|
||||||
import qualified Conduit as C
|
import qualified Conduit as C
|
||||||
import Conduit ((.|))
|
import Conduit ((.|))
|
||||||
@@ -24,8 +23,12 @@ import Data.Set (Set)
|
|||||||
import qualified Data.Set as S
|
import qualified Data.Set as S
|
||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
import System.FilePath ((</>))
|
import System.FilePath ((</>))
|
||||||
import System.IO (hPutStrLn, stderr)
|
|
||||||
import System.IO.Error (isDoesNotExistError)
|
import System.IO.Error (isDoesNotExistError)
|
||||||
|
import GHC.Stack (HasCallStack)
|
||||||
|
import Katip (KatipContext, logLocM, Severity (..), ls)
|
||||||
|
import Control.Monad.Catch (MonadCatch, handle)
|
||||||
|
import Control.Exception (IOException)
|
||||||
|
import Data.Maybe (fromMaybe)
|
||||||
|
|
||||||
type Name = Text
|
type Name = Text
|
||||||
|
|
||||||
@@ -36,14 +39,14 @@ data Flags = Flags
|
|||||||
, flagsValidNames :: Set Text
|
, flagsValidNames :: Set Text
|
||||||
}
|
}
|
||||||
|
|
||||||
loadFlags :: MonadIO m => FilePath -> [Name] -> m Flags
|
loadFlags :: (KatipContext m, MonadCatch m, MonadIO m) => FilePath -> [Name] -> m Flags
|
||||||
loadFlags rootPath allNames = liftIO $ do
|
loadFlags rootPath allNames = do
|
||||||
let path = rootPath </> "handlers.json"
|
let path = rootPath </> "handlers.json"
|
||||||
fileMap <- readFlagsFile path
|
fileMap <- readFlagsFile path
|
||||||
let defaults = M.fromList [(n, True) | n <- allNames]
|
let defaults = M.fromList [(n, True) | n <- allNames]
|
||||||
initial = M.unionWith (\fileVal _default -> fileVal) fileMap defaults
|
initial = M.unionWith (\fileVal -> const fileVal) fileMap defaults
|
||||||
tv <- newTVarIO initial
|
tv <- liftIO $ newTVarIO initial
|
||||||
lock <- newMVar ()
|
lock <- liftIO $ newMVar ()
|
||||||
pure Flags
|
pure Flags
|
||||||
{ flagsState = tv
|
{ flagsState = tv
|
||||||
, flagsLock = lock
|
, flagsLock = lock
|
||||||
@@ -51,21 +54,21 @@ loadFlags rootPath allNames = liftIO $ do
|
|||||||
, flagsValidNames = S.fromList allNames
|
, flagsValidNames = S.fromList allNames
|
||||||
}
|
}
|
||||||
|
|
||||||
readFlagsFile :: FilePath -> IO (Map Name Bool)
|
readFlagsFile :: forall m. (HasCallStack, KatipContext m, MonadCatch m) => FilePath -> m (Map Name Bool)
|
||||||
readFlagsFile path =
|
readFlagsFile path =
|
||||||
handle onMissingOrUnreadable $ do
|
handle onMissingOrUnreadable $ do
|
||||||
decoded <- decodeFileStrict' path
|
decoded <- liftIO $ decodeFileStrict' path
|
||||||
case decoded of
|
case decoded of
|
||||||
Nothing -> do
|
Nothing -> do
|
||||||
hPutStrLn stderr ("handlers.json is unparseable; treating all handlers as enabled: " <> path)
|
logLocM WarningS $ ls ("handlers.json is unparseable; treating all handlers as enabled: " <> path)
|
||||||
pure mempty
|
pure mempty
|
||||||
Just m -> pure (maybe mempty id m)
|
Just m -> pure (fromMaybe mempty m)
|
||||||
where
|
where
|
||||||
onMissingOrUnreadable :: IOException -> IO (Map Name Bool)
|
onMissingOrUnreadable :: HasCallStack => IOException -> m (Map Name Bool)
|
||||||
onMissingOrUnreadable e
|
onMissingOrUnreadable e
|
||||||
| isDoesNotExistError e = pure mempty
|
| isDoesNotExistError e = pure mempty
|
||||||
| otherwise = do
|
| otherwise = do
|
||||||
hPutStrLn stderr ("could not read handlers.json (" <> show e <> "); treating all handlers as enabled")
|
logLocM WarningS $ ls ("could not read handlers.json (" <> show e <> "); treating all handlers as enabled")
|
||||||
pure mempty
|
pure mempty
|
||||||
|
|
||||||
isEnabled :: MonadIO m => Flags -> Name -> m Bool
|
isEnabled :: MonadIO m => Flags -> Name -> m Bool
|
||||||
|
|||||||
@@ -38,12 +38,13 @@ data RateLimiter = RateLimiter
|
|||||||
|
|
||||||
|
|
||||||
slidingWindowLimiter
|
slidingWindowLimiter
|
||||||
:: RateLimitMetrics
|
:: MonadIO m
|
||||||
|
=> RateLimitMetrics
|
||||||
-> NominalDiffTime -- ^ Within how many seconds
|
-> NominalDiffTime -- ^ Within how many seconds
|
||||||
-> Int -- ^ How many requests we can make
|
-> Int -- ^ How many requests we can make
|
||||||
-> IO RateLimiter
|
-> m RateLimiter
|
||||||
slidingWindowLimiter metrics timeWindow size = do
|
slidingWindowLimiter metrics timeWindow size = do
|
||||||
window <- newTVarIO []
|
window <- liftIO $ newTVarIO []
|
||||||
return $ RateLimiter metrics $ \(RateLimited action) -> do
|
return $ RateLimiter metrics $ \(RateLimited action) -> do
|
||||||
now <- liftIO getPOSIXTime
|
now <- liftIO getPOSIXTime
|
||||||
allowed <- liftIO $ atomically $ do
|
allowed <- liftIO $ atomically $ do
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
module Katip.Scribes.Journal where
|
||||||
|
|
||||||
|
import Data.Text.Lazy qualified as TL
|
||||||
|
import Data.Text.Lazy.Builder qualified as Builder
|
||||||
|
import Katip (Item (..), LogStr (..), PermitFunc, Scribe (..), Verbosity (..), permitItem, Severity (..), registerScribe, defaultScribeSettings, initLogEnv, closeScribes, runKatipContextT, logLocM, LogItem, Namespace (..), getThreadIdText, payloadObject, katipAddContext, sl, getEnvironment)
|
||||||
|
import Systemd.Journal qualified as J
|
||||||
|
import Control.Exception (bracket)
|
||||||
|
import GHC.Stack (HasCallStack)
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import qualified Data.HashMap.Strict as HashMap
|
||||||
|
import qualified Data.Text.Encoding as TE
|
||||||
|
import qualified Data.Aeson as A
|
||||||
|
import qualified Data.ByteString.Lazy as BL
|
||||||
|
import qualified Data.Aeson.KeyMap as KeyMap
|
||||||
|
import qualified Data.Aeson.Key as Key
|
||||||
|
import qualified Data.ByteString as B
|
||||||
|
|
||||||
|
mkJournalScribe :: PermitFunc -> Verbosity -> IO Scribe
|
||||||
|
mkJournalScribe permitFunc verbosity =
|
||||||
|
pure $
|
||||||
|
Scribe
|
||||||
|
{ liPush = \i ->
|
||||||
|
J.sendMessageWith (TL.toStrict $ Builder.toLazyText $ unLogStr $ _itemMessage i) (itemToJournalFields verbosity i),
|
||||||
|
scribeFinalizer = pure (), -- no cleanup?
|
||||||
|
scribePermitItem = permitFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
itemToJournalFields :: forall a. LogItem a => Verbosity -> Item a -> J.JournalFields
|
||||||
|
itemToJournalFields verbosity item = mconcat
|
||||||
|
[ J.syslogIdentifier (unNS item)
|
||||||
|
, J.priority (mapPriority item)
|
||||||
|
, thread item
|
||||||
|
, payload item
|
||||||
|
, environment item
|
||||||
|
]
|
||||||
|
where
|
||||||
|
mapPriority i =
|
||||||
|
case _itemSeverity i of
|
||||||
|
DebugS -> J.Debug
|
||||||
|
InfoS -> J.Info
|
||||||
|
NoticeS -> J.Notice
|
||||||
|
WarningS -> J.Warning
|
||||||
|
ErrorS -> J.Error
|
||||||
|
CriticalS -> J.Critical
|
||||||
|
AlertS -> J.Alert
|
||||||
|
EmergencyS -> J.Emergency
|
||||||
|
unNS = T.intercalate "." . unNamespace . _itemNamespace
|
||||||
|
thread i = HashMap.singleton (katipField "thread") (TE.encodeUtf8 $ getThreadIdText $ _itemThread i)
|
||||||
|
environment i = HashMap.singleton (katipField "environment") (TE.encodeUtf8 $ getEnvironment $ _itemEnv i)
|
||||||
|
payload :: Item a -> J.JournalFields
|
||||||
|
payload i = -- HashMap.singleton (J.mkJournalField "payload") (BL.toStrict $ A.encode $ payloadObject verbosity $ _itemPayload i)
|
||||||
|
HashMap.fromList $ map (\(k,v) -> (katipField (Key.toText k), encodeValue v)) $ KeyMap.toList $ payloadObject verbosity $ _itemPayload i
|
||||||
|
-- The upstream doesn't handle '-'
|
||||||
|
katipField = J.mkJournalField . T.replace "-" "_" . ("KATIP_" <>)
|
||||||
|
encodeValue :: A.Value -> B.ByteString
|
||||||
|
encodeValue = \case
|
||||||
|
-- Handle simple scalar values as is
|
||||||
|
A.String t -> TE.encodeUtf8 t
|
||||||
|
x -> BL.toStrict $ A.encode x
|
||||||
|
|
||||||
|
test :: HasCallStack => IO ()
|
||||||
|
test = do
|
||||||
|
scribe <- mkJournalScribe (permitItem InfoS) V2
|
||||||
|
let makeLogEnv = registerScribe "journald" scribe defaultScribeSettings =<< initLogEnv "hass-controller" "dev"
|
||||||
|
bracket makeLogEnv closeScribes $ \le -> do
|
||||||
|
runKatipContextT le () "findme-context" $
|
||||||
|
katipAddContext (sl "trace-id" ("abcdefg" :: String)) $
|
||||||
|
logLocM InfoS "Hello world"
|
||||||
|
pure ()
|
||||||
+14
-14
@@ -5,7 +5,7 @@ module BedroomSpec (spec) where
|
|||||||
import AFRP (Event (..), entities)
|
import AFRP (Event (..), entities)
|
||||||
import qualified Data.Set as S
|
import qualified Data.Set as S
|
||||||
import qualified Data.Text as T
|
import qualified Data.Text as T
|
||||||
import Data.Aeson (Value, object, (.=))
|
import Data.Aeson (Value)
|
||||||
import HomeAssistant.Controller
|
import HomeAssistant.Controller
|
||||||
import HomeAssistant.Controller.Bedroom
|
import HomeAssistant.Controller.Bedroom
|
||||||
import Support
|
import Support
|
||||||
@@ -49,8 +49,8 @@ entitySpec = describe "entities" $ do
|
|||||||
]
|
]
|
||||||
|
|
||||||
it "bedroomPresenceController subscribes to the presence sensor" $
|
it "bedroomPresenceController subscribes to the presence sensor" $
|
||||||
entities bedroomPresenceController
|
S.toList (entities bedroomPresenceController)
|
||||||
`shouldBe` S.singleton "binary_sensor.presence_sensor_bedroom_occupancy"
|
`shouldContain` [ "binary_sensor.presence_sensor_bedroom_occupancy" ]
|
||||||
|
|
||||||
it "humidifierController subscribes to the door sensor" $
|
it "humidifierController subscribes to the door sensor" $
|
||||||
entities humidifierController
|
entities humidifierController
|
||||||
@@ -62,18 +62,18 @@ drawerSpec = describe "bedroomDrawerController" $ do
|
|||||||
|
|
||||||
it "turns the drawer light on when the drawer opens" $
|
it "turns the drawer light on when the drawer opens" $
|
||||||
services (runHASS bedroomDrawerController [drawerState "on"])
|
services (runHASS bedroomDrawerController [drawerState "on"])
|
||||||
`shouldBe` [[switch [entity] True]]
|
`shouldBe` [[switchService [entity] True]]
|
||||||
|
|
||||||
it "turns the drawer light off when the drawer closes" $
|
it "turns the drawer light off when the drawer closes" $
|
||||||
services (runHASS bedroomDrawerController [drawerState "off"])
|
services (runHASS bedroomDrawerController [drawerState "off"])
|
||||||
`shouldBe` [[switch [entity] False]]
|
`shouldBe` [[switchService [entity] False]]
|
||||||
|
|
||||||
it "toggles the light as the drawer opens and closes" $
|
it "toggles the light as the drawer opens and closes" $
|
||||||
services (runHASS bedroomDrawerController
|
services (runHASS bedroomDrawerController
|
||||||
[ drawerState "on", drawerState "off", drawerState "on" ])
|
[ drawerState "on", drawerState "off", drawerState "on" ])
|
||||||
`shouldBe` [ [switch [entity] True]
|
`shouldBe` [ [switchService [entity] True]
|
||||||
, [switch [entity] False]
|
, [switchService [entity] False]
|
||||||
, [switch [entity] True]
|
, [switchService [entity] True]
|
||||||
]
|
]
|
||||||
|
|
||||||
it "ignores state events for other entities" $
|
it "ignores state events for other entities" $
|
||||||
@@ -91,15 +91,15 @@ buttonSpec = describe "bedroomButtonController" $ do
|
|||||||
|
|
||||||
it "Masse single click turns on his nightstand scene (lowest)" $
|
it "Masse single click turns on his nightstand scene (lowest)" $
|
||||||
concat (services (runHASS bedroomButtonController [masseButton "1_short_release"]))
|
concat (services (runHASS bedroomButtonController [masseButton "1_short_release"]))
|
||||||
`shouldContain` [activateSceneWith "scene.makuuhuone_masse" (Just $ object ["transition" .= (5 :: Int)])]
|
`shouldContain` [activateScene "scene.makuuhuone_masse"]
|
||||||
|
|
||||||
it "Masse double click turns on the middle scene" $
|
it "Masse double click turns on the middle scene" $
|
||||||
concat (services (runHASS bedroomButtonController [masseButton "1_double_press"]))
|
concat (services (runHASS bedroomButtonController [masseButton "1_double_press"]))
|
||||||
`shouldContain` [activateSceneWith "scene.makuuhuone_keski" (Just $ object ["transition" .= (5 :: Int)])]
|
`shouldContain` [activateScene "scene.makuuhuone_keski"]
|
||||||
|
|
||||||
it "Masse long click turns on the bright scene" $
|
it "Masse long click turns on the bright scene" $
|
||||||
concat (services (runHASS bedroomButtonController [masseButton "1_long_press"]))
|
concat (services (runHASS bedroomButtonController [masseButton "1_long_press"]))
|
||||||
`shouldContain` [activateSceneWith "scene.makuuhuone_kirkas" (Just $ object ["transition" .= (5 :: Int)])]
|
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
|
||||||
|
|
||||||
it "Masse off click turns the bedroom lights off" $
|
it "Masse off click turns the bedroom lights off" $
|
||||||
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
|
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
|
||||||
@@ -107,15 +107,15 @@ buttonSpec = describe "bedroomButtonController" $ do
|
|||||||
|
|
||||||
it "Enishen single click turns on her nightstand scene (lowest)" $
|
it "Enishen single click turns on her nightstand scene (lowest)" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
|
||||||
`shouldContain` [activateSceneWith "scene.makuuhuone_jemina" (Just $ object ["transition" .= (5 :: Int)])]
|
`shouldContain` [activateScene "scene.makuuhuone_jemina"]
|
||||||
|
|
||||||
it "Enishen double click turns on the middle scene" $
|
it "Enishen double click turns on the middle scene" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "1_double_press"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "1_double_press"]))
|
||||||
`shouldContain` [activateSceneWith "scene.makuuhuone_keski" (Just $ object ["transition" .= (5 :: Int)])]
|
`shouldContain` [activateScene "scene.makuuhuone_keski"]
|
||||||
|
|
||||||
it "Enishen long click turns on the bright scene" $
|
it "Enishen long click turns on the bright scene" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "1_long_press"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "1_long_press"]))
|
||||||
`shouldContain` [activateSceneWith "scene.makuuhuone_kirkas" (Just $ object ["transition" .= (5 :: Int)])]
|
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
|
||||||
|
|
||||||
it "Enishen off click turns the bedroom lights off" $
|
it "Enishen off click turns the bedroom lights off" $
|
||||||
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
|
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
|
||||||
|
|||||||
+18
-10
@@ -18,9 +18,13 @@ import HomeAssistant.Controller (HASSEff (..), Service (..), Target(..))
|
|||||||
import HomeAssistant.Runtime.Bus
|
import HomeAssistant.Runtime.Bus
|
||||||
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
|
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
|
||||||
import HomeAssistant.Runtime.Metrics (registerAppMetrics)
|
import HomeAssistant.Runtime.Metrics (registerAppMetrics)
|
||||||
import Katip (Namespace (Namespace), runKatipContextT, Severity (..))
|
import Control.Monad.IO.Class (liftIO)
|
||||||
|
import Katip (Namespace (Namespace), runKatipContextT)
|
||||||
|
import Katip.Monadic (runNoLoggingT)
|
||||||
|
import Support (withTestLogEnv)
|
||||||
import qualified System.Metrics as Metrics
|
import qualified System.Metrics as Metrics
|
||||||
import System.IO.Temp (withTempDirectory)
|
import System.IO.Temp (withTempDirectory)
|
||||||
|
import System.Timeout (timeout)
|
||||||
import Test.Hspec
|
import Test.Hspec
|
||||||
|
|
||||||
spec :: Spec
|
spec :: Spec
|
||||||
@@ -43,15 +47,17 @@ spec = describe "Bus" $ do
|
|||||||
(_, svc') <- atomically $ readTChan (busOutbound bus)
|
(_, svc') <- atomically $ readTChan (busOutbound bus)
|
||||||
svc' `shouldBe` svc
|
svc' `shouldBe` svc
|
||||||
|
|
||||||
it "channelHassEval drops CallService when the handler is disabled" $
|
it "channelHassEval writes CallService to the outbound channel even when the handler is disabled" $
|
||||||
withTestFlagsBus $ \bus -> do
|
withTestFlagsBus $ \bus -> do
|
||||||
setEnabled (busFlags bus) "test-handler" False
|
setEnabled (busFlags bus) "test-handler" False
|
||||||
let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler"
|
let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler"
|
||||||
svc = Service "light" "turn_on" Nothing [EntityId "light.test"]
|
svc = Service "light" "turn_on" Nothing [EntityId "light.test"]
|
||||||
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
|
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
|
||||||
channelHassEval bus (CallService req svc)
|
channelHassEval bus (CallService req svc)
|
||||||
atomically (isEmptyTChan (busOutbound bus)) `shouldReturn` True
|
result <- timeout 1000000 $ atomically $ readTChan (busOutbound bus)
|
||||||
|
case result of
|
||||||
|
Nothing -> expectationFailure "expected a write to the outbound channel"
|
||||||
|
Just (_, svc') -> svc' `shouldBe` svc
|
||||||
|
|
||||||
it "generates unique sequential call ids" $ do
|
it "generates unique sequential call ids" $ do
|
||||||
gen <- mkCallIdGen 0
|
gen <- mkCallIdGen 0
|
||||||
@@ -64,8 +70,8 @@ spec = describe "Bus" $ do
|
|||||||
store <- Metrics.newStore
|
store <- Metrics.newStore
|
||||||
m <- registerAppMetrics store
|
m <- registerAppMetrics store
|
||||||
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
|
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
|
||||||
flags <- loadFlags dir []
|
flags <- runNoLoggingT (loadFlags dir [])
|
||||||
withBus InfoS m flags $ \bus -> do
|
withTestLogEnv $ \le -> withBus le m flags $ \bus -> do
|
||||||
recordInbound bus
|
recordInbound bus
|
||||||
recordInbound bus
|
recordInbound bus
|
||||||
recordOutbound bus
|
recordOutbound bus
|
||||||
@@ -77,14 +83,16 @@ withTestBus :: (Bus -> IO a) -> IO a
|
|||||||
withTestBus action = do
|
withTestBus action = do
|
||||||
store <- Metrics.newStore
|
store <- Metrics.newStore
|
||||||
m <- registerAppMetrics store
|
m <- registerAppMetrics store
|
||||||
|
withTestLogEnv $ \le ->
|
||||||
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
|
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
|
||||||
flags <- loadFlags dir []
|
flags <- runNoLoggingT (loadFlags dir [])
|
||||||
withBus InfoS m flags action
|
withBus le m flags action
|
||||||
|
|
||||||
withTestFlagsBus :: (Bus -> IO a) -> IO a
|
withTestFlagsBus :: (Bus -> IO a) -> IO a
|
||||||
withTestFlagsBus action = do
|
withTestFlagsBus action = do
|
||||||
store <- Metrics.newStore
|
store <- Metrics.newStore
|
||||||
m <- registerAppMetrics store
|
m <- registerAppMetrics store
|
||||||
|
withTestLogEnv $ \le ->
|
||||||
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
|
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
|
||||||
flags <- loadFlags dir ["test-handler"]
|
flags <- runNoLoggingT (loadFlags dir ["test-handler"])
|
||||||
withBus InfoS m flags action
|
withBus le m flags action
|
||||||
+28
-1
@@ -4,12 +4,23 @@ module ConnectionSpec (spec) where
|
|||||||
|
|
||||||
import AFRP (Request(..))
|
import AFRP (Request(..))
|
||||||
import Data.Aeson (object, (.=))
|
import Data.Aeson (object, (.=))
|
||||||
|
import qualified Data.HashMap.Strict as HM
|
||||||
import Data.Maybe (fromJust)
|
import Data.Maybe (fromJust)
|
||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
import Data.Time (UTCTime (..), utc)
|
import Data.Time (UTCTime (..), utc)
|
||||||
import Data.UUID (fromString)
|
import Data.UUID (fromString)
|
||||||
import HomeAssistant.Controller (Service (..), Target(..))
|
import HomeAssistant.Controller (Service (..), Target(..))
|
||||||
import HomeAssistant.Runtime.Connection (encodeService, isTriggerEvent)
|
import HomeAssistant.Runtime.Bus
|
||||||
|
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
|
||||||
|
import HomeAssistant.Runtime.Metrics (registerAppMetrics)
|
||||||
|
import HomeAssistant.Runtime.RateLimit (registerRateLimitMetrics, slidingWindowLimiter)
|
||||||
|
import HomeAssistant.Runtime.Connection (dispatchService, encodeService, isTriggerEvent)
|
||||||
|
import Katip (Namespace (Namespace), runKatipContextT)
|
||||||
|
import Katip.Monadic (runNoLoggingT)
|
||||||
|
import Support (withTestLogEnv)
|
||||||
|
import System.IO.Temp (withTempDirectory)
|
||||||
|
import qualified System.Metrics as Metrics
|
||||||
|
import System.Timeout (timeout)
|
||||||
import Test.Hspec
|
import Test.Hspec
|
||||||
|
|
||||||
spec :: Spec
|
spec :: Spec
|
||||||
@@ -44,6 +55,22 @@ spec = do
|
|||||||
it "is false when there is no type" $
|
it "is false when there is no type" $
|
||||||
isTriggerEvent (object ["id" .= (1 :: Int)]) `shouldBe` False
|
isTriggerEvent (object ["id" .= (1 :: Int)]) `shouldBe` False
|
||||||
|
|
||||||
|
describe "dispatchService" $ do
|
||||||
|
it "skips disabled handlers without consuming a call id" $ do
|
||||||
|
store <- Metrics.newStore
|
||||||
|
m <- registerAppMetrics store
|
||||||
|
rlMetrics <- registerRateLimitMetrics store
|
||||||
|
limiter <- slidingWindowLimiter rlMetrics 10 20
|
||||||
|
withTempDirectory "/tmp" "connection-spec" $ \dir -> do
|
||||||
|
flags <- runNoLoggingT (loadFlags dir ["test"])
|
||||||
|
setEnabled flags "test" False
|
||||||
|
withTestLogEnv $ \le -> withBus le m flags $ \bus -> do
|
||||||
|
timeout 1000000 (do
|
||||||
|
runKatipContextT (busLogEnv bus) () (Namespace ["connection"]) $
|
||||||
|
dispatchService limiter bus (req 1) (lightOn [EntityId "light.test"])
|
||||||
|
generateCallId (busGen bus)) `shouldReturn` Just 1
|
||||||
|
sample <- Metrics.sampleAll store
|
||||||
|
HM.lookup "hass.service.out" sample `shouldBe` Just (Metrics.Counter 0)
|
||||||
|
|
||||||
req :: Int -> Request
|
req :: Int -> Request
|
||||||
req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
|
req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
module ControllerSpec where
|
||||||
|
import Test.Hspec
|
||||||
|
import Data.Default (def)
|
||||||
|
import HomeAssistant.Controller (Brightness(..), formatLightAttributes, LightAttributes(..))
|
||||||
|
import Data.Aeson (object, (.=))
|
||||||
|
import HomeAssistant.Controller ()
|
||||||
|
|
||||||
|
|
||||||
|
spec :: Spec
|
||||||
|
spec = describe "Generic controller" $
|
||||||
|
describe "Light settings" $ do
|
||||||
|
it "formats the default as empty" $
|
||||||
|
formatLightAttributes def `shouldBe` Nothing
|
||||||
|
it "formats the transition" $
|
||||||
|
formatLightAttributes def{lightTransition=Just 5} `shouldBe`
|
||||||
|
Just (object ["transition" .= (5 :: Int)])
|
||||||
|
it "formats the temperature" $
|
||||||
|
formatLightAttributes def{lightColorTemperature=Just 5} `shouldBe`
|
||||||
|
Just (object ["color_temp_kelvin" .= (5 :: Int)])
|
||||||
|
it "formats the brightness as percentage" $
|
||||||
|
formatLightAttributes def{lightBrightness=Just (BrightnessPercent 100)} `shouldBe`
|
||||||
|
Just (object ["brightness_pct" .= (100 :: Int)])
|
||||||
|
it "formats the brightness as absolute" $
|
||||||
|
formatLightAttributes def{lightBrightness=Just (BrightnessAbsolute 200)} `shouldBe`
|
||||||
|
Just (object ["brightness" .= (200 :: Int)])
|
||||||
|
it "formats multiple values" $
|
||||||
|
formatLightAttributes def{lightTransition = Just 5, lightBrightness=Just (BrightnessAbsolute 200)} `shouldBe`
|
||||||
|
Just (object ["brightness" .= (200 :: Int), "transition" .= (5 :: Int)])
|
||||||
+9
-8
@@ -10,6 +10,7 @@ import qualified Data.Map.Strict as M
|
|||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
import qualified Hedgehog.Gen as Gen
|
import qualified Hedgehog.Gen as Gen
|
||||||
import qualified Hedgehog.Range as Range
|
import qualified Hedgehog.Range as Range
|
||||||
|
import Katip.Monadic (runNoLoggingT)
|
||||||
import System.IO.Temp (withTempDirectory)
|
import System.IO.Temp (withTempDirectory)
|
||||||
import Test.Hspec
|
import Test.Hspec
|
||||||
import Test.Hspec.Hedgehog
|
import Test.Hspec.Hedgehog
|
||||||
@@ -21,7 +22,7 @@ spec = describe "Flags" $ do
|
|||||||
describe "loadFlags" $ do
|
describe "loadFlags" $ do
|
||||||
it "defaults all names to True when the file is missing (opt-out)" $
|
it "defaults all names to True when the file is missing (opt-out)" $
|
||||||
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
||||||
flags <- loadFlags dir ["a", "b"]
|
flags <- runNoLoggingT (loadFlags dir ["a", "b"])
|
||||||
m <- allFlags flags
|
m <- allFlags flags
|
||||||
m `shouldBe` M.fromList [("a" :: Text, True), ("b", True)]
|
m `shouldBe` M.fromList [("a" :: Text, True), ("b", True)]
|
||||||
|
|
||||||
@@ -29,7 +30,7 @@ spec = describe "Flags" $ do
|
|||||||
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
||||||
let path = dir <> "/handlers.json"
|
let path = dir <> "/handlers.json"
|
||||||
writeFile path "{\"b\": false}"
|
writeFile path "{\"b\": false}"
|
||||||
flags <- loadFlags dir ["a", "b"]
|
flags <- runNoLoggingT (loadFlags dir ["a", "b"])
|
||||||
m <- allFlags flags
|
m <- allFlags flags
|
||||||
m `shouldBe` M.fromList [("a" :: Text, True), ("b" :: Text, False)]
|
m `shouldBe` M.fromList [("a" :: Text, True), ("b" :: Text, False)]
|
||||||
|
|
||||||
@@ -37,7 +38,7 @@ spec = describe "Flags" $ do
|
|||||||
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
||||||
let path = dir <> "/handlers.json"
|
let path = dir <> "/handlers.json"
|
||||||
writeFile path "not json at all"
|
writeFile path "not json at all"
|
||||||
flags <- loadFlags dir ["a"]
|
flags <- runNoLoggingT (loadFlags dir ["a"])
|
||||||
m <- allFlags flags
|
m <- allFlags flags
|
||||||
m `shouldBe` M.fromList [("a" :: Text, True)]
|
m `shouldBe` M.fromList [("a" :: Text, True)]
|
||||||
|
|
||||||
@@ -46,29 +47,29 @@ spec = describe "Flags" $ do
|
|||||||
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
||||||
let path = dir <> "/handlers.json"
|
let path = dir <> "/handlers.json"
|
||||||
writeFile path "{\"a\": false}"
|
writeFile path "{\"a\": false}"
|
||||||
flags <- loadFlags dir ["a"]
|
flags <- runNoLoggingT (loadFlags dir ["a"])
|
||||||
isEnabled flags "a" `shouldReturn` False
|
isEnabled flags "a" `shouldReturn` False
|
||||||
|
|
||||||
it "defaults unknown names to True" $
|
it "defaults unknown names to True" $
|
||||||
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
||||||
flags <- loadFlags dir []
|
flags <- runNoLoggingT (loadFlags dir [])
|
||||||
isEnabled flags "unknown" `shouldReturn` True
|
isEnabled flags "unknown" `shouldReturn` True
|
||||||
|
|
||||||
describe "setEnabled" $ do
|
describe "setEnabled" $ do
|
||||||
it "updates the in-memory map and persists to disk" $
|
it "updates the in-memory map and persists to disk" $
|
||||||
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
||||||
flags <- loadFlags dir ["a"]
|
flags <- runNoLoggingT (loadFlags dir ["a"])
|
||||||
setEnabled flags "a" False
|
setEnabled flags "a" False
|
||||||
isEnabled flags "a" `shouldReturn` False
|
isEnabled flags "a" `shouldReturn` False
|
||||||
-- reload from disk to confirm persistence
|
-- reload from disk to confirm persistence
|
||||||
flags' <- loadFlags dir ["a"]
|
flags' <- runNoLoggingT (loadFlags dir ["a"])
|
||||||
isEnabled flags' "a" `shouldReturn` False
|
isEnabled flags' "a" `shouldReturn` False
|
||||||
|
|
||||||
it "concurrent writes leave the file consistent with the TVar" $
|
it "concurrent writes leave the file consistent with the TVar" $
|
||||||
hedgehog $ do
|
hedgehog $ do
|
||||||
n <- forAll $ Gen.int (Range.linear 1 50)
|
n <- forAll $ Gen.int (Range.linear 1 50)
|
||||||
liftIO $ withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
liftIO $ withTempDirectory "/tmp" "flags-spec" $ \dir -> do
|
||||||
flags <- loadFlags dir ["x"]
|
flags <- runNoLoggingT (loadFlags dir ["x"])
|
||||||
mapConcurrently_ (\i -> setEnabled flags "x" (even i)) [1 .. n]
|
mapConcurrently_ (\i -> setEnabled flags "x" (even i)) [1 .. n]
|
||||||
m <- allFlags flags
|
m <- allFlags flags
|
||||||
decoded <- decodeFileStrict (dir <> "/handlers.json")
|
decoded <- decodeFileStrict (dir <> "/handlers.json")
|
||||||
|
|||||||
+4
-3
@@ -10,6 +10,7 @@ import HomeAssistant.Controller
|
|||||||
import HomeAssistant.Controller.Kitchen
|
import HomeAssistant.Controller.Kitchen
|
||||||
import Support
|
import Support
|
||||||
import Test.Hspec
|
import Test.Hspec
|
||||||
|
import Data.Default (def)
|
||||||
|
|
||||||
-- Helper functions for creating test events
|
-- Helper functions for creating test events
|
||||||
testDinnerLightLevel :: Int -> Event Value
|
testDinnerLightLevel :: Int -> Event Value
|
||||||
@@ -34,12 +35,12 @@ dinnerTableSpec = describe "dinnerTableController" $ do
|
|||||||
|
|
||||||
it "turns lights on when presence is occupied and light level is low" $ do
|
it "turns lights on when presence is occupied and light level is low" $ do
|
||||||
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"])
|
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"])
|
||||||
`shouldBe` [[switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] (On Nothing)]]
|
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] (On def)]]
|
||||||
|
|
||||||
it "turns lights off when presence is unoccupied" $ do
|
it "turns lights off when presence is unoccupied" $ do
|
||||||
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "off"])
|
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "off"])
|
||||||
`shouldBe` [[switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], []]
|
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], []]
|
||||||
|
|
||||||
it "does nothing on Tick" $ do
|
it "does nothing on Tick" $ do
|
||||||
services (runHASS dinnerTableController [Tick])
|
services (runHASS dinnerTableController [Tick])
|
||||||
`shouldBe` [[switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True]]
|
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True]]
|
||||||
@@ -12,6 +12,7 @@ import qualified KitchenSpec
|
|||||||
import qualified LivingroomSpec
|
import qualified LivingroomSpec
|
||||||
import qualified MetricsSpec
|
import qualified MetricsSpec
|
||||||
import qualified RuntimeSpec
|
import qualified RuntimeSpec
|
||||||
|
import qualified ControllerSpec
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = hspec $ do
|
main = hspec $ do
|
||||||
@@ -26,3 +27,4 @@ main = hspec $ do
|
|||||||
LivingroomSpec.spec
|
LivingroomSpec.spec
|
||||||
MetricsSpec.spec
|
MetricsSpec.spec
|
||||||
RuntimeSpec.spec
|
RuntimeSpec.spec
|
||||||
|
ControllerSpec.spec
|
||||||
@@ -10,10 +10,13 @@ module Support
|
|||||||
, sec
|
, sec
|
||||||
, stateEvent
|
, stateEvent
|
||||||
, buttonEvent
|
, buttonEvent
|
||||||
|
, withTestLogEnv
|
||||||
) where
|
) where
|
||||||
|
|
||||||
|
import Control.Exception (bracket)
|
||||||
import Control.Monad.Fix (MonadFix (..))
|
import Control.Monad.Fix (MonadFix (..))
|
||||||
import Data.Aeson (Value, object, (.=))
|
import Data.Aeson (Value, object, (.=))
|
||||||
|
import Katip (LogEnv, closeScribes, initLogEnv)
|
||||||
import qualified Data.Text as T
|
import qualified Data.Text as T
|
||||||
import Data.Time (UTCTime (..), utc)
|
import Data.Time (UTCTime (..), utc)
|
||||||
import Data.UUID (nil)
|
import Data.UUID (nil)
|
||||||
@@ -42,6 +45,10 @@ instance Monad Acc where
|
|||||||
instance MonadFix Acc where
|
instance MonadFix Acc where
|
||||||
mfix f = Acc $ \s -> let (a, s') = runAcc (f a) s in (a, s')
|
mfix f = Acc $ \s -> let (a, s') = runAcc (f a) s in (a, s')
|
||||||
|
|
||||||
|
-- | A silent LogEnv: no scribes registered, so nothing is written anywhere.
|
||||||
|
withTestLogEnv :: (LogEnv -> IO a) -> IO a
|
||||||
|
withTestLogEnv = bracket (initLogEnv "test" "test") closeScribes
|
||||||
|
|
||||||
-- | Interpret `HASSEff` in `Acc`: record `CallService`, drop tracing/debug.
|
-- | Interpret `HASSEff` in `Acc`: record `CallService`, drop tracing/debug.
|
||||||
interp :: HASSEff a -> Acc a
|
interp :: HASSEff a -> Acc a
|
||||||
interp (CallService _ svc) = Acc $ \s -> ((), s ++ [svc])
|
interp (CallService _ svc) = Acc $ \s -> ((), s ++ [svc])
|
||||||
|
|||||||
Reference in new issue
Block a user