40 Commits
Author SHA1 Message Date
MasseR 6bcab1a0d8 Update tests 2026-09-30 15:01:17 +03:00
MasseR cceddad037 Capped based on light level 2026-09-30 14:27:50 +03:00
MasseR c75fc1a7b9 Logging and really not working light restoration 2026-09-30 13:46:16 +03:00
MasseR 1098be227d Push to journalctl 2026-09-30 12:33:31 +03:00
MasseR a427acd6ed Fix warnings 2026-09-30 09:05:48 +03:00
MasseR aee34f4e14 Make flag-decision tests fail fast and assert the outbound metric 2026-09-30 08:57:40 +03:00
MasseR 526710ef71 Simplify channelHassEval now that the writer owns the flag decision 2026-09-30 08:56:07 +03:00
MasseR c2425e8fb0 Move handler flag check from bus to writer with skip logging 2026-09-30 08:06:59 +03:00
MasseR a7a11e96b7 Complete rename vocabulary (childrenBedroomButton, toIkeaRemoteAction) 2026-09-30 00:21:24 +03:00
MasseR adce7c8427 Split Controller.hs into vertical submodules behind umbrella re-export 2026-09-30 00:07:31 +03:00
MasseR 9e00aeb6a2 Rename entity-list and snapshot helpers for consistency 2026-09-29 23:52:46 +03:00
MasseR b643fe55b1 Rename switch to switchService to avoid AFRP name conflict 2026-09-29 23:47:58 +03:00
MasseR 138b62c54a Rename IkeaController to IkeaRemoteAction, fix brightness typo 2026-09-29 23:44:56 +03:00
MasseR 889091d321 Regenerate default.nix (data-default was missing from the derivation) 2026-09-29 23:40:20 +03:00
MasseR c2426dec3d Unify per-room Lights enums into shared LightingMode 2026-09-29 23:38:43 +03:00
MasseR ad023a1ba2 Rename light observation layer (LightStatus, lightSignal, brightness, temperature) 2026-09-29 23:19:34 +03:00
MasseR 7ce994e814 Rename light command layer (Light, LightSettings, BrightnessSettings) 2026-09-29 23:14:07 +03:00
MasseR fefeae6301 Store a custom snapshot of lights 2026-09-29 22:51:37 +03:00
MasseR fcaccfdeb0 Faster transition 2026-09-29 20:42:14 +03:00
MasseR 73d4255fd7 Update tests 2026-09-29 20:01:03 +03:00
MasseR 7ad36d8ccb More transition stuff 2026-09-29 19:48:16 +03:00
MasseR f4c82df968 Scene transitions 2026-09-29 18:05:51 +03:00
MasseR 219f75c0e4 Remove the debug line
I thought I already had..?
2026-09-29 11:35:24 +03:00
MasseR 7ed846d0fc Fix the ambience mode 2026-09-29 11:33:56 +03:00
MasseR 53c36a81de Trial age 2026-09-25 13:55:29 +03:00
MasseR 1bf2258167 Merge branch 'runtime-flags': runtime handler toggling 2026-09-25 13:17:08 +03:00
MasseR 4d8cb8dc36 Log and return 500 when handler flag persistence fails 2026-09-25 13:14:25 +03:00
MasseR 1697d55ad5 Drop build-time controller flag, run all controllers, consolidate paths 2026-09-25 13:10:26 +03:00
MasseR bd1402ab3a Add REST endpoints for handler flags 2026-09-25 13:09:25 +03:00
MasseR c412435172 Gate CallService by handler flags on the Bus 2026-09-25 13:07:40 +03:00
MasseR 3b08988e30 Route Flags load warnings to stderr 2026-09-25 13:02:14 +03:00
MasseR 44497173de Add Flags module for runtime handler toggling 2026-09-25 13:01:44 +03:00
MasseR 894d8f8436 Add requestHandler field to Request 2026-09-25 12:59:14 +03:00
MasseR bd5f97f96e Merge pull request 'Replace scotty with servant' (#4) from servant into main
Reviewed-on: #4
2026-09-25 12:10:58 +03:00
MasseR d6f785662b Logging in http 2026-09-25 12:10:24 +03:00
MasseR 5d16bf4ade Move http to separate module 2026-09-25 11:54:36 +03:00
MasseR 05bd609c7e Replace scotty with servant 2026-09-25 11:48:42 +03:00
MasseR 4ea75beb7b Merge pull request 'Plant lights' (#3) from plant-light into main
Reviewed-on: #3
2026-09-25 10:37:26 +03:00
MasseR 96d3482af8 Merge pull request 'Use scenes instead of stateful applications of adaptive sleep mode' (#2) from bedroom-sleep-mode-via-scenes into main
Reviewed-on: #2
2026-09-25 10:37:20 +03:00
MasseR a7becaf2d4 Use scenes instead of stateful applications of adaptive sleep mode 2026-09-25 09:55:48 +03:00
44 changed files with 1422 additions and 622 deletions

No files matched your search

+1
View File
@@ -10,3 +10,4 @@ docs/superpowers
*.eventlog
*.eventlog.html
*.rrd
*.rrd.*bak*
+5 -1
View File
@@ -1,3 +1,7 @@
creation_rules:
- path_regex: "secrets.yaml"
pgp: "95DBE64C2EA64D6B0E0C8C2F9DE6E04ED1918118"
age:
# usb-c yubikey
- "age1yubikey1qw7m7rad6malegqypgntr7qmu97xrxxurp0c00s23263nuxnpek6w0jye60"
# usb-a yubikey
- "age1yubikey1qdnx7jum6k4fzenkqj8y5met9hyq6lqxrpzrl2788wr0q445vhupzuqtpk0"
+1
View File
@@ -10,6 +10,7 @@ reactive programming (AFRP). Haskell, built with cabal.
- Vertical modules: split by feature/concept, not by layer.
- Comments are minimal. They describe the contract, not the implementation,
and should stay stable as the implementation changes.
- Never ever log directly to stdout via `putStr` and friends. Always use proper logging functions
## Build
-1
View File
@@ -4,5 +4,4 @@ import qualified HomeAssistant.Runtime (defaultMain)
main :: IO ()
main = do
putStrLn "Hello, Haskell!"
HomeAssistant.Runtime.defaultMain
+13 -9
View File
@@ -1,8 +1,10 @@
{ mkDerivation, aeson, annotated-exception, async, base, bytestring
, cereal, cereal-conduit, conduit, containers, directory, ekg-core
, filepath, hedgehog, hspec, hspec-hedgehog, http-types, katip
, lens, lens-aeson, lib, network, process, retry, scotty, stm, text
, time, unordered-containers, uuid, wai, warp, websockets
, cereal, cereal-conduit, cereal-text, conduit, containers
, data-default, directory, ekg-core, exceptions, filepath, hedgehog
, 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
, unordered-containers, uuid, wai, warp, websockets
}:
mkDerivation {
pname = "home-assistant-controller";
@@ -12,15 +14,17 @@ mkDerivation {
isExecutable = true;
libraryHaskellDepends = [
aeson annotated-exception async base bytestring cereal
cereal-conduit conduit containers directory ekg-core filepath
http-types katip lens lens-aeson network process retry scotty stm
text time unordered-containers uuid wai warp websockets
cereal-conduit cereal-text conduit containers data-default
directory ekg-core exceptions filepath http-media http-types katip
lens lens-aeson libsystemd-journal network process retry servant
servant-server stm text time unliftio unordered-containers uuid wai
warp websockets
];
executableHaskellDepends = [ base ];
testHaskellDepends = [
aeson annotated-exception async base bytestring cereal containers
directory ekg-core hedgehog hspec hspec-hedgehog katip process stm
text time unordered-containers uuid
data-default directory ekg-core hedgehog hspec hspec-hedgehog katip
process servant stm temporary text time unordered-containers uuid
];
license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause";
mainProgram = "home-assistant-controller";
+38 -12
View File
@@ -62,18 +62,32 @@ library
exposed-modules: AFRP
, HomeAssistant.Controller
, HomeAssistant.Controller.Bedroom
, HomeAssistant.Controller.Hallway
, HomeAssistant.Controller.Kitchen
, 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.Presence
, HomeAssistant.Controller.Ruuvi
, HomeAssistant.Controller.Scene
, HomeAssistant.Controller.Service
, HomeAssistant.Controller.Switch
, HomeAssistant.Runtime
, HomeAssistant.Runtime.Bus
, HomeAssistant.Runtime.Connection
, HomeAssistant.Runtime.Flags
, HomeAssistant.Runtime.Graphing
, HomeAssistant.Runtime.Metrics
, HomeAssistant.Runtime.Supervisor
, HomeAssistant.Runtime.RateLimit
, HttpServer
, Katip.Scribes.Journal
-- Modules included in this library but not exported.
-- other-modules:
@@ -84,6 +98,7 @@ library
-- Other library packages from which modules are imported.
build-depends: base ^>=4.20.2.0
, websockets
, http-media
, aeson
, lens-aeson
, lens
@@ -104,15 +119,19 @@ library
, process
, directory
, cereal
, cereal-text
, containers
, data-default
, filepath
, conduit
, cereal-conduit
, scotty
, servant
, servant-server
, http-types
, warp
, wai
, retry
, libsystemd-journal
-- Directories containing source files.
hs-source-dirs: src
@@ -154,14 +173,18 @@ test-suite home-assistant-controller-test
-- Modules included in this executable, other than Main.
other-modules: AFRPLawsSpec
, AFRPSpec
, BedroomSpec
, BusSpec
, ConnectionSpec
, GraphingSpec
, MetricsSpec
, RuntimeSpec
, Support
, AFRPSpec
, BedroomSpec
, BusSpec
, ConnectionSpec
, FlagsSpec
, GraphingSpec
, KitchenSpec
, LivingroomSpec
, MetricsSpec
, RuntimeSpec
, Support
, ControllerSpec
-- LANGUAGE extensions used by modules in this package.
-- other-extensions:
@@ -180,8 +203,10 @@ test-suite home-assistant-controller-test
base ^>=4.20.2.0,
home-assistant-controller,
bytestring,
data-default,
hspec,
stm,
servant,
aeson,
cereal,
text,
@@ -196,4 +221,5 @@ test-suite home-assistant-controller-test
ekg-core,
unordered-containers,
process,
directory
directory,
temporary
+21 -21
View File
@@ -1,28 +1,28 @@
HA_TOKEN: ENC[AES256_GCM,data:zs9nTT2EV/OhBiH9alUuupUvYURXj40lxe7IKKWXdExW+BW98yEDHcQr/KNsQ0Iu9+U2GrsA8WpODeM351kI3Owj3rl082tObBJ2jwF1iyYcXhoH3xvbHb+HN802SBOTIO32m+ZwGvIVPjF8W+67eGKTrIUcqnKj7Ab/TchG+mYPLdil0mYjITY+DCUi0mW1nElCaTTexovj4PHlUdA1xIsCYF+XnTypQv8o+Zy8MsMZtdzNQKJG,iv:Lmxmp5y15sqhQvEO7liVk6x3Y26qtoL39TT2MSqZdok=,tag:1Xvs6YUilP/XH0UxYngTIg==,type:str]
HA_HOST: ENC[AES256_GCM,data:MfA+RReJHnKP31bD4YAoZrc=,iv:Z9xDtzPsUER4jQ12BbM2EtnLNggZhOWzCb7VAL2I02g=,tag:/Eogbd2kT7phdhaR/vGNDA==,type:str]
sops:
age:
- enc: |
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IHJKaXRSQSBBeEpPRXVT
NDY2ZUxZRDB5a21waDFoUXJsQkdsbFhQRjhobFBGVDlaZmlpSApGNEpKS1JzUStw
eWFJcUkxbWRtWURLQm0rWWtURXVNVEwvVlRLa3prNFZRCi0tLSBJWjhiL2RLV3ZO
NStpUlVSRHlSTEJWa2ZkenI3T292RnMwaHB6cnJRSW1NCt3zpORUDB2m9V+IK9UI
Z94uFopKZsRxzbxbZWklNykYoryjKfVCTO7sFDxapzr1UlG3UjVp2kgBJeDCEBVt
SwQ=
-----END AGE ENCRYPTED FILE-----
recipient: age1yubikey1qw7m7rad6malegqypgntr7qmu97xrxxurp0c00s23263nuxnpek6w0jye60
- enc: |
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IFVnM21GQSBBNFYvaEM2
MFoyR3NhcDc4eklaTHJaUVZRWlJzT2dkclBOaExLYWZDb05DaQpidVcrRklydWJZ
WUhxQUR1c281R1RtdGlxNy9uMmJPODE1YXQ1K2g3bnFJCi0tLSAwblViWnhPMUNC
dTRoelphM1djcW9DK0NkWE44TSsvYmE5aEtIMW5RVG9vCqO5SqZ73i4wRn9qWyXA
8bW5XLeTN4qCIeMFEKloiAKDUKFWutHt/9SedYUsqMuRmQ9btmWg5TdkHV4S/6iR
qDU=
-----END AGE ENCRYPTED FILE-----
recipient: age1yubikey1qdnx7jum6k4fzenkqj8y5met9hyq6lqxrpzrl2788wr0q445vhupzuqtpk0
lastmodified: "2026-08-21T10:17:59Z"
mac: ENC[AES256_GCM,data:GuNyo/3flhR30e6kds1iXcDGmq0Xq2hqvBmAvYtakKwzUzMocP9vImfxs+MfVNiMGirlkwbihrX5mFSbfORjES/FDTs6p0100H1tkBqPTecW88PC6/66Js9umVevGYbgToCNBjV9mUBu7o7SyU+NYLnZ/8X4xdx0y6/MKnuvjUA=,iv:/nL5AIL80iV3sutjMTmHyF62SRezmX9XyJJ6+o9TdkQ=,tag:SNMu17rgMIhdzZVsGmXyfg==,type:str]
pgp:
- created_at: "2026-08-20T05:39:51Z"
enc: |-
-----BEGIN PGP MESSAGE-----
hQIMA5Urps8/GyTEAQ//ZQeXRy2SHcR2/hVqleE8V9/3u150TWX7GpDPVdjK7pxu
zK1JZSw/FSpNrUPFHXk6rWDm6lv1k/GCx34egHwgumlO1/192nQLMxwNHXhDeJmc
k6y44pb3Z1m/upVp62fIif2/f7X2BIQqGI0nZBaCM6sD5FE8HqXCk+jYw4YMvNZp
I6dtxxnYwW5wK5Gfv86hTHkn2ibDqARMgd0QsB8fv9fpE9iHWTeeSHqkCBVnb5Kn
s0Xk1DeED/ylLAlHfY0p0LVIjeCK5KCQCbIHXh4yb8ioxUxg9LQp8glXbjqbfaBx
FadLksLDxBuO0CWxAB4bVk4G/MKCL1nN3KzZBWfy96aknHHGQre0DCe7IxfmSYjd
f5UhfeFCVrWQTOtaoq3Oimw6CFeoGe04FKogQmZOWK1zmJmHxjCRGn4n5vzEZB1g
Cq+fzDLl2+Krr91Wq/xGwatoWaPl+SDzw1i7CnfGhWJn50BtO/YI1229yLSyANhs
M2R9JXxiWFst8xur0nJBKkzH+EZpaVOOLT7FgFpf/vWOO/se1kVPaMAhg6fQ3IwJ
JphPD+FTkTDY4GBefVP/qOhOnibcIjhwTiDWP6ppcaOxgVjyDyLsqS96jYSwfyKQ
puDyzrD4BlLv1lc2lULCtgMwZj428Vpd7YI1SjnxxKnKhIQ1IZx0ddneHn9fSivS
XgE6NpQKQ110FFYse8P1fb2yNaYb2ZRbLh0cUOe2qcTATTvK5OdDVlgCjNsO8Fgl
OO8hwmsk+1QziCwO4Md8NPdyNn4Kup1iRojMyAh23CT5LyYXoccakWvF/awLvz8=
=nX50
-----END PGP MESSAGE-----
fp: 95DBE64C2EA64D6B0E0C8C2F9DE6E04ED1918118
unencrypted_suffix: _unencrypted
version: 3.13.3
+17 -8
View File
@@ -42,6 +42,7 @@ module AFRP
, load
, stepAuto
, stepAutoSerializing
, snapshot
) where
import Control.Category (Category(..), (>>>))
@@ -55,7 +56,7 @@ import qualified Data.Set as S
import qualified Data.Text as T
import Data.Serialize (Get, Putter, Serialize (put), runGet, get)
import qualified Data.ByteString as B
import Control.Exception (IOException, handle, throwIO)
import Control.Exception (IOException)
import System.IO.Error (isDoesNotExistError)
import GHC.Generics (Generic)
import Data.Sequence (Seq, (|>))
@@ -64,6 +65,8 @@ import Control.Monad.IO.Class (MonadIO, liftIO)
import Conduit (ConduitT, (.|))
import qualified Data.Conduit.Cereal as CC
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) }
@@ -103,9 +106,10 @@ mergeCodec (Codec agetter aputter) (Codec bgetter bputter) = Codec (mergeGet age
data Pair a b = Pair !a !b
data Request = Request
{ requestTime :: !UTCTime
, requestTimeZone :: !TimeZone
, requestTraceId :: !UUID
{ requestTime :: !UTCTime
, requestTimeZone :: !TimeZone
, requestTraceId :: !UUID
, requestHandler :: !T.Text
} deriving (Show, Eq)
@@ -245,13 +249,13 @@ save path s
isDirty _ = False
load :: forall m a b. FilePath -> Auto m a b -> IO (DecodedAuto m a b)
load path a = handle defaultOnMissingFile (flip deserialize a <$> B.readFile path)
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 <$> liftIO (B.readFile path))
where
defaultOnMissingFile :: IOException -> IO (DecodedAuto m a b)
defaultOnMissingFile :: IOException -> m (DecodedAuto eff a b)
defaultOnMissingFile e
| 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
-- change as the machine steps, so the runtime can read it once to build
@@ -324,6 +328,11 @@ hold def = mapAccum step def id
Tick -> prev
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 = arr $ \case
+12 -264
View File
@@ -1,267 +1,15 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE GADTs #-}
module HomeAssistant.Controller
( Service(..)
, 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
, ikeaBoxRemote
, IkeaController(..)
( module Export
) where
import AFRP (Mealy (..), eff, Event(..), events, filterA, (>>|), toEvent, Request, hold, lMerge, waitFor, tag, edge)
import Control.Arrow (Arrow(..), returnA)
import Control.Category ((>>>))
import Data.Aeson (Value, object, (.=))
import qualified Data.Text as T
import qualified Data.Set as S
import Control.Lens (has, only, (^?), to, traversed)
import Data.Aeson.Lens (key, _String, _Integral)
import qualified Data.Text.Lens as TL
import Data.Bool (bool)
import Data.Serialize (Serialize)
import GHC.Generics (Generic)
import Data.Time (NominalDiffTime)
data Target = EntityId !T.Text | AreaId !T.Text
deriving (Show,Eq,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 = Service
{ serviceDomain="scene"
, serviceName= "turn_on"
, serviceTarget= [EntityId sceneId]
, serviceData = Nothing
}
import HomeAssistant.Controller.Service as Export
import HomeAssistant.Controller.Effect as Export
import HomeAssistant.Controller.Entity as Export
import HomeAssistant.Controller.Presence as Export
import HomeAssistant.Controller.Door as Export
import HomeAssistant.Controller.Switch as Export
import HomeAssistant.Controller.Scene as Export
import HomeAssistant.Controller.Ikea as Export
import HomeAssistant.Controller.Light.Command as Export
import HomeAssistant.Controller.Light.Observation as Export
import HomeAssistant.Controller.Light.Mode as Export
+52 -51
View File
@@ -1,5 +1,6 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HomeAssistant.Controller.Bedroom where
import HomeAssistant.Controller
@@ -10,11 +11,16 @@ import Control.Arrow ((>>>), returnA, arr, Arrow (..))
import Data.Bool (bool)
import Data.Time (NominalDiffTime)
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]
bedroomLights = map EntityId ["light.bedroom_masse","light.bedroom_jemina","light.bedroom_ceiling","light.bedroom_led_switch"]
bedroomLightTargets :: [Target]
bedroomLightTargets = map EntityId ["light.bedroom_masse","light.bedroom_jemina","light.bedroom_ceiling","light.bedroom_led_switch"]
createBedroomScene :: Service
createBedroomScene = Service
@@ -22,22 +28,16 @@ createBedroomScene = Service
, serviceName= "create"
, serviceData= Just $ object
[ "scene_id" .= ("makuuhuone_lights_snapshot" :: T.Text)
, "snapshot_entities" .= [l | EntityId l <- bedroomLights]
, "snapshot_entities" .= [l | EntityId l <- bedroomLightTargets]
]
, serviceTarget= []
}
data PresenceLights
= LightsOn -- Restore lights
| LightsOff -- Timer expired, darkness
| LightsSleep -- No presence detected, sleep mode
deriving Show
-- Bedroom presence
bedroomPresence :: HASS (Event Value) (Event Presence)
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
presenceLightEvents :: HASS (Event Value) (Event PresenceLights)
presenceLightEvents :: HASS (Event Value) (Event LightingMode)
presenceLightEvents =
bedroomPresence >>> AFRP.hold Unoccupied
>>> arr lightWanted
@@ -45,35 +45,58 @@ presenceLightEvents =
>>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
where
lightWanted o = o == Occupied
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightsSleep)
onEvent = AFRP.edge >>> arr (AFRP.tag LightsOn)
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightsOff)
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightingSleep)
onEvent = AFRP.edge >>> arr (AFRP.tag LightingOn)
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightingOff)
bedroomLightStatus :: HASS (Event Value) (Map T.Text LightObservation)
bedroomLightStatus = 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 = proc x -> do
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
Event LightsOff -> do
callService (light bedroomLights Off) -< ()
Event LightsOn -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_lights_snapshot") -< ()
Event LightsSleep -> do
callService createBedroomScene -< ()
adaptiveMode -< True
sleepMode -< True
Event LightingOff -> do
callService (light bedroomLightTargets Off) -< ()
Event LightingOn -> do
callServicesDyn (\(c,xs) -> concatMap (uncurry (toLight c)) xs) -< (capped, M.toList (getSnapshot snap))
returnA -< ()
Event LightingSleep -> do
callService (activateScene "scene.makuuhuone_lepotila") -< ()
_ -> returnA -< ()
where
sleepMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot_sleep_mode"] )
adaptiveMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot"] )
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
= Masse (IkeaButton IkeaGesture)
| Enishen (IkeaButton IkeaGesture)
| Central IkeaController
| Central IkeaRemoteAction
deriving Show
@@ -91,44 +114,22 @@ bedroomButtonController = proc x -> do
-- Any event will cause the sleep mode to be turned off
case ev of
Event (Masse (OnButton ShortRelease)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_masse") -< ()
Event (Masse (OnButton DoubleClick)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_keski") -< ()
Event (Masse (OnButton LongClick)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Masse (OffButton _)) -> do
sleepMode -< False
adaptiveMode -< False
callService (light [AreaId "makuuhuone"] Off) -< ()
Event (Enishen (OnButton ShortRelease)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_jemina") -< ()
Event (Enishen (OnButton DoubleClick)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_keski") -< ()
Event (Enishen (OnButton LongClick)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Enishen (OffButton _)) -> do
sleepMode -< False
adaptiveMode -< False
callService (light [AreaId "makuuhuone"] Off) -< ()
Event (Central _) -> do
sleepMode -< False
adaptiveMode -< False
_ -> returnA -< ()
where
sleepMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot_sleep_mode"] )
adaptiveMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot"] )
@@ -140,8 +141,8 @@ bedroomDrawerController :: HASS (Event Value) ()
bedroomDrawerController = proc x -> do
st <- drawer >>> traceEvent -< x
case st of
Event Open -> callService (switch [entity] True) -< ()
Event Closed -> callService (switch [entity] False) -< ()
Event Open -> callService (switchService [entity] True) -< ()
Event Closed -> callService (switchService [entity] False) -< ()
_ -> returnA -< ()
where
entity = EntityId "switch.bedroom_drawer_light_masse"
+6 -6
View File
@@ -1,7 +1,7 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
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 qualified AFRP
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.Functor.Contravariant (Predicate (..), (>$<))
import Data.Aeson (Value)
import Data.Default (Default(..))
-- Let's see building some reasonable interface for utctime
dow :: Day -> (WeekOfYear, Int)
@@ -49,7 +50,6 @@ timersOff =
, day 3 <> at (08,15)
, day 4 <> at (08,15)
, day 5 <> at (08,15)
, at (18,57) -- debug
]
where
dayOfWeek = snd . mondayStartWeek . localDay
@@ -75,19 +75,19 @@ schoolLightController = lightsOn <> lightsOff
lightsOn :: HASS a ()
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 = foldMap atTime timersOff
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] Off))
bedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
bedroomButton = ikeaQuickButton "event.children_quick_remote_action"
childrenBedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
childrenBedroomButton = ikeaQuickButton "event.children_quick_remote_action"
childrenBedroomButtonController :: HASS (Event Value) ()
childrenBedroomButtonController = proc x -> do
ev <- bedroomButton >>> traceEvent -< x
ev <- childrenBedroomButton >>> traceEvent -< x
case ev of
Event (OnButton ShortRelease) -> callService (activateScene "scene.lasten_nukkuvalmistelu") -< ()
Event (OnButton DoubleClick) -> callService (activateScene "scene.lasten_luku") -< ()
+9
View File
@@ -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
+55
View File
@@ -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
+50
View File
@@ -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
+7 -14
View File
@@ -2,37 +2,30 @@
{-# LANGUAGE Arrows #-}
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 qualified AFRP
import Data.Aeson (Value)
import Control.Arrow ((>>>), Arrow (..), returnA)
import Control.Arrow ((>>>), returnA)
import Data.Time (LocalTime(..), TimeOfDay (..))
import Data.Default (def)
hallwayPresence :: HASS (Event Value) Presence
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
data Lights = LightsOn | LightsOff
deriving (Show)
eventLights :: HASS Presence (Event Lights)
eventLights = AFRP.changes >>> arr (fmap presenceLights)
where
presenceLights Occupied = LightsOn
presenceLights Unoccupied = LightsOff
hallwayLightsController :: HASS (Event Value) ()
hallwayLightsController = proc x -> do
now <- AFRP.currentTime -< ()
p <- hallwayPresence -< x
ev <- eventLights -< p
ev <- lightingModeEvents -< p
traceEvent -< ev
case ev of
-- The lights entity is a "group of lights" in hass
Event LightsOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< On Nothing
Event LightsOff -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< Off
Event LightingOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< On def
Event LightingOff -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< Off
_ -> returnA -< ()
where
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
+80
View File
@@ -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
+13 -21
View File
@@ -8,31 +8,23 @@ import Data.Aeson (Value)
import Control.Arrow ((>>>), Arrow (..), returnA)
import Prelude hiding (id)
import Data.Time (LocalTime(..), TimeOfDay (..))
import Data.Default (def)
-- Kitchen has two "presence" sensors. One IKEA motion sensor and one SwitchBot presence sensor
data Lights = LightsOn | LightsOff | LightsSleep
deriving (Show)
kitchenPresence :: HASS (Event Value) Presence
kitchenPresence = motion "binary_sensor.kitchen_movement_occupancy" >>> motionToPresence 500
eventLights :: HASS Presence (Event Lights)
eventLights = AFRP.changes >>> arr (fmap presenceLights)
where
presenceLights Occupied = LightsOn
presenceLights Unoccupied = LightsOff
kitchenCeilingController :: HASS (Event Value) ()
kitchenCeilingController = proc x -> do
now <- AFRP.currentTime -< ()
p <- kitchenPresence -< x
ev <- eventLights -< p
ev <- lightingModeEvents -< p
traceEvent -< ev
case ev of
Event LightsOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< On Nothing
Event LightsOff -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< Off
Event LightingOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< On def
Event LightingOff -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< Off
_ -> returnA -< ()
where
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 = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
dinnerLightEvents :: HASS (Event Value) (Event Lights)
dinnerLightEvents :: HASS (Event Value) (Event LightingMode)
dinnerLightEvents =
((,) <$> dinnerLightLevel <*> dinnerPresence)
>>> arr lightWanted
@@ -55,33 +47,33 @@ dinnerLightEvents =
onEvent =
AFRP.edge
>>> arr (fmap (const LightsOn))
>>> arr (fmap (const LightingOn))
sleepEvent =
arr not
>>> AFRP.edge
>>> arr (fmap (const LightsSleep))
>>> arr (fmap (const LightingSleep))
offEvent =
arr not
>>> AFRP.waitFor 300
>>> arr (fmap (const LightsOff))
>>> arr (fmap (const LightingOff))
dinnerTableController :: HASS (Event Value) ()
dinnerTableController = proc x -> do
ev <- dinnerLightEvents -< x
case ev of
Event LightsOn -> do
Event LightingOn -> do
sleep -< False
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On Nothing
Event LightsOff -> do
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On def
Event LightingOff -> do
sleep -< False
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< Off
Event LightsSleep -> do
Event LightingSleep -> do
sleep -< True
_ -> returnA -< ()
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 = 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
+9 -16
View File
@@ -2,26 +2,19 @@
{-# LANGUAGE Arrows #-}
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 Control.Arrow ((>>>), Arrow (..), returnA)
import Data.Aeson (Value)
import Prelude hiding ((.))
import Control.Category ((.))
import Data.Time (LocalTime(..), toGregorian, TimeOfDay (..))
data Lights = LightsOn | LightsOff
deriving (Show)
import Data.Default (def)
livingroomPresence :: HASS (AFRP.Event Value) Presence
livingroomPresence = presence "binary_sensor.occupancy_olohuone_derived" >>> AFRP.hold Unoccupied
eventLights :: HASS Presence (AFRP.Event Lights)
eventLights = AFRP.changes >>> arr (fmap presenceLights)
where
presenceLights Occupied = LightsOn
presenceLights Unoccupied = LightsOff
-- There's a small race condition / corner case bug in the og implementation
-- I have a couple of lights in the Livingroom
@@ -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
lights :: [Target]
lights = [EntityId "light.livingroom_ceiling", EntityId "light.livingroom_sofa"]
livingroomLightTargets :: [Target]
livingroomLightTargets = [EntityId "light.livingroom_ceiling", EntityId "light.livingroom_sofa"]
livingroomPresenceController :: HASS (AFRP.Event Value) ()
livingroomPresenceController = proc x -> do
ev <- eventLights . livingroomPresence -< x
ev <- lightingModeEvents . livingroomPresence -< x
traceEvent -< ev
case ev of
AFRP.Event LightsOn -> callServiceDyn (light lights) -< On Nothing
AFRP.Event LightsOff -> callServiceDyn (light lights) -< Off
AFRP.Event LightingOn -> callServiceDyn (light livingroomLightTargets) -< On def
AFRP.Event LightingOff -> callServiceDyn (light livingroomLightTargets) -< Off
_ -> returnA -< ()
returnA -< ()
@@ -96,5 +89,5 @@ livingroomPlantLights = (season &&& tod)
setLights = proc mode -> do
case mode of
AFRP.Event Growth -> callService (activateScene "scene.olohuoneen_kasvivalo") -< ()
AFRP.Event Ambience -> callService (activateScene "scene.makuuhuone_lepotila") -< ()
AFRP.Event Ambience -> callService (activateScene "scene.kasvivalo_iltatila") -< ()
_ -> returnA -< ()
+55
View File
@@ -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
+21
View File
@@ -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
}
+18
View File
@@ -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)
+14
View File
@@ -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
}
+95 -79
View File
@@ -4,128 +4,144 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Runtime
( defaultMain
, step
, CallIdGen
, mkCallIdGen
, dryRunHassEval
, Controller(..)
, runController
) where
( defaultMain,
step,
CallIdGen,
mkCallIdGen,
dryRunHassEval,
Controller (..),
runController,
)
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.Monad.IO.Class (MonadIO, liftIO)
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.UUID (UUID, toText)
import Data.UUID.V4 qualified as UUID.V4
import Data.Void (Void)
import GHC.Stack (HasCallStack)
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.Connection (writerAction, readerAction)
import HomeAssistant.Runtime.Connection (readerAction, writerAction)
import HomeAssistant.Runtime.Flags (loadFlags)
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 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.Metrics qualified
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 HomeAssistant.Runtime.Supervisor (supervised)
import qualified HomeAssistant.Runtime.Graphing
import HomeAssistant.Controller.Hallway (hallwayLightsController)
import Control.Monad.Catch (MonadCatch)
import Control.Exception.Annotated (checkpoint, Annotation (..))
step :: (MonadIO m) => FilePath -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
step path trace st a = do
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
now <- liftIO getCurrentTime
tz <- liftIO getCurrentTimeZone
let req = Request now tz trace
let req = Request now tz trace name
stepAutoSerializing path st req a
data Controller = forall b. Controller Bool T.Text (HASS (Event Value) b)
data Controller = forall b. Controller T.Text (HASS (Event Value) b)
controllers :: [Controller]
controllers =
[ Controller True "bedroom-presence" bedroomPresenceController
, Controller True "bedroom-button" bedroomButtonController
, Controller True "bedroom-drawer" bedroomDrawerController
, Controller True "bedroom-humidifier" humidifierController
, Controller True "school-light-controller" schoolLightController
, Controller True "kitchen-motion-controller" kitchenMotionController
, Controller True "livingroom-presence" livingroomPresenceController
, Controller True "hallway-motion-controller" hallwayLightsController
, Controller True "children-button" childrenBedroomButtonController
, Controller True "livingroom-plants" livingroomPlantLights
[ Controller "bedroom-presence" bedroomPresenceController,
Controller "bedroom-button" bedroomButtonController,
Controller "bedroom-drawer" bedroomDrawerController,
Controller "bedroom-humidifier" humidifierController,
Controller "school-light-controller" schoolLightController,
Controller "kitchen-motion-controller" kitchenMotionController,
Controller "livingroom-presence" livingroomPresenceController,
Controller "hallway-motion-controller" hallwayLightsController,
Controller "children-button" childrenBedroomButtonController,
Controller "livingroom-plants" livingroomPlantLights
]
-- | Steps the machine for every inbound message; service calls go to the
-- bus. A restart re-dups the inbound channel and starts from the machine's
-- initial state; messages broadcast during the restart window are lost.
runController :: MonadIO m => FilePath -> Bus -> Controller -> m Void
runController rootDir bus (Controller _enabled name machine ) = liftIO $ do
inbound <- atomically (dupTChan (busInbound bus))
let ns = Namespace [name]
let workerDefinition = runMealy machine (runKatipContextT (busLogEnv bus) () ns . channelHassEval bus)
let path = rootDir </> T.unpack name
worker <- load path workerDefinition >>= \case
Decoded a -> pure a
FailDecode err a -> a <$ putStrLn ("Failed to load (" <> T.unpack name <> "): " <> err)
runController :: forall m. (HasCallStack, MonadCatch m, KatipContext m, MonadIO m) => FilePath -> Bus -> Controller -> m Void
runController rootDir bus (Controller name machine) = checkpoint (Annotation name) $ katipAddNamespace ns $ do
inbound <- liftIO $ atomically (dupTChan (busInbound bus))
let workerDefinition = runMealy machine (channelHassEval @m bus)
let path = rootDir </> T.unpack name
worker <-
load path workerDefinition >>= \case
Decoded a -> pure a
FailDecode err a -> a <$ logLocM WarningS (ls ("Failed to load (" <> T.unpack name <> "): " <> err))
go path inbound worker
where
ns = Namespace [name]
go path inbound f = do
msg <- atomically (readTChan inbound)
uuid <- UUID.V4.nextRandom
(_, next) <- step path uuid f msg
msg <- liftIO $ atomically (readTChan inbound)
uuid <- liftIO UUID.V4.nextRandom
(_, next) <- step path name uuid f msg
go path inbound next
lookupPort :: IO Int
lookupPort :: (MonadFail m, MonadIO m) => m Int
lookupPort = do
m <- lookupEnv "HA_METRICS_PORT"
m <- liftIO (lookupEnv "HA_METRICS_PORT")
case m of
Nothing -> pure 8124
Just s -> case readMaybe s of
Just s -> case readMaybe s of
Just p | p >= 1 && p <= 65535 -> pure p
_ -> fail ("HA_METRICS_PORT must be a port in 1..65535: " <> s)
defaultMain :: IO ()
defaultMain = withSocketsDo $ do
severity <- maybe InfoS (const DebugS) <$> lookupEnv "HA_DEBUG"
store <- System.Metrics.newStore
System.Metrics.registerGcMetrics store
appMetrics <- HomeAssistant.Runtime.Metrics.registerAppMetrics store
rateLimitMetrics <- registerRateLimitMetrics store
withBus severity appMetrics $ \bus -> do
token <- getEnv "HA_TOKEN"
host <- getEnv "HA_HOST"
rootPath <- fromMaybe "/tmp/" <$> lookupEnv "HA_LIB_DIR"
rrdPath <- fromMaybe "hass-controller.rrd" <$> lookupEnv "HA_RRD_PATH"
rrdtool <- fromMaybe "rrdtool" <$> lookupEnv "HA_RRDTOOL"
metricsPort <- lookupPort
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
let active = [c | c@(Controller True _ _) <- controllers]
ents = foldMap (\(Controller _ _ m) -> entities m) active
workers =
[ ("reader", readerAction host 8123 token ents bus)
, ("writer", writerAction writerLimiter bus)
, ("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool)
, ("metrics-http", HomeAssistant.Runtime.Graphing.graphAction rrdPath rrdtool metricsPort)
] ++ [ (name, runController rootPath bus c) | c@(Controller True name _) <- active ]
runKatipContextT (busLogEnv bus) () mempty $
mapConcurrently_ (uncurry supervised) workers
defaultMain =
withSocketsDo $
getSeverity >>= \s -> withLogEnv s $ \le -> runKatipContextT le () mempty $ do
logLocM InfoS "Hello world"
store <- liftIO System.Metrics.newStore
liftIO $ System.Metrics.registerGcMetrics store
appMetrics <- liftIO $ HomeAssistant.Runtime.Metrics.registerAppMetrics store
rateLimitMetrics <- registerRateLimitMetrics store
rootPath <- fromMaybe "/tmp/" <$> liftIO (lookupEnv "HA_LIB_DIR")
let allNames = map (\(Controller n _) -> n) controllers
flags <- loadFlags rootPath allNames
withBus le appMetrics flags $ \bus -> do
token <- liftIO $ getEnv "HA_TOKEN"
host <- liftIO $ getEnv "HA_HOST"
let rrdPath = rootPath </> "hass-controller.rrd"
rrdtool <- fromMaybe "rrdtool" <$> liftIO (lookupEnv "HA_RRDTOOL")
metricsPort <- lookupPort
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
let ents = foldMap (\(Controller _ m) -> entities m) controllers
workers =
[ ("reader", readerAction host 8123 token ents bus),
("writer", writerAction writerLimiter bus),
("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool),
("metrics-http", HttpServer.runHttpServer (busLogEnv bus) rrdPath rrdtool (busFlags bus) metricsPort)
]
++ [(name, runController rootPath bus c) | c@(Controller name _) <- controllers]
runKatipContextT (busLogEnv bus) () mempty $
mapConcurrently_ (uncurry supervised) workers
where
getSeverity = maybe InfoS (const DebugS) <$> lookupEnv "HA_DEBUG"
dryRunHassEval :: Namespace -> Bus -> HASSEff a -> IO a
dryRunHassEval ns bus = \case
CallService req x -> runKatipT (busLogEnv bus) $ do
callId <- liftIO $ generateCallId (busGen bus)
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
logF () ns DebugS (ls $ show x)
Trace req x -> runKatipT (busLogEnv bus) $ do
+41 -17
View File
@@ -1,5 +1,6 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module HomeAssistant.Runtime.Bus
( Bus(..)
@@ -9,6 +10,7 @@ module HomeAssistant.Runtime.Bus
, recordInbound
, recordOutbound
, channelHassEval
, withLogEnv
) where
import Control.Concurrent.STM
@@ -32,6 +34,10 @@ import System.Metrics.Counter (inc)
import Data.UUID (toText)
import AFRP (Request(..), Event(..))
import Control.Monad.IO.Class (MonadIO, liftIO)
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
-- read from 'dupTChan' copies), outbound queues service calls for the
@@ -43,22 +49,38 @@ data Bus = Bus
, busGen :: CallIdGen
, busLogEnv :: LogEnv
, busMetrics :: AppMetrics
, busFlags :: Flags
}
withBus :: Severity -> AppMetrics -> (Bus -> IO a) -> IO a
withBus severity metrics callback = do
handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem severity) V2
let makeLogEnv = registerScribe "stdout" handleScribe defaultScribeSettings =<< initLogEnv "hass-controller" "production"
withLogEnv :: Severity -> (LogEnv -> IO a) -> IO a
withLogEnv severity f = do
let makeLogEnv = registerJournalScribe =<< registerHandleScribe =<< initLogEnv "hass-controller" "production"
-- closeScribes will stop accepting new logs, flush existing ones and clean up resources
bracket makeLogEnv closeScribes $ \le -> do
bus <- Bus
<$> newBroadcastTChanIO
<*> newTChanIO
<*> newTVarIO Nothing
<*> mkCallIdGen 0
<*> pure le
<*> pure metrics
callback bus
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
<$> liftIO newBroadcastTChanIO
<*> liftIO newTChanIO
<*> liftIO (newTVarIO Nothing)
<*> liftIO (mkCallIdGen 0)
<*> pure le
<*> pure metrics
<*> pure flags
callback bus
recordInbound :: Bus -> IO ()
recordInbound bus = inc (amTriggersIn (busMetrics bus))
@@ -66,14 +88,16 @@ recordInbound bus = inc (amTriggersIn (busMetrics bus))
recordOutbound :: Bus -> IO ()
recordOutbound bus = inc (amServicesOut (busMetrics bus))
channelHassEval :: (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a
channelHassEval :: forall m a. (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a
channelHassEval bus = \case
CallService req svc -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ do
logFM DebugS (ls $ show svc)
liftIO $ atomically $ writeTChan (busOutbound bus) (req, svc)
CallService req svc -> emit req svc
CallServices req svcs -> mapM_ (emit req) svcs
Debug x -> logFM DebugS (ls $ show x)
Trace req x -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $
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 }
+35 -21
View File
@@ -4,6 +4,7 @@
module HomeAssistant.Runtime.Connection
( readerAction
, writerAction
, dispatchService
, encodeService
, isTriggerEvent
) where
@@ -16,9 +17,7 @@ import Control.Concurrent.STM
, writeTChan
, writeTVar
)
import Control.Concurrent.Async (race)
import Control.Concurrent (threadDelay)
import Control.Exception (onException)
import Control.Exception.Annotated (throw)
import Control.Lens ((^?))
import Control.Monad (forever, forM_, when)
@@ -29,27 +28,31 @@ import qualified Data.Text as T
import Data.Void (Void)
import HomeAssistant.Controller (Service (..), Target (..))
import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (isEnabled)
import HomeAssistant.Runtime.Supervisor (Fatal (..))
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 AFRP (Request(..), Event(..))
import Control.Monad.IO.Class (liftIO, MonadIO)
import HomeAssistant.Runtime.RateLimit (RateLimited, RateLimiter, runRateLimited)
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.
-- Restarting this action reconnects. All setup sends happen before the
-- 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 host port token ents bus = liftIO $
WS.runClient host port "/api/websocket" $ \conn -> do
handshake conn token
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 = katipAddNamespace "receiver" $ withRunInIO $ \rio ->
WS.runClient host port "/api/websocket" $ \conn -> rio $ do
liftIO $ handshake conn token
subscribe bus conn ents
atomically $ writeTVar (busConn bus) (Just conn)
putStrLn "[reader] connected"
liftIO $ atomically $ writeTVar (busConn bus) (Just conn)
logLocM InfoS "connected"
-- 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 conn token = do
@@ -71,12 +74,12 @@ expectType expected msg =
isTriggerEvent :: Value -> Bool
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 =
forM_ (S.toList ents) $ \entityId -> do
print entityId
sid <- generateCallId (busGen bus)
WS.sendTextData conn $ encode $ object
logLocM InfoS $ ls entityId
sid <- liftIO $ generateCallId (busGen bus)
liftIO $ WS.sendTextData conn $ encode $ object
[ "id" .= sid
, "type" .= ("subscribe_trigger" :: T.Text)
, "trigger" .= object
@@ -91,14 +94,14 @@ subscribe bus conn ents =
-- Each read races a one-second timeout: a timeout broadcasts 'Tick' so
-- time-based primitives (debounce, rollup, fixed, ...) keep advancing
-- even when no state changes arrive.
receiveLoop :: Bus -> WS.Connection -> IO Void
receiveLoop :: (HasCallStack, MonadUnliftIO m, KatipContext m) => Bus -> WS.Connection -> m Void
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
Left () -> atomically $ writeTChan (busInbound bus) Tick
Left () -> liftIO $ atomically $ writeTChan (busInbound bus) Tick
Right msg -> case eitherDecode msg of
Left err -> putStrLn $ "[reader] skipping undecodable message: " <> err
Right v -> do
Left err -> logLocM WarningS $ ls $ "skipping undecodable message: " <> err
Right v -> liftIO $ do
when (isTriggerEvent v) (recordInbound bus)
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 rateLimiter bus = forever $ do
(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
-- runRateLimited rateLimiter $ sendWithId bus conn request svc
runRateLimited rateLimiter $ sendWithId bus conn svc
encodeService :: Int -> Service -> Value
+93
View File
@@ -0,0 +1,93 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Runtime.Flags
( Name
, Flags(..)
, loadFlags
, isEnabled
, setEnabled
, allFlags
, validNames
) where
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Control.Concurrent.STM (TVar, atomically, newTVarIO, readTVarIO, stateTVar)
import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Conduit as C
import Conduit ((.|))
import Data.Aeson (decodeFileStrict', encode)
import qualified Data.ByteString.Lazy as BL
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Set (Set)
import qualified Data.Set as S
import Data.Text (Text)
import System.FilePath ((</>))
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
data Flags = Flags
{ flagsState :: TVar (Map Name Bool)
, flagsLock :: MVar ()
, flagsPath :: FilePath
, flagsValidNames :: Set Text
}
loadFlags :: (KatipContext m, MonadCatch m, MonadIO m) => FilePath -> [Name] -> m Flags
loadFlags rootPath allNames = do
let path = rootPath </> "handlers.json"
fileMap <- readFlagsFile path
let defaults = M.fromList [(n, True) | n <- allNames]
initial = M.unionWith (\fileVal -> const fileVal) fileMap defaults
tv <- liftIO $ newTVarIO initial
lock <- liftIO $ newMVar ()
pure Flags
{ flagsState = tv
, flagsLock = lock
, flagsPath = path
, flagsValidNames = S.fromList allNames
}
readFlagsFile :: forall m. (HasCallStack, KatipContext m, MonadCatch m) => FilePath -> m (Map Name Bool)
readFlagsFile path =
handle onMissingOrUnreadable $ do
decoded <- liftIO $ decodeFileStrict' path
case decoded of
Nothing -> do
logLocM WarningS $ ls ("handlers.json is unparseable; treating all handlers as enabled: " <> path)
pure mempty
Just m -> pure (fromMaybe mempty m)
where
onMissingOrUnreadable :: HasCallStack => IOException -> m (Map Name Bool)
onMissingOrUnreadable e
| isDoesNotExistError e = pure mempty
| otherwise = do
logLocM WarningS $ ls ("could not read handlers.json (" <> show e <> "); treating all handlers as enabled")
pure mempty
isEnabled :: MonadIO m => Flags -> Name -> m Bool
isEnabled flags name = liftIO $
M.findWithDefault True name <$> readTVarIO (flagsState flags)
allFlags :: MonadIO m => Flags -> m (Map Name Bool)
allFlags flags = liftIO $ readTVarIO (flagsState flags)
setEnabled :: MonadIO m => Flags -> Name -> Bool -> m ()
setEnabled Flags{flagsState, flagsLock, flagsPath} name val =
liftIO $ withMVar flagsLock $ \_ -> do
m <- atomically $ stateTVar flagsState $ \cur ->
let next = M.insert name val cur in (next, next)
safeWrite flagsPath m
validNames :: Flags -> Set Text
validNames = flagsValidNames
safeWrite :: FilePath -> Map Name Bool -> IO ()
safeWrite path m = C.runResourceT $ C.runConduit $
C.yieldMany [BL.toStrict (encode m)] .| C.sinkFileCautious path
+42 -54
View File
@@ -11,37 +11,19 @@ module HomeAssistant.Runtime.Graphing
, parseNameParam
, buildGraphArgs
, readProcessBytes
, graphAction
, Graph(..)
, renderGraph
) where
import Control.Exception (evaluate)
import Control.Monad (forever)
import Control.Monad.IO.Class (liftIO, MonadIO)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Void (Void)
import Network.HTTP.Types.Status (Status, status400, status404, status500)
import Network.Wai.Handler.Warp (defaultSettings, setHost, setPort)
import System.Exit (ExitCode (..))
import System.IO (hGetContents)
import System.Process (CreateProcess (..), StdStream (..), proc, waitForProcess, withCreateProcess)
import Web.Scotty
( ActionM
, ScottyM
, defaultOptions
, get
, pathParam
, queryParamMaybe
, raw
, scottyOpts
, setHeader
, settings
, status
, text
)
import Servant.API (FromHttpApiData (..), ToHttpApiData (..))
data Range = TenMinutes | OneHour | OneDay | OneWeek | OneMonth
deriving (Eq, Show, Bounded, Enum)
@@ -56,6 +38,12 @@ rangeSuffix OneMonth = "30d"
parseRange :: Text -> Maybe Range
parseRange t = lookup t [(T.pack (rangeSuffix r), r) | r <- [minBound .. maxBound]]
instance ToHttpApiData Range where
toQueryParam = T.pack . rangeSuffix
instance FromHttpApiData Range where
parseQueryParam x = maybe (Left ("Could not parse '" <> x <> "' as Range")) Right $ parseRange x
rangeStart :: Range -> String
rangeStart r = "end-" ++ rangeSuffix r
@@ -91,6 +79,7 @@ data GraphSpec = GraphSpec
{ gsName :: Text
, gsTitle :: String
, gsPlots :: [Plot]
, gsIdentifier :: Graph
}
deriving (Eq, Show)
@@ -141,6 +130,7 @@ ratelimitGraph =
, serLabel = "Requests exhausted/min"
}
]
, gsIdentifier = RateLimit
}
trafficGraph :: GraphSpec
@@ -164,6 +154,7 @@ trafficGraph =
, serLabel = "Service calls out/min"
}
]
, gsIdentifier = Traffic
}
memoryGraph :: GraphSpec
@@ -174,17 +165,21 @@ memoryGraph =
[ area "live" "#99ccff" (average "rts_gc_current__a7a")
, line "peak" "#cc0000" (maximumCF "rts_gc_current__a7a")
]
Memory
graphs :: [GraphSpec]
graphs = [memoryGraph, ratelimitGraph, trafficGraph]
lookupGraph :: [GraphSpec] -> Text -> Maybe GraphSpec
lookupGraph specs name = case [g | g <- specs, gsName g == name] of
-- XXX: Proper lookup..?
lookupGraph :: [GraphSpec] -> Graph -> Maybe GraphSpec
lookupGraph specs graphMode = case [g | g <- specs, gsIdentifier g == graphMode] of
(g : _) -> Just g
[] -> Nothing
parseNameParam :: [GraphSpec] -> Text -> Maybe GraphSpec
parseNameParam specs t = T.stripSuffix ".png" t >>= lookupGraph specs
parseNameParam specs t = rightToMaybe (parseQueryParam t) >>= lookupGraph specs
where
rightToMaybe = either (const Nothing) Just
cfName :: CF -> String
cfName = \case
@@ -255,39 +250,32 @@ readProcessBytes cmd args =
pure (code, out, err)
_ -> pure (ExitFailure 1, BS.empty, "failed to create pipes")
respond :: Status -> TL.Text -> ActionM ()
respond st body = status st >> text body
serve :: FilePath -> FilePath -> GraphSpec -> Range -> ActionM ()
serve rrdPath rrdtool spec range = do
renderGraph :: MonadIO m => FilePath -> FilePath -> GraphSpec -> Range -> m (Either Text BS.ByteString)
renderGraph rrdPath rrdtool spec range = do
(code, out, err) <- liftIO (readProcessBytes rrdtool (buildGraphArgs rrdPath spec range))
case code of
ExitSuccess
| not (BS.null out) -> do
setHeader "Content-Type" "image/png"
raw (BL.fromStrict out)
| otherwise -> respond status500 "empty graph"
_ -> respond status500 (TL.pack (take 200 err))
| not (BS.null out) -> pure $ Right out
| otherwise -> pure $ Left "empty graph"
_ -> pure $ Left (T.pack $ take 200 err)
handler :: FilePath -> FilePath -> ActionM ()
handler rrdPath rrdtool = do
name <- pathParam "name"
case parseNameParam graphs name of
Nothing -> respond status404 "unknown graph"
Just spec -> do
rangeArg <- queryParamMaybe "range"
case rangeArg of
Nothing -> serve rrdPath rrdtool spec OneDay
Just t -> case parseRange t of
Nothing -> respond status400 "invalid range"
Just range -> serve rrdPath rrdtool spec range
app :: FilePath -> FilePath -> ScottyM ()
app rrdPath rrdtool = get "/metrics/:name" (handler rrdPath rrdtool)
graphAction :: MonadIO m => FilePath -> FilePath -> Int -> m Void
graphAction rrdPath rrdtool port = liftIO $ forever $ scottyOpts opts (app rrdPath rrdtool)
where
opts = defaultOptions
{ settings = setHost "0.0.0.0" (setPort port defaultSettings)
}
data Graph
= Memory
| Traffic
| RateLimit
deriving (Show, Eq, Enum, Bounded)
instance ToHttpApiData Graph where
toQueryParam Memory = "memory.png"
toQueryParam Traffic = "traffic.png"
toQueryParam RateLimit = "ratelimit.png"
instance FromHttpApiData Graph where
parseQueryParam "memory.png" = Right Memory
parseQueryParam "traffic.png" = Right Traffic
parseQueryParam "ratelimit.png" = Right RateLimit
parseQueryParam x = Left ("Can't parse '" <> x <> "' as Graph")
+4 -3
View File
@@ -38,12 +38,13 @@ data RateLimiter = RateLimiter
slidingWindowLimiter
:: RateLimitMetrics
:: MonadIO m
=> RateLimitMetrics
-> NominalDiffTime -- ^ Within how many seconds
-> Int -- ^ How many requests we can make
-> IO RateLimiter
-> m RateLimiter
slidingWindowLimiter metrics timeWindow size = do
window <- newTVarIO []
window <- liftIO $ newTVarIO []
return $ RateLimiter metrics $ \(RateLimited action) -> do
now <- liftIO getPOSIXTime
allowed <- liftIO $ atomically $ do
+87
View File
@@ -0,0 +1,87 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HttpServer where
import Control.Monad (forever)
import Control.Monad.IO.Class (liftIO, MonadIO)
import qualified Data.ByteString as BS
import Data.Void (Void)
import Network.Wai.Handler.Warp (run)
import Servant.API ((:>), Capture, Get, QueryParam, (:-), MimeRender (..), Accept (..), NamedRoutes, JSON, ReqBody, Put)
import Data.ByteString (ByteString)
import GHC.Generics (Generic)
import Servant (Handler, err404)
import Control.Monad.Catch (throwM, catch, MonadCatch, MonadThrow, SomeException)
import Servant.Server (err500, ServerT)
import Data.Maybe (fromMaybe)
import Data.Map.Strict (Map)
import qualified Data.Set as S
import Data.Text (Text)
import HomeAssistant.Runtime.Flags (Flags, allFlags, setEnabled, validNames)
import Control.Exception.Annotated (checkpoint, Annotation (Annotation))
import Servant.Server.Generic (genericServeT)
import Network.Wai (Application)
import Network.HTTP.Media ((//))
import HomeAssistant.Runtime.Graphing (Graph, Range (..), lookupGraph, graphs, renderGraph)
import Katip (KatipContextT, Katip, runKatipContextT, LogEnv, KatipContext, ls, Severity (..), logFM)
data ImagePng
instance MimeRender ImagePng ByteString where
mimeRender _ = BS.fromStrict
instance Accept ImagePng where
contentType _ = "image" // "png"
data API mode = API
{ getMetrics :: mode :- "metrics" :> Capture "graph" Graph :> QueryParam "range" Range :> Get '[ImagePng] ByteString
, getFlags :: mode :- "flags" :> Get '[JSON] (Map Text Bool)
, putFlag :: mode :- "flags" :> Capture "name" Text :> ReqBody '[JSON] Bool :> Put '[JSON] (Map Text Bool)
}
deriving Generic
getFlagsHandler :: Flags -> LoggingHandler (Map Text Bool)
getFlagsHandler flags = allFlags flags
putFlagHandler :: Flags -> Text -> Bool -> LoggingHandler (Map Text Bool)
putFlagHandler flags name val
| name `S.notMember` validNames flags = throwM err404
| otherwise = do
setEnabled flags name val `catch` \e -> do
logFM ErrorS (ls ("failed to persist handler flag: " <> show (e :: SomeException)))
throwM err500
allFlags flags
getMetricsHandler :: FilePath -> FilePath -> Graph -> Maybe Range -> LoggingHandler ByteString
getMetricsHandler rrdPath rrdtool graphMode mRange = checkpoint (Annotation (graphMode, mRange)) $ do
case lookupGraph graphs graphMode of
Nothing -> throwM err404
Just spec -> do
let range = fromMaybe OneDay mRange
g <- renderGraph rrdPath rrdtool spec range
either (\e -> logFM ErrorS (ls e) >> throwM err500) pure g
-- server :: FilePath -> FilePath -> API AsServer
server :: FilePath -> FilePath -> Flags -> ServerT (NamedRoutes API) LoggingHandler
server rrdPath rrdtool flags = API
{ getMetrics = getMetricsHandler rrdPath rrdtool
, getFlags = getFlagsHandler flags
, putFlag = putFlagHandler flags
}
servantApp :: LogEnv -> FilePath -> FilePath -> Flags -> Application
servantApp le rrdPath rrdtool flags = genericServeT (toHandler le) (server rrdPath rrdtool flags)
runHttpServer :: MonadIO m => LogEnv -> FilePath -> FilePath -> Flags -> Int -> m Void
runHttpServer le rrdPath rrdtool flags port = liftIO $ forever $ run port (servantApp le rrdPath rrdtool flags)
newtype LoggingHandler a = LoggingHandler (KatipContextT Handler a)
deriving (Functor, Applicative, Monad, MonadIO, Katip, KatipContext, MonadCatch, MonadThrow) via (KatipContextT Handler)
toHandler :: LogEnv -> (forall a. LoggingHandler a -> Handler a)
toHandler le (LoggingHandler k) = runKatipContextT le () "http" k
+70
View File
@@ -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 ()
+2 -2
View File
@@ -21,7 +21,7 @@ import Test.Hspec
import Test.Hspec.Hedgehog
fakeRequest :: Request
fakeRequest = Request (sec 0) utc nil
fakeRequest = Request (sec 0) utc nil "test"
sec :: Integer -> UTCTime
sec n = UTCTime (toEnum 0) (fromIntegral n)
@@ -42,7 +42,7 @@ runTimed m = go (runMealy m id)
where
go _ [] = []
go w ((s, a) : as) =
case runIdentity (stepAuto w (Request (sec s) utc nil) a) of
case runIdentity (stepAuto w (Request (sec s) utc nil "test") a) of
(b, w') -> b : go w' as
-- | A minimal State monad for observing effectful arrows (e.g. whenA gating).
+7 -7
View File
@@ -49,8 +49,8 @@ entitySpec = describe "entities" $ do
]
it "bedroomPresenceController subscribes to the presence sensor" $
entities bedroomPresenceController
`shouldBe` S.singleton "binary_sensor.presence_sensor_bedroom_occupancy"
S.toList (entities bedroomPresenceController)
`shouldContain` [ "binary_sensor.presence_sensor_bedroom_occupancy" ]
it "humidifierController subscribes to the door sensor" $
entities humidifierController
@@ -62,18 +62,18 @@ drawerSpec = describe "bedroomDrawerController" $ do
it "turns the drawer light on when the drawer opens" $
services (runHASS bedroomDrawerController [drawerState "on"])
`shouldBe` [[switch [entity] True]]
`shouldBe` [[switchService [entity] True]]
it "turns the drawer light off when the drawer closes" $
services (runHASS bedroomDrawerController [drawerState "off"])
`shouldBe` [[switch [entity] False]]
`shouldBe` [[switchService [entity] False]]
it "toggles the light as the drawer opens and closes" $
services (runHASS bedroomDrawerController
[ drawerState "on", drawerState "off", drawerState "on" ])
`shouldBe` [ [switch [entity] True]
, [switch [entity] False]
, [switch [entity] True]
`shouldBe` [ [switchService [entity] True]
, [switchService [entity] False]
, [switchService [entity] True]
]
it "ignores state events for other entities" $
+42 -10
View File
@@ -6,6 +6,7 @@ import AFRP (Request (..), Event (..))
import Control.Concurrent.STM
( atomically
, dupTChan
, isEmptyTChan
, readTChan
, writeTChan
)
@@ -15,9 +16,15 @@ import Data.Time (UTCTime (..), utc)
import Data.UUID (nil)
import HomeAssistant.Controller (HASSEff (..), Service (..), Target(..))
import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
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 System.IO.Temp (withTempDirectory)
import System.Timeout (timeout)
import Test.Hspec
spec :: Spec
@@ -33,13 +40,24 @@ spec = describe "Bus" $ do
r2 `shouldBe` (Event (Number 1), Event (Number 2))
it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do
let req = Request (UTCTime (toEnum 0) 0) utc nil
let req = Request (UTCTime (toEnum 0) 0) utc nil "test"
svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"]
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
channelHassEval bus (CallService req svc)
(_, svc') <- atomically $ readTChan (busOutbound bus)
svc' `shouldBe` svc
it "channelHassEval writes CallService to the outbound channel even when the handler is disabled" $
withTestFlagsBus $ \bus -> do
setEnabled (busFlags bus) "test-handler" False
let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler"
svc = Service "light" "turn_on" Nothing [EntityId "light.test"]
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
channelHassEval bus (CallService req svc)
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
gen <- mkCallIdGen 0
@@ -51,16 +69,30 @@ spec = describe "Bus" $ do
it "increments the trigger and service counters" $ do
store <- Metrics.newStore
m <- registerAppMetrics store
withBus InfoS m $ \bus -> do
recordInbound bus
recordInbound bus
recordOutbound bus
sample <- Metrics.sampleAll store
HM.lookup "hass.trigger.in" sample `shouldBe` Just (Metrics.Counter 2)
HM.lookup "hass.service.out" sample `shouldBe` Just (Metrics.Counter 1)
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir [])
withTestLogEnv $ \le -> withBus le m flags $ \bus -> do
recordInbound bus
recordInbound bus
recordOutbound bus
sample <- Metrics.sampleAll store
HM.lookup "hass.trigger.in" sample `shouldBe` Just (Metrics.Counter 2)
HM.lookup "hass.service.out" sample `shouldBe` Just (Metrics.Counter 1)
withTestBus :: (Bus -> IO a) -> IO a
withTestBus action = do
store <- Metrics.newStore
m <- registerAppMetrics store
withBus InfoS m action
withTestLogEnv $ \le ->
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir [])
withBus le m flags action
withTestFlagsBus :: (Bus -> IO a) -> IO a
withTestFlagsBus action = do
store <- Metrics.newStore
m <- registerAppMetrics store
withTestLogEnv $ \le ->
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["test-handler"])
withBus le m flags action
+29 -2
View File
@@ -4,12 +4,23 @@ module ConnectionSpec (spec) where
import AFRP (Request(..))
import Data.Aeson (object, (.=))
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromJust)
import Data.Text (Text)
import Data.Time (UTCTime (..), utc)
import Data.UUID (fromString)
import HomeAssistant.Controller (Service (..), Target(..))
import HomeAssistant.Runtime.Connection (encodeService, 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
spec :: Spec
@@ -44,10 +55,26 @@ spec = do
it "is false when there is no type" $
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 n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
(fromJust (fromString uuid))
(fromJust (fromString uuid)) "test"
where
pad i = replicate (12 - length (show i)) '0' <> show i
uuid = "00000000-0000-0000-0000-" <> pad n
+29
View File
@@ -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)])
+76
View File
@@ -0,0 +1,76 @@
{-# LANGUAGE OverloadedStrings #-}
module FlagsSpec (spec) where
import Control.Concurrent.Async (mapConcurrently_)
import Control.Monad.IO.Class (liftIO)
import Data.Aeson (decodeFileStrict)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Katip.Monadic (runNoLoggingT)
import System.IO.Temp (withTempDirectory)
import Test.Hspec
import Test.Hspec.Hedgehog
import HomeAssistant.Runtime.Flags
spec :: Spec
spec = describe "Flags" $ do
describe "loadFlags" $ do
it "defaults all names to True when the file is missing (opt-out)" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["a", "b"])
m <- allFlags flags
m `shouldBe` M.fromList [("a" :: Text, True), ("b", True)]
it "lets the file override the True default, missing keys stay True" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
let path = dir <> "/handlers.json"
writeFile path "{\"b\": false}"
flags <- runNoLoggingT (loadFlags dir ["a", "b"])
m <- allFlags flags
m `shouldBe` M.fromList [("a" :: Text, True), ("b" :: Text, False)]
it "treats a corrupt file as empty (all-enabled) without throwing" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
let path = dir <> "/handlers.json"
writeFile path "not json at all"
flags <- runNoLoggingT (loadFlags dir ["a"])
m <- allFlags flags
m `shouldBe` M.fromList [("a" :: Text, True)]
describe "isEnabled" $ do
it "returns the stored value" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
let path = dir <> "/handlers.json"
writeFile path "{\"a\": false}"
flags <- runNoLoggingT (loadFlags dir ["a"])
isEnabled flags "a" `shouldReturn` False
it "defaults unknown names to True" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir [])
isEnabled flags "unknown" `shouldReturn` True
describe "setEnabled" $ do
it "updates the in-memory map and persists to disk" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["a"])
setEnabled flags "a" False
isEnabled flags "a" `shouldReturn` False
-- reload from disk to confirm persistence
flags' <- runNoLoggingT (loadFlags dir ["a"])
isEnabled flags' "a" `shouldReturn` False
it "concurrent writes leave the file consistent with the TVar" $
hedgehog $ do
n <- forAll $ Gen.int (Range.linear 1 50)
liftIO $ withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["x"])
mapConcurrently_ (\i -> setEnabled flags "x" (even i)) [1 .. n]
m <- allFlags flags
decoded <- decodeFileStrict (dir <> "/handlers.json")
(decoded :: Maybe (Map Text Bool)) `shouldBe` Just m
+19 -1
View File
@@ -20,15 +20,30 @@ import System.Directory (findExecutable, getTemporaryDirectory, removeFile)
import System.Exit (ExitCode (..))
import System.Process (readProcessWithExitCode)
import Test.Hspec
import Servant.API (FromHttpApiData(..), ToHttpApiData (..))
import HomeAssistant.Runtime.Graphing (Graph(..))
traffic :: GraphSpec
traffic = case lookupGraph graphs "traffic" of
traffic = case lookupGraph graphs Traffic of
Just s -> s
Nothing -> error "traffic graph is missing from the table"
spec :: Spec
spec = do
describe "Graph HttpApiData" $ do
-- There's an enumerable amount of graphs, we can just enumerate through them all
it "satisfies roundtrip property" $ do
let modes = [minBound..maxBound]
let got = map (parseQueryParam . toQueryParam @Graph) modes
let wanted = map Right modes
got `shouldBe` wanted
describe "parseRange" $ do
-- Fully enumerable
it "the http-api-data satisfies roundtrip property" $ do
let rs = [minBound..maxBound]
let got = map (parseQueryParam . toQueryParam @Range) rs
let wanted = map Right rs
got `shouldBe` wanted
it "accepts every suffix in the closed set" $
map parseRange ["10m", "1h", "24h", "7d", "30d"]
`shouldBe` [ Just TenMinutes
@@ -124,3 +139,6 @@ spec = do
out `shouldSatisfy` BS.isPrefixOf pngMagic
)
`finally` cleanup
+46
View File
@@ -0,0 +1,46 @@
{-# LANGUAGE OverloadedStrings #-}
module KitchenSpec (spec) where
import AFRP (Event (..), entities)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Aeson (Value)
import HomeAssistant.Controller
import HomeAssistant.Controller.Kitchen
import Support
import Test.Hspec
import Data.Default (def)
-- Helper functions for creating test events
testDinnerLightLevel :: Int -> Event Value
testDinnerLightLevel level = Event (stateEvent "sensor.sijainti_keittio_light_level" (T.pack $ show level))
testDinnerPresence :: T.Text -> Event Value
testDinnerPresence state = Event (stateEvent "binary_sensor.sijainti_keittio_occupancy" state)
spec :: Spec
spec = describe "Kitchen" $ do
dinnerTableSpec
dinnerTableSpec :: Spec
dinnerTableSpec = describe "dinnerTableController" $ do
it "subscribes to the light level sensor" $ do
entities dinnerTableController
`shouldBe` S.fromList ["sensor.sijainti_keittio_light_level", "binary_sensor.sijainti_keittio_occupancy"]
it "subscribes to the presence sensor" $ do
entities dinnerTableController
`shouldBe` S.fromList ["sensor.sijainti_keittio_light_level", "binary_sensor.sijainti_keittio_occupancy"]
it "turns lights on when presence is occupied and light level is low" $ do
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] (On def)]]
it "turns lights off when presence is unoccupied" $ do
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "off"])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], []]
it "does nothing on Tick" $ do
services (runHASS dinnerTableController [Tick])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True]]
+43
View File
@@ -0,0 +1,43 @@
{-# LANGUAGE OverloadedStrings #-}
module LivingroomSpec (spec) where
import AFRP (Event (..))
import Data.Time (UTCTime (..), fromGregorian)
import HomeAssistant.Controller
import HomeAssistant.Controller.Livingroom
import Support
import Test.Hspec
-- | A UTCTime at a given hour on March 15, 2025 (Spring).
springAt :: Int -> UTCTime
springAt h = UTCTime (fromGregorian 2025 3 15) (fromIntegral (h * 3600))
-- | A UTCTime at a given hour on July 15, 2025 (Summer).
summerAt :: Int -> UTCTime
summerAt h = UTCTime (fromGregorian 2025 7 15) (fromIntegral (h * 3600))
spec :: Spec
spec = describe "livingroomPlantLights" $ do
it "activates the Growth scene at 10:00 in Spring" $ do
let result = runHASSTimed livingroomPlantLights
[ (springAt 9, Tick)
, (springAt 10, Tick)
]
services result
`shouldBe` [ [], [activateScene "scene.olohuoneen_kasvivalo"] ]
it "activates the Ambience scene at 20:00 in Spring" $ do
let result = runHASSTimed livingroomPlantLights
[ (springAt 19, Tick)
, (springAt 20, Tick)
]
services result
`shouldBe` [ [], [activateScene "scene.kasvivalo_iltatila"] ]
it "does not activate Growth in Summer" $ do
let result = runHASSTimed livingroomPlantLights
[ (summerAt 9, Tick)
, (summerAt 10, Tick)
]
services result `shouldBe` [ [], [] ]
+8
View File
@@ -6,9 +6,13 @@ import qualified AFRPSpec
import qualified BedroomSpec
import qualified BusSpec
import qualified ConnectionSpec
import qualified FlagsSpec
import qualified GraphingSpec
import qualified KitchenSpec
import qualified LivingroomSpec
import qualified MetricsSpec
import qualified RuntimeSpec
import qualified ControllerSpec
main :: IO ()
main = hspec $ do
@@ -17,6 +21,10 @@ main = hspec $ do
BedroomSpec.spec
BusSpec.spec
ConnectionSpec.spec
FlagsSpec.spec
GraphingSpec.spec
KitchenSpec.spec
LivingroomSpec.spec
MetricsSpec.spec
RuntimeSpec.spec
ControllerSpec.spec
+20 -2
View File
@@ -4,23 +4,27 @@ module Support
( Acc(..)
, interp
, runHASS
, runHASSTimed
, services
, fakeRequest
, sec
, stateEvent
, buttonEvent
, withTestLogEnv
) where
import Control.Exception (bracket)
import Control.Monad.Fix (MonadFix (..))
import Data.Aeson (Value, object, (.=))
import Katip (LogEnv, closeScribes, initLogEnv)
import qualified Data.Text as T
import Data.Time (UTCTime (..), utc)
import Data.UUID (nil)
import AFRP (Mealy (..), Request (..), stepAuto)
import AFRP (Mealy (..), Request (..), stepAuto, Event (..))
import HomeAssistant.Controller (HASSEff (..), Service)
fakeRequest :: Request
fakeRequest = Request (sec 0) utc nil
fakeRequest = Request (sec 0) utc nil "test"
sec :: Integer -> UTCTime
sec n = UTCTime (toEnum 0) (fromIntegral n)
@@ -41,6 +45,10 @@ instance Monad Acc where
instance MonadFix Acc where
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.
interp :: HASSEff a -> Acc a
interp (CallService _ svc) = Acc $ \s -> ((), s ++ [svc])
@@ -56,6 +64,16 @@ runHASS m = go (runMealy m interp)
case runAcc (stepAuto w fakeRequest a) [] of
((b, w'), svcs) -> (b, svcs) : go w' as
-- | Run a HASS arrow over a list of (time, input) pairs, collecting per-step
-- emitted services. Each step uses a fresh Request with the given UTCTime.
runHASSTimed :: Mealy HASSEff (Event a) b -> [(UTCTime, Event a)] -> [(b, [Service])]
runHASSTimed m = go (runMealy m interp)
where
go _ [] = []
go w ((t, a) : as) =
case runAcc (stepAuto w (Request t utc nil "test") a) [] of
((b, w'), svcs) -> (b, svcs) : go w' as
services :: [(b, [Service])] -> [[Service]]
services = map snd