16 Commits
Author SHA1 Message Date
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 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 7fc07c1883 Plant lights 2026-09-25 10:31:06 +03:00
MasseR a7becaf2d4 Use scenes instead of stateful applications of adaptive sleep mode 2026-09-25 09:55:48 +03:00
21 changed files with 460 additions and 105 deletions

No files matched your search

+1
View File
@@ -10,3 +10,4 @@ docs/superpowers
*.eventlog *.eventlog
*.eventlog.html *.eventlog.html
*.rrd *.rrd
*.rrd.*bak*
+5 -1
View File
@@ -1,3 +1,7 @@
creation_rules: creation_rules:
- path_regex: "secrets.yaml" - path_regex: "secrets.yaml"
pgp: "95DBE64C2EA64D6B0E0C8C2F9DE6E04ED1918118" age:
# usb-c yubikey
- "age1yubikey1qw7m7rad6malegqypgntr7qmu97xrxxurp0c00s23263nuxnpek6w0jye60"
# usb-a yubikey
- "age1yubikey1qdnx7jum6k4fzenkqj8y5met9hyq6lqxrpzrl2788wr0q445vhupzuqtpk0"
+7 -7
View File
@@ -1,8 +1,8 @@
{ mkDerivation, aeson, annotated-exception, async, base, bytestring { mkDerivation, aeson, annotated-exception, async, base, bytestring
, cereal, cereal-conduit, conduit, containers, directory, ekg-core , cereal, cereal-conduit, conduit, containers, directory, ekg-core
, exceptions, filepath, hedgehog, hspec, hspec-hedgehog, http-types , exceptions, filepath, hedgehog, hspec, hspec-hedgehog, http-media
, katip, lens, lens-aeson, lib, network, process, retry, scotty , http-types, katip, lens, lens-aeson, lib, network, process, retry
, servant, servant-server, stm, text, time, unliftio , servant, servant-server, stm, temporary, text, time, unliftio
, unordered-containers, uuid, wai, warp, websockets , unordered-containers, uuid, wai, warp, websockets
}: }:
mkDerivation { mkDerivation {
@@ -14,15 +14,15 @@ mkDerivation {
libraryHaskellDepends = [ libraryHaskellDepends = [
aeson annotated-exception async base bytestring cereal aeson annotated-exception async base bytestring cereal
cereal-conduit conduit containers directory ekg-core exceptions cereal-conduit conduit containers directory ekg-core exceptions
filepath http-types katip lens lens-aeson network process retry filepath http-media http-types katip lens lens-aeson network
scotty servant servant-server stm text time unliftio process retry servant servant-server stm text time unliftio
unordered-containers uuid wai warp websockets unordered-containers uuid wai warp websockets
]; ];
executableHaskellDepends = [ base ]; executableHaskellDepends = [ base ];
testHaskellDepends = [ testHaskellDepends = [
aeson annotated-exception async base bytestring cereal containers aeson annotated-exception async base bytestring cereal containers
directory ekg-core hedgehog hspec hspec-hedgehog katip process stm directory ekg-core hedgehog hspec hspec-hedgehog katip process
text time unordered-containers uuid servant stm temporary text time unordered-containers uuid
]; ];
license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause"; license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause";
mainProgram = "home-assistant-controller"; mainProgram = "home-assistant-controller";
+6 -1
View File
@@ -70,6 +70,7 @@ library
, HomeAssistant.Runtime , HomeAssistant.Runtime
, HomeAssistant.Runtime.Bus , HomeAssistant.Runtime.Bus
, HomeAssistant.Runtime.Connection , HomeAssistant.Runtime.Connection
, HomeAssistant.Runtime.Flags
, HomeAssistant.Runtime.Graphing , HomeAssistant.Runtime.Graphing
, HomeAssistant.Runtime.Metrics , HomeAssistant.Runtime.Metrics
, HomeAssistant.Runtime.Supervisor , HomeAssistant.Runtime.Supervisor
@@ -161,7 +162,10 @@ test-suite home-assistant-controller-test
, BedroomSpec , BedroomSpec
, BusSpec , BusSpec
, ConnectionSpec , ConnectionSpec
, FlagsSpec
, GraphingSpec , GraphingSpec
, KitchenSpec
, LivingroomSpec
, MetricsSpec , MetricsSpec
, RuntimeSpec , RuntimeSpec
, Support , Support
@@ -200,4 +204,5 @@ test-suite home-assistant-controller-test
ekg-core, ekg-core,
unordered-containers, unordered-containers,
process, 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_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] HA_HOST: ENC[AES256_GCM,data:MfA+RReJHnKP31bD4YAoZrc=,iv:Z9xDtzPsUER4jQ12BbM2EtnLNggZhOWzCb7VAL2I02g=,tag:/Eogbd2kT7phdhaR/vGNDA==,type:str]
sops: 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" 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] 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 unencrypted_suffix: _unencrypted
version: 3.13.3 version: 3.13.3
+1
View File
@@ -106,6 +106,7 @@ data Request = Request
{ requestTime :: !UTCTime { requestTime :: !UTCTime
, requestTimeZone :: !TimeZone , requestTimeZone :: !TimeZone
, requestTraceId :: !UUID , requestTraceId :: !UUID
, requestHandler :: !T.Text
} deriving (Show, Eq) } deriving (Show, Eq)
+1 -30
View File
@@ -56,19 +56,12 @@ bedroomPresenceController = proc x -> do
Event LightsOff -> do Event LightsOff -> do
callService (light bedroomLights Off) -< () callService (light bedroomLights Off) -< ()
Event LightsOn -> do Event LightsOn -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_lights_snapshot") -< () callService (activateScene "scene.makuuhuone_lights_snapshot") -< ()
Event LightsSleep -> do Event LightsSleep -> do
callService createBedroomScene -< () callService createBedroomScene -< ()
adaptiveMode -< True callService (activateScene "scene.makuuhuone_lepotila") -< ()
sleepMode -< True
_ -> returnA -< () _ -> returnA -< ()
where
sleepMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot_sleep_mode"] )
adaptiveMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot"] )
data BedroomControls data BedroomControls
= Masse (IkeaButton IkeaGesture) = Masse (IkeaButton IkeaGesture)
@@ -91,44 +84,22 @@ bedroomButtonController = proc x -> do
-- Any event will cause the sleep mode to be turned off -- Any event will cause the sleep mode to be turned off
case ev of case ev of
Event (Masse (OnButton ShortRelease)) -> do Event (Masse (OnButton ShortRelease)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_masse") -< () callService (activateScene "scene.makuuhuone_masse") -< ()
Event (Masse (OnButton DoubleClick)) -> do Event (Masse (OnButton DoubleClick)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_keski") -< () callService (activateScene "scene.makuuhuone_keski") -< ()
Event (Masse (OnButton LongClick)) -> do Event (Masse (OnButton LongClick)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_kirkas") -< () callService (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Masse (OffButton _)) -> do Event (Masse (OffButton _)) -> do
sleepMode -< False
adaptiveMode -< False
callService (light [AreaId "makuuhuone"] Off) -< () callService (light [AreaId "makuuhuone"] Off) -< ()
Event (Enishen (OnButton ShortRelease)) -> do Event (Enishen (OnButton ShortRelease)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_jemina") -< () callService (activateScene "scene.makuuhuone_jemina") -< ()
Event (Enishen (OnButton DoubleClick)) -> do Event (Enishen (OnButton DoubleClick)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_keski") -< () callService (activateScene "scene.makuuhuone_keski") -< ()
Event (Enishen (OnButton LongClick)) -> do Event (Enishen (OnButton LongClick)) -> do
sleepMode -< False
adaptiveMode -< False
callService (activateScene "scene.makuuhuone_kirkas") -< () callService (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Enishen (OffButton _)) -> do Event (Enishen (OffButton _)) -> do
sleepMode -< False
adaptiveMode -< False
callService (light [AreaId "makuuhuone"] Off) -< () callService (light [AreaId "makuuhuone"] Off) -< ()
Event (Central _) -> do
sleepMode -< False
adaptiveMode -< False
_ -> returnA -< () _ -> returnA -< ()
where
sleepMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot_sleep_mode"] )
adaptiveMode = callServiceDyn (switch [EntityId "switch.adaptive_lighting_makuuhuoneen_valot"] )
-1
View File
@@ -49,7 +49,6 @@ timersOff =
, day 3 <> at (08,15) , day 3 <> at (08,15)
, day 4 <> at (08,15) , day 4 <> at (08,15)
, day 5 <> at (08,15) , day 5 <> at (08,15)
, at (18,57) -- debug
] ]
where where
dayOfWeek = snd . mondayStartWeek . localDay dayOfWeek = snd . mondayStartWeek . localDay
+50 -1
View File
@@ -2,12 +2,13 @@
{-# LANGUAGE Arrows #-} {-# LANGUAGE Arrows #-}
module HomeAssistant.Controller.Livingroom where module HomeAssistant.Controller.Livingroom where
import HomeAssistant.Controller (HASS, Presence (..), Target (..), presence, callServiceDyn, light, Light (..), traceEvent) import HomeAssistant.Controller (HASS, Presence (..), Target (..), presence, callServiceDyn, light, Light (..), traceEvent, callService, activateScene)
import qualified AFRP import qualified AFRP
import Control.Arrow ((>>>), Arrow (..), returnA) import Control.Arrow ((>>>), Arrow (..), returnA)
import Data.Aeson (Value) import Data.Aeson (Value)
import Prelude hiding ((.)) import Prelude hiding ((.))
import Control.Category ((.)) import Control.Category ((.))
import Data.Time (LocalTime(..), toGregorian, TimeOfDay (..))
data Lights = LightsOn | LightsOff data Lights = LightsOn | LightsOff
deriving (Show) deriving (Show)
@@ -49,3 +50,51 @@ livingroomPresenceController = proc x -> do
AFRP.Event LightsOff -> callServiceDyn (light lights) -< Off AFRP.Event LightsOff -> callServiceDyn (light lights) -< Off
_ -> returnA -< () _ -> returnA -< ()
returnA -< () returnA -< ()
data Season = Summer | Fall | Winter | Spring
deriving Show
season :: HASS a Season
season = AFRP.currentTime >>> arr toSeason
where
toSeason t =
case toGregorian (localDay t) of
(_, m, _)
| m >= 12 || m <= 2 -> Winter
| m <= 5 -> Spring
| m <= 8 -> Summer
| otherwise -> Fall
tod :: HASS a TimeOfDay
tod = AFRP.currentTime >>> arr localTimeOfDay
data PlantLightMode = Growth | Ambience
deriving Show
plantLightMode :: HASS (Season, TimeOfDay) (AFRP.Event PlantLightMode)
plantLightMode =
(lightMode &&& ambienceMode) >>> arr (uncurry AFRP.lMerge)
where
lightMode = arr (uncurry lightWanted) >>> AFRP.edge >>> arr (AFRP.tag Growth)
ambienceMode = arr (uncurry ambienceWanted) >>> AFRP.edge >>> arr (AFRP.tag Ambience)
-- Full brightness during daytime only non-summer
lightWanted :: Season -> TimeOfDay -> Bool
lightWanted Summer _ = False
lightWanted _ TimeOfDay{todHour=10,todMin=00} = True
lightWanted _ _ = False
-- Ambience mode is always
ambienceWanted :: Season -> TimeOfDay -> Bool
ambienceWanted _ TimeOfDay{todHour=20,todMin=0} = True
ambienceWanted _ _ = False
livingroomPlantLights :: HASS (AFRP.Event a) ()
livingroomPlantLights = (season &&& tod)
>>> plantLightMode
>>> setLights
where
setLights = proc mode -> do
case mode of
AFRP.Event Growth -> callService (activateScene "scene.olohuoneen_kasvivalo") -< ()
AFRP.Event Ambience -> callService (activateScene "scene.kasvivalo_iltatila") -< ()
_ -> returnA -< ()
+26 -23
View File
@@ -21,6 +21,7 @@ import Data.Time (getCurrentTime, getCurrentTimeZone)
import Data.Void (Void) import Data.Void (Void)
import HomeAssistant.Controller (HASS, HASSEff (..)) import HomeAssistant.Controller (HASS, HASSEff (..))
import HomeAssistant.Runtime.Bus import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (loadFlags)
import HomeAssistant.Runtime.Connection (writerAction, readerAction) import HomeAssistant.Runtime.Connection (writerAction, readerAction)
import Network.Socket (withSocketsDo) import Network.Socket (withSocketsDo)
import System.Environment (getEnv, lookupEnv) import System.Environment (getEnv, lookupEnv)
@@ -36,40 +37,41 @@ import qualified HomeAssistant.Runtime.Metrics
import System.FilePath ((</>)) import System.FilePath ((</>))
import Text.Read (readMaybe) import Text.Read (readMaybe)
import HomeAssistant.Controller.Kitchen (kitchenMotionController) import HomeAssistant.Controller.Kitchen (kitchenMotionController)
import HomeAssistant.Controller.Livingroom (livingroomPresenceController) import HomeAssistant.Controller.Livingroom (livingroomPresenceController, livingroomPlantLights)
import HomeAssistant.Runtime.RateLimit (slidingWindowLimiter, registerRateLimitMetrics) import HomeAssistant.Runtime.RateLimit (slidingWindowLimiter, registerRateLimitMetrics)
import UnliftIO.Async import UnliftIO.Async
import HomeAssistant.Runtime.Supervisor (supervised) import HomeAssistant.Runtime.Supervisor (supervised)
import HomeAssistant.Controller.Hallway (hallwayLightsController) import HomeAssistant.Controller.Hallway (hallwayLightsController)
import qualified HttpServer import qualified HttpServer
step :: (MonadIO m) => FilePath -> UUID -> Auto m a b -> a -> m (b, Auto m a b) step :: (MonadIO m) => FilePath -> T.Text -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
step path trace st a = do step path name trace st a = do
now <- liftIO getCurrentTime now <- liftIO getCurrentTime
tz <- liftIO getCurrentTimeZone tz <- liftIO getCurrentTimeZone
let req = Request now tz trace let req = Request now tz trace name
stepAutoSerializing path st req a 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]
controllers = controllers =
[ Controller True "bedroom-presence" bedroomPresenceController [ Controller "bedroom-presence" bedroomPresenceController
, Controller True "bedroom-button" bedroomButtonController , Controller "bedroom-button" bedroomButtonController
, Controller True "bedroom-drawer" bedroomDrawerController , Controller "bedroom-drawer" bedroomDrawerController
, Controller True "bedroom-humidifier" humidifierController , Controller "bedroom-humidifier" humidifierController
, Controller True "school-light-controller" schoolLightController , Controller "school-light-controller" schoolLightController
, Controller True "kitchen-motion-controller" kitchenMotionController , Controller "kitchen-motion-controller" kitchenMotionController
, Controller True "livingroom-presence" livingroomPresenceController , Controller "livingroom-presence" livingroomPresenceController
, Controller True "hallway-motion-controller" hallwayLightsController , Controller "hallway-motion-controller" hallwayLightsController
, Controller True "children-button" childrenBedroomButtonController , Controller "children-button" childrenBedroomButtonController
, Controller "livingroom-plants" livingroomPlantLights
] ]
-- | Steps the machine for every inbound message; service calls go to the -- | Steps the machine for every inbound message; service calls go to the
-- bus. A restart re-dups the inbound channel and starts from the machine's -- bus. A restart re-dups the inbound channel and starts from the machine's
-- initial state; messages broadcast during the restart window are lost. -- initial state; messages broadcast during the restart window are lost.
runController :: MonadIO m => FilePath -> Bus -> Controller -> m Void runController :: MonadIO m => FilePath -> Bus -> Controller -> m Void
runController rootDir bus (Controller _enabled name machine ) = liftIO $ do runController rootDir bus (Controller name machine ) = liftIO $ do
inbound <- atomically (dupTChan (busInbound bus)) inbound <- atomically (dupTChan (busInbound bus))
let ns = Namespace [name] let ns = Namespace [name]
let workerDefinition = runMealy machine (runKatipContextT (busLogEnv bus) () ns . channelHassEval bus) let workerDefinition = runMealy machine (runKatipContextT (busLogEnv bus) () ns . channelHassEval bus)
@@ -82,7 +84,7 @@ runController rootDir bus (Controller _enabled name machine ) = liftIO $ do
go path inbound f = do go path inbound f = do
msg <- atomically (readTChan inbound) msg <- atomically (readTChan inbound)
uuid <- UUID.V4.nextRandom uuid <- UUID.V4.nextRandom
(_, next) <- step path uuid f msg (_, next) <- step path name uuid f msg
go path inbound next go path inbound next
lookupPort :: IO Int lookupPort :: IO Int
@@ -101,22 +103,23 @@ defaultMain = withSocketsDo $ do
System.Metrics.registerGcMetrics store System.Metrics.registerGcMetrics store
appMetrics <- HomeAssistant.Runtime.Metrics.registerAppMetrics store appMetrics <- HomeAssistant.Runtime.Metrics.registerAppMetrics store
rateLimitMetrics <- registerRateLimitMetrics store rateLimitMetrics <- registerRateLimitMetrics store
withBus severity appMetrics $ \bus -> do rootPath <- fromMaybe "/tmp/" <$> lookupEnv "HA_LIB_DIR"
let allNames = map (\(Controller n _) -> n) controllers
flags <- loadFlags rootPath allNames
withBus severity appMetrics flags $ \bus -> do
token <- getEnv "HA_TOKEN" token <- getEnv "HA_TOKEN"
host <- getEnv "HA_HOST" host <- getEnv "HA_HOST"
rootPath <- fromMaybe "/tmp/" <$> lookupEnv "HA_LIB_DIR" let rrdPath = rootPath </> "hass-controller.rrd"
rrdPath <- fromMaybe "hass-controller.rrd" <$> lookupEnv "HA_RRD_PATH"
rrdtool <- fromMaybe "rrdtool" <$> lookupEnv "HA_RRDTOOL" rrdtool <- fromMaybe "rrdtool" <$> lookupEnv "HA_RRDTOOL"
metricsPort <- lookupPort metricsPort <- lookupPort
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20 writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
let active = [c | c@(Controller True _ _) <- controllers] let ents = foldMap (\(Controller _ m) -> entities m) controllers
ents = foldMap (\(Controller _ _ m) -> entities m) active
workers = workers =
[ ("reader", readerAction host 8123 token ents bus) [ ("reader", readerAction host 8123 token ents bus)
, ("writer", writerAction writerLimiter bus) , ("writer", writerAction writerLimiter bus)
, ("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool) , ("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool)
, ("metrics-http", HttpServer.runHttpServer (busLogEnv bus) rrdPath rrdtool metricsPort) , ("metrics-http", HttpServer.runHttpServer (busLogEnv bus) rrdPath rrdtool (busFlags bus) metricsPort)
] ++ [ (name, runController rootPath bus c) | c@(Controller True name _) <- active ] ] ++ [ (name, runController rootPath bus c) | c@(Controller name _) <- controllers ]
runKatipContextT (busLogEnv bus) () mempty $ runKatipContextT (busLogEnv bus) () mempty $
mapConcurrently_ (uncurry supervised) workers mapConcurrently_ (uncurry supervised) workers
+8 -3
View File
@@ -31,7 +31,9 @@ import System.IO (stdout)
import System.Metrics.Counter (inc) import System.Metrics.Counter (inc)
import Data.UUID (toText) import Data.UUID (toText)
import AFRP (Request(..), Event(..)) import AFRP (Request(..), Event(..))
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.IO.Class (MonadIO, liftIO)
import HomeAssistant.Runtime.Flags (Flags, isEnabled)
-- | Shared runtime state: inbound is a broadcast channel (controllers -- | Shared runtime state: inbound is a broadcast channel (controllers
-- read from 'dupTChan' copies), outbound queues service calls for the -- read from 'dupTChan' copies), outbound queues service calls for the
@@ -43,10 +45,11 @@ data Bus = Bus
, busGen :: CallIdGen , busGen :: CallIdGen
, busLogEnv :: LogEnv , busLogEnv :: LogEnv
, busMetrics :: AppMetrics , busMetrics :: AppMetrics
, busFlags :: Flags
} }
withBus :: Severity -> AppMetrics -> (Bus -> IO a) -> IO a withBus :: Severity -> AppMetrics -> Flags -> (Bus -> IO a) -> IO a
withBus severity metrics callback = do withBus severity metrics flags callback = do
handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem severity) V2 handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem severity) V2
let makeLogEnv = registerScribe "stdout" handleScribe defaultScribeSettings =<< initLogEnv "hass-controller" "production" let makeLogEnv = registerScribe "stdout" handleScribe defaultScribeSettings =<< initLogEnv "hass-controller" "production"
-- closeScribes will stop accepting new logs, flush existing ones and clean up resources -- closeScribes will stop accepting new logs, flush existing ones and clean up resources
@@ -58,6 +61,7 @@ withBus severity metrics callback = do
<*> mkCallIdGen 0 <*> mkCallIdGen 0
<*> pure le <*> pure le
<*> pure metrics <*> pure metrics
<*> pure flags
callback bus callback bus
recordInbound :: Bus -> IO () recordInbound :: Bus -> IO ()
@@ -70,7 +74,8 @@ channelHassEval :: (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a
channelHassEval bus = \case channelHassEval bus = \case
CallService req svc -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ do CallService req svc -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ do
logFM DebugS (ls $ show svc) logFM DebugS (ls $ show svc)
liftIO $ atomically $ writeTChan (busOutbound bus) (req, svc) enabled <- isEnabled (busFlags bus) (requestHandler req)
when enabled $ liftIO $ atomically $ writeTChan (busOutbound bus) (req, svc)
Debug x -> logFM DebugS (ls $ show x) Debug x -> logFM DebugS (ls $ show x)
Trace req x -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ Trace req x -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $
logFM InfoS (ls $ show x) logFM InfoS (ls $ show x)
+90
View File
@@ -0,0 +1,90 @@
{-# 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.Exception (IOException, handle)
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 (hPutStrLn, stderr)
import System.IO.Error (isDoesNotExistError)
type Name = Text
data Flags = Flags
{ flagsState :: TVar (Map Name Bool)
, flagsLock :: MVar ()
, flagsPath :: FilePath
, flagsValidNames :: Set Text
}
loadFlags :: MonadIO m => FilePath -> [Name] -> m Flags
loadFlags rootPath allNames = liftIO $ do
let path = rootPath </> "handlers.json"
fileMap <- readFlagsFile path
let defaults = M.fromList [(n, True) | n <- allNames]
initial = M.unionWith (\fileVal _default -> fileVal) fileMap defaults
tv <- newTVarIO initial
lock <- newMVar ()
pure Flags
{ flagsState = tv
, flagsLock = lock
, flagsPath = path
, flagsValidNames = S.fromList allNames
}
readFlagsFile :: FilePath -> IO (Map Name Bool)
readFlagsFile path =
handle onMissingOrUnreadable $ do
decoded <- decodeFileStrict' path
case decoded of
Nothing -> do
hPutStrLn stderr ("handlers.json is unparseable; treating all handlers as enabled: " <> path)
pure mempty
Just m -> pure (maybe mempty id m)
where
onMissingOrUnreadable :: IOException -> IO (Map Name Bool)
onMissingOrUnreadable e
| isDoesNotExistError e = pure mempty
| otherwise = do
hPutStrLn stderr ("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
+32 -9
View File
@@ -7,13 +7,17 @@ import Control.Monad.IO.Class (liftIO, MonadIO)
import qualified Data.ByteString as BS import qualified Data.ByteString as BS
import Data.Void (Void) import Data.Void (Void)
import Network.Wai.Handler.Warp (run) import Network.Wai.Handler.Warp (run)
import Servant.API ((:>), Capture, Get, QueryParam, (:-), MimeRender (..), Accept (..), NamedRoutes) import Servant.API ((:>), Capture, Get, QueryParam, (:-), MimeRender (..), Accept (..), NamedRoutes, JSON, ReqBody, Put)
import Data.ByteString (ByteString) import Data.ByteString (ByteString)
import GHC.Generics (Generic) import GHC.Generics (Generic)
import Servant (Handler, err404) import Servant (Handler, err404)
import Control.Monad.Catch (throwM, MonadCatch, MonadThrow) import Control.Monad.Catch (throwM, catch, MonadCatch, MonadThrow, SomeException)
import Servant.Server (err500, ServerT) import Servant.Server (err500, ServerT)
import Data.Maybe (fromMaybe) 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 Control.Exception.Annotated (checkpoint, Annotation (Annotation))
import Servant.Server.Generic (genericServeT) import Servant.Server.Generic (genericServeT)
import Network.Wai (Application) import Network.Wai (Application)
@@ -30,12 +34,27 @@ instance Accept ImagePng where
contentType _ = "image" // "png" contentType _ = "image" // "png"
newtype API mode = API data API mode = API
{ getMetrics :: mode :- "metrics" :> Capture "graph" Graph :> QueryParam "range" Range :> Get '[ImagePng] ByteString { 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 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 :: FilePath -> FilePath -> Graph -> Maybe Range -> LoggingHandler ByteString
getMetricsHandler rrdPath rrdtool graphMode mRange = checkpoint (Annotation (graphMode, mRange)) $ do getMetricsHandler rrdPath rrdtool graphMode mRange = checkpoint (Annotation (graphMode, mRange)) $ do
case lookupGraph graphs graphMode of case lookupGraph graphs graphMode of
@@ -46,14 +65,18 @@ getMetricsHandler rrdPath rrdtool graphMode mRange = checkpoint (Annotation (gra
either (\e -> logFM ErrorS (ls e) >> throwM err500) pure g either (\e -> logFM ErrorS (ls e) >> throwM err500) pure g
-- server :: FilePath -> FilePath -> API AsServer -- server :: FilePath -> FilePath -> API AsServer
server :: FilePath -> FilePath -> ServerT (NamedRoutes API) LoggingHandler server :: FilePath -> FilePath -> Flags -> ServerT (NamedRoutes API) LoggingHandler
server rrdPath rrdtool = API { getMetrics = getMetricsHandler rrdPath rrdtool } server rrdPath rrdtool flags = API
{ getMetrics = getMetricsHandler rrdPath rrdtool
, getFlags = getFlagsHandler flags
, putFlag = putFlagHandler flags
}
servantApp :: LogEnv -> FilePath -> FilePath -> Application servantApp :: LogEnv -> FilePath -> FilePath -> Flags -> Application
servantApp le rrdPath rrdtool = genericServeT (toHandler le) (server rrdPath rrdtool) servantApp le rrdPath rrdtool flags = genericServeT (toHandler le) (server rrdPath rrdtool flags)
runHttpServer :: MonadIO m => LogEnv -> FilePath -> FilePath -> Int -> m Void runHttpServer :: MonadIO m => LogEnv -> FilePath -> FilePath -> Flags -> Int -> m Void
runHttpServer le rrdPath rrdtool port = liftIO $ forever $ run port (servantApp le rrdPath rrdtool) runHttpServer le rrdPath rrdtool flags port = liftIO $ forever $ run port (servantApp le rrdPath rrdtool flags)
newtype LoggingHandler a = LoggingHandler (KatipContextT Handler a) newtype LoggingHandler a = LoggingHandler (KatipContextT Handler a)
deriving (Functor, Applicative, Monad, MonadIO, Katip, KatipContext, MonadCatch, MonadThrow) via (KatipContextT Handler) deriving (Functor, Applicative, Monad, MonadIO, Katip, KatipContext, MonadCatch, MonadThrow) via (KatipContextT Handler)
+2 -2
View File
@@ -21,7 +21,7 @@ import Test.Hspec
import Test.Hspec.Hedgehog import Test.Hspec.Hedgehog
fakeRequest :: Request fakeRequest :: Request
fakeRequest = Request (sec 0) utc nil fakeRequest = Request (sec 0) utc nil "test"
sec :: Integer -> UTCTime sec :: Integer -> UTCTime
sec n = UTCTime (toEnum 0) (fromIntegral n) sec n = UTCTime (toEnum 0) (fromIntegral n)
@@ -42,7 +42,7 @@ runTimed m = go (runMealy m id)
where where
go _ [] = [] go _ [] = []
go w ((s, a) : as) = 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 (b, w') -> b : go w' as
-- | A minimal State monad for observing effectful arrows (e.g. whenA gating). -- | A minimal State monad for observing effectful arrows (e.g. whenA gating).
+27 -3
View File
@@ -6,6 +6,7 @@ import AFRP (Request (..), Event (..))
import Control.Concurrent.STM import Control.Concurrent.STM
( atomically ( atomically
, dupTChan , dupTChan
, isEmptyTChan
, readTChan , readTChan
, writeTChan , writeTChan
) )
@@ -15,9 +16,11 @@ import Data.Time (UTCTime (..), utc)
import Data.UUID (nil) import Data.UUID (nil)
import HomeAssistant.Controller (HASSEff (..), Service (..), Target(..)) import HomeAssistant.Controller (HASSEff (..), Service (..), Target(..))
import HomeAssistant.Runtime.Bus import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
import HomeAssistant.Runtime.Metrics (registerAppMetrics) import HomeAssistant.Runtime.Metrics (registerAppMetrics)
import Katip (Namespace (Namespace), runKatipContextT, Severity (..)) import Katip (Namespace (Namespace), runKatipContextT, Severity (..))
import qualified System.Metrics as Metrics import qualified System.Metrics as Metrics
import System.IO.Temp (withTempDirectory)
import Test.Hspec import Test.Hspec
spec :: Spec spec :: Spec
@@ -33,13 +36,22 @@ spec = describe "Bus" $ do
r2 `shouldBe` (Event (Number 1), Event (Number 2)) r2 `shouldBe` (Event (Number 1), Event (Number 2))
it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do
let req = Request (UTCTime (toEnum 0) 0) utc nil let req = Request (UTCTime (toEnum 0) 0) utc nil "test"
svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"] svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"]
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $ runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
channelHassEval bus (CallService req svc) channelHassEval bus (CallService req svc)
(_, svc') <- atomically $ readTChan (busOutbound bus) (_, svc') <- atomically $ readTChan (busOutbound bus)
svc' `shouldBe` svc svc' `shouldBe` svc
it "channelHassEval drops CallService 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)
atomically (isEmptyTChan (busOutbound bus)) `shouldReturn` True
it "generates unique sequential call ids" $ do it "generates unique sequential call ids" $ do
gen <- mkCallIdGen 0 gen <- mkCallIdGen 0
@@ -51,7 +63,9 @@ spec = describe "Bus" $ do
it "increments the trigger and service counters" $ do it "increments the trigger and service counters" $ do
store <- Metrics.newStore store <- Metrics.newStore
m <- registerAppMetrics store m <- registerAppMetrics store
withBus InfoS m $ \bus -> do withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- loadFlags dir []
withBus InfoS m flags $ \bus -> do
recordInbound bus recordInbound bus
recordInbound bus recordInbound bus
recordOutbound bus recordOutbound bus
@@ -63,4 +77,14 @@ withTestBus :: (Bus -> IO a) -> IO a
withTestBus action = do withTestBus action = do
store <- Metrics.newStore store <- Metrics.newStore
m <- registerAppMetrics store m <- registerAppMetrics store
withBus InfoS m action withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- loadFlags dir []
withBus InfoS m flags action
withTestFlagsBus :: (Bus -> IO a) -> IO a
withTestFlagsBus action = do
store <- Metrics.newStore
m <- registerAppMetrics store
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- loadFlags dir ["test-handler"]
withBus InfoS m flags action
+1 -1
View File
@@ -47,7 +47,7 @@ spec = do
req :: Int -> Request req :: Int -> Request
req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
(fromJust (fromString uuid)) (fromJust (fromString uuid)) "test"
where where
pad i = replicate (12 - length (show i)) '0' <> show i pad i = replicate (12 - length (show i)) '0' <> show i
uuid = "00000000-0000-0000-0000-" <> pad n uuid = "00000000-0000-0000-0000-" <> pad n
+75
View File
@@ -0,0 +1,75 @@
{-# 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 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 <- 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 <- 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 <- 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 <- loadFlags dir ["a"]
isEnabled flags "a" `shouldReturn` False
it "defaults unknown names to True" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- 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 <- loadFlags dir ["a"]
setEnabled flags "a" False
isEnabled flags "a" `shouldReturn` False
-- reload from disk to confirm persistence
flags' <- 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 <- 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
+45
View File
@@ -0,0 +1,45 @@
{-# 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
-- 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` [[switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] (On Nothing)]]
it "turns lights off when presence is unoccupied" $ do
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "off"])
`shouldBe` [[switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], []]
it "does nothing on Tick" $ do
services (runHASS dinnerTableController [Tick])
`shouldBe` [[switch [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` [ [], [] ]
+6
View File
@@ -6,7 +6,10 @@ import qualified AFRPSpec
import qualified BedroomSpec import qualified BedroomSpec
import qualified BusSpec import qualified BusSpec
import qualified ConnectionSpec import qualified ConnectionSpec
import qualified FlagsSpec
import qualified GraphingSpec import qualified GraphingSpec
import qualified KitchenSpec
import qualified LivingroomSpec
import qualified MetricsSpec import qualified MetricsSpec
import qualified RuntimeSpec import qualified RuntimeSpec
@@ -17,6 +20,9 @@ main = hspec $ do
BedroomSpec.spec BedroomSpec.spec
BusSpec.spec BusSpec.spec
ConnectionSpec.spec ConnectionSpec.spec
FlagsSpec.spec
GraphingSpec.spec GraphingSpec.spec
KitchenSpec.spec
LivingroomSpec.spec
MetricsSpec.spec MetricsSpec.spec
RuntimeSpec.spec RuntimeSpec.spec
+13 -2
View File
@@ -4,6 +4,7 @@ module Support
( Acc(..) ( Acc(..)
, interp , interp
, runHASS , runHASS
, runHASSTimed
, services , services
, fakeRequest , fakeRequest
, sec , sec
@@ -16,11 +17,11 @@ import Data.Aeson (Value, object, (.=))
import qualified Data.Text as T import qualified Data.Text as T
import Data.Time (UTCTime (..), utc) import Data.Time (UTCTime (..), utc)
import Data.UUID (nil) import Data.UUID (nil)
import AFRP (Mealy (..), Request (..), stepAuto) import AFRP (Mealy (..), Request (..), stepAuto, Event (..))
import HomeAssistant.Controller (HASSEff (..), Service) import HomeAssistant.Controller (HASSEff (..), Service)
fakeRequest :: Request fakeRequest :: Request
fakeRequest = Request (sec 0) utc nil fakeRequest = Request (sec 0) utc nil "test"
sec :: Integer -> UTCTime sec :: Integer -> UTCTime
sec n = UTCTime (toEnum 0) (fromIntegral n) sec n = UTCTime (toEnum 0) (fromIntegral n)
@@ -56,6 +57,16 @@ runHASS m = go (runMealy m interp)
case runAcc (stepAuto w fakeRequest a) [] of case runAcc (stepAuto w fakeRequest a) [] of
((b, w'), svcs) -> (b, svcs) : go w' as ((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 :: [(b, [Service])] -> [[Service]]
services = map snd services = map snd